{ // 获取包含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\nCSS \n .container {\n width: 960px;\n color: gray;\n}\n\n/* Header */\n\n.header {\n background-color: rgba(255, 255, 255, 0.95);\n border-bottom: 1px solid #ddd;\n\n font-family: 'Oswald', sans-serif;\n font-weight: 300;\n\n font-size: 17px;\n padding: 15px;\n}\n\n/* Menu */ \n\n.header .menu {\n float: right;\n list-style: none;\n margin-top: 5px;\n}\n\n.menu > li {\n display: inline;\n padding-left: 20px;\n padding-right: 20px;\n}\n\n.menu a {\n color: #898989;\n}\n\n/* Dropdown */\n\n.dropdown-menu {\n font-size: 16px;\n margin-top: 5px;\n min-width: 105px;\n}\n\n.dropdown-menu li a {\n color: #898989;\n padding: 6px 20px;\n font-weight: 300;\n}\n\n/* Carousel */\n\n.slider {\n position: relative;\n width: 100%;\n height: 470px;\n border-bottom: 1px solid #ddd;\n}\n\n.slide {\n background: transparent url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/feature-gradient-transparent.png') center center no-repeat;\n background-size: cover;\n display: none;\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n}\n .slide {\n text-align: center;\n height: 550px;\n }\n\n #nyce-slide{\n background-image: url('nsce.jpg');\n } \n #pharm-slide-feature{\n background-image: url('pharm.jpg');\n } \n #mountain-slide-feature{\n background-image: url('mountain.jpg');\n } \n.active-slide {\n display: block;\n}\n\n.slide-copy h1 {\n color: #363636; \n\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 40px;\n margin-top: 105px;\n margin-bottom: 0px;\n}\n\n.slide-copy h2 {\n color: #b7b7b7;\n\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 40px;\n margin: 5px;\n}\n\n.slide-copy p {\n color: #959595;\n font-family: Georgia, \"Times New Roman\", serif;\n font-size: 1.15em;\n line-height: 1.75em;\n margin-bottom: 15px;\n margin-top: 16px;\n}\n\n.slide-img {\n text-align: right;\n}\n\n/* Slide feature */\n\n.slide-feature {\n text-align: center;\n background-image: url('http://devonsstudio.com/businesspeople.png');\n height: 550px;\n}\n\n.slide-feature img {\n margin-top: 112px;\n margin-bottom: 28px;\n}\n\n.slide-feature a {\n display: block;\n color: #6fc5e0;\n\n font-family: \"HelveticaNeueMdCn\", Helvetica, sans-serif;\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 20px;\n}\n.slide-feature p {\ncolor: red;\n}\n\n.slider-nav {\n text-align: center;\n margin-top: 80px;\n\n}\n\n.arrow-prev {\n margin-right: 45px;\n display: inline-block;\n vertical-align: top;\n margin-top: 9px;\n}\n\n.arrow-next {\n margin-left: 45px;\n display: inline-block;\n vertical-align: top;\n margin-top: 9px;\n}\n\n.slider-dots {\n list-style: none;\n display: inline-block;\n padding-left: 0;\n margin-bottom: 0;\n}\n\n.slider-dots li {\n color: #bbbcbc;\n display: inline;\n font-size: 30px;\n margin-right: 5px;\n}\n\n.slider-dots li.active-dot {\n color: #363636;\n}\n\n/* App links */\n\n.get-app {\n list-style: none;\n padding-bottom: 9px;\n padding-left: 0px;\n padding-top: 9px;\n}\n\n.get-app li {\n float: left;\n margin-bottom: 5px;\n margin-right: 5px;\n}\n\n.get-app img {\n height: 40px;\n}\n color: #898989;\n padding: 6px 20px;\n font-weight: 300;\n }\n\n /* Carousel */\n\n .slider {\n position: relative;\n width: 100%;\n height: 470px;\n border-bottom: 1px solid #ddd;\n }\n\n .slide {\n background: transparent url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/feature-gradient-transparent.png') center center no-repeat;\n background-size: cover;\n display: none;\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n\n .active-slide {\n display: block;\n }\n\n .slide-copy h1 {\n color: #363636; \n\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 40px;\n margin-top: 105px;\n margin-bottom: 0px;\n }\n\n .slide-copy h2 {\n color: #b7b7b7;\n\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 40px;\n margin: 5px;\n }\n\n .slide-copy p {\n color: #959595;\n font-family: Georgia, \"Times New Roman\", serif;\n font-size: 1.15em;\n line-height: 1.75em;\n margin-bottom: 15px;\n margin-top: 16px;\n }\n\n .slide-img {\n text-align: right;\n }\n\n /* Slide feature */\n\n .slide-feature {\n text-align: center;\n background-image: url('http://devonsstudio.com/businesspeople.png');\n height: 550px;\n }\n\n .slide-feature img {\n margin-top: 112px;\n margin-bottom: 28px;\n }\n\n .slide-feature a {\n display: block;\n color: #6fc5e0;\n\n font-family: \"HelveticaNeueMdCn\", Helvetica, sans-serif;\n font-family: 'Oswald', sans-serif;\n font-weight: 400;\n\n font-size: 20px;\n }\n .slide-feature p {\n color: red;\n }\n\n .slider-nav {\n text-align: center;\n margin-top: 80px;\n\n }\n\n .arrow-prev {\n margin-right: 45px;\n display: inline-block;\n vertical-align: top;\n margin-top: 9px;\n }\n\n .arrow-next {\n margin-left: 45px;\n display: inline-block;\n vertical-align: top;\n margin-top: 9px;\n }\n\n .slider-dots {\n list-style: none;\n display: inline-block;\n padding-left: 0;\n margin-bottom: 0;\n }\n\n .slider-dots li {\n color: #bbbcbc;\n display: inline;\n font-size: 30px;\n margin-right: 5px;\n }\n\n .slider-dots li.active-dot {\n color: #363636;\n }\n\n /* App links */\n\n .get-app {\n list-style: none;\n padding-bottom: 9px;\n padding-left: 0px;\n padding-top: 9px;\n }\n\n .get-app li {\n float: left;\n margin-bottom: 5px;\n margin-right: 5px;\n }\n\n .get-app img {\n height: 40px;\n }\n\nJAVASCRIPT\n var main = function() {\n $('.dropdown-toggle').click(function() {\n $('.dropdown-menu').toggle();\n });\n\n $('.arrow-next').click(function(e) {\n e.preventDefault();\n var currentSlide = $('.active-slide');\n var nextSlide = currentSlide.next();\n\n var currentDot = $('.active-dot');\n var nextDot = currentDot.next();\n\n if(nextSlide.length === 0) {\n nextSlide = $('.slide').first();\n nextDot = $('.dot').first();\n }\n\n currentSlide.fadeOut(600).removeClass('active-slide');\n nextSlide.fadeIn(600).addClass('active-slide');\n\n currentDot.removeClass('active-dot');\n nextDot.addClass('active-dot');\n });\n\n $('.arrow-prev').click(function(e) {\n e.preventDefault();\n var currentSlide = $('.active-slide');\n var prevSlide = currentSlide.prev();\n\n var currentDot = $('.active-dot');\n var prevDot = currentDot.prev();\n\n if(prevSlide.length === 0) {\n prevSlide = $('.slide').last();\n prevDot = $('.dot').last();\n }\n\n currentSlide.fadeOut(600).removeClass('active-slide');\n prevSlide.fadeIn(600).addClass('active-slide');\n\n currentDot.removeClass('active-dot');\n prevDot.addClass('active-dot');\n });\n\n}\n\n$(document).ready(main);\n\nA:\n\nHeres a DEMO FIDDLE (You only need to add your images URLS to the CSS)\nThe first thing you need to do is to add e.preventDefault(); to your click evennts like this:\n $('.arrow-next').click(function(e) {\n e.preventDefault();\n //..more code\n });\n\n $('.arrow-prev').click(function(e) {\n e.preventDefault();\n //..more code\n });\n\nThen you need to give each slide a unique ID and give it a background for the image, just like you have a background for the .slide-feature like this:\nHTML:\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n\nCSS:\n .slide {\n text-align: center;\n height: 550px;\n }\n\n #nyce-slide{\n background-image: url('nyce.jpg');\n } \n #mentor-slide{\n background-image: url('mentor.jpg');\n } \n #mountain-slide{\n background-image: url('mountain.jpg');\n } \n\nHeres the final edit:\n\n
\n
\n \n \n \n\n
\n
\n \n

NIDC Graduate Scheme

\n \n
CVS Health's Northern Ireland Development Centre, which opened in 2012,
\n creates software solutions for all parts of the US company,
\n with particular focus on internet and mobile applications.
\n\n \n
\n
\n
\n\n
\n\n
\n
\n
\n
\n

CVS is now hiring

\n

We will soon have a nice new building.

\n\n
    \n
  • \n
  • \n
  • \n
  • \n
\n
\n
\n
\n
\n\n
\n
\n
\n
\n

\n

\n

\n

\n

\n

\n

\n Accountability\n

Take responsibility for your actions.

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

Collaboration

\n

At CVS, it's important to work together with your mentor!

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

Tenacity

\n

Be determined.

\n\n
    \n
  • \n
  • \n
  • \n
  • \n
\n
\n
\n
\n
\n\n
\n\n
\n \n
    \n
  • •
  • \n
  • •
  • \n
  • •
  • \n
  • •
  • \n
\n \n
\n\n \n \n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29430,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can I retrieve all property values from a list of common objects?\n\nI want to retrieve all single properties from a collection as an array:\nclass Foo{\n public string Bar { get; set; }\n public string Baz { get; set;}\n}\n\nI want to get i.e. all Bar properties from the collection \nvar list = new List();\n\nstring[] allBars = list. .... \n\nand how does it go on???\nThanks for any help.\n\nA:\n\nYou can use:\nstring[] allBars = list.Select(foo => foo.Bar).ToArray();\n\nI would only convert this to an array if you specifically need it to be in an array. If your goal is just to output the \"Bar\" list, you could just do:\nvar allBars = list.Select(foo => foo.Bar); // Will produce IEnumerable\nforeach(var bar in allBars)\n{\n // Do something with bar\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29431,"cells":{"text":{"kind":"string","value":"Q:\n\nGet the full exception type/message and stack trace\n\nI've written an API which returns Json in the following format...\n{\"Success\": true, Result: {...}}\n\n{\"Success\": false, ExceptionId: \"(some uuid)\"}\n\nThe exceptions are logged. This is fine in principle for allowing someone to discuss an error without us ever telling them what it is (as a security measure). During debugging I also want to output the error message to stop me having to refer to a database all the time.\nAs things stand, the problem is getting useful information from the exception (either to return or log in the db)\nI'm doing something like this...\ntry:\n Ret['Result'] = \n Ret['Success'] = True\nexcept Exception as e:\n # ... Logging/ExceptionId\n if Settings.DebugMode: \n Ret['Exception'] = str(e)\n\nIf I put a breakpoint on the last line and inspect e in eclipse's watch window, I get KeyError: 'Something', but str(e) results in 'Something' which is very unhelpful.\nI've googled and I can't find any way to get a proper message from an exception. Apparently there used to be a .message in v<2.4 but that's no help to me in 3.3\nAs an alternative, I tried doing:\nRet['Exception'] = str(type(e)) + \": \" + str(e)\n\nWhich resulted in : 'job' which is a little closer but it's starting to feel more and more hackish.\nI also want to include a Stack Trace but have had even less luck there - I can get the __traceback__ but of course it's not serializable and calling str() on it just results in a description of the object eg \nHow can I get a decent/comprehensive error message?\n\nA:\n\nYou probably want repr:\nRet['Exception'] = repr(e)\n\nFor the traceback, use the traceback module:\nfrom traceback import format_exc\nRet['Traceback'] = format_exc()\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29432,"cells":{"text":{"kind":"string","value":"Q:\n\nSAS - How to filter by max value from one column in a datastep\n\nI have a yearly survey that I do some validations on. I only want to do the validations for the current year (max year in the column surveyYear). The survey comes every year so I want to have it automatised instead of writing the current year. So when the survey for 2019 comes I do not need to change the code.\nIs it possible to filter surveyYear in the set statement to only take the largest number in the column? I have tried different combinations but do not sucseed. And if it is not possible, how could I solve it otherwise\nI would also like to do it in a datastep and not in proc as the validation code comes in the want datastep after the set statement.\ndata have;\ninput surveyYear id score varChar$10. ;\ndatalines;\n2016 1 10 Yes\n2016 2 6 Yes\n2016 3 8 Yes\n2016 4 . No\n2017 5 6 No\n2017 6 5 No\n2017 7 12 IU\n2017 8 3 IU\n2017 9 2 IU\n2017 10 15 99999\n2018 11 0 .\n2018 12 . No\n2018 13 10 Yes\n2018 14 8 No\n2018 15 11 No\n2018 16 3 IU\n;\nrun; \n\ndata want;\nset have (where=(surveyYear > 2017));\n/* I would like to have something that states the max surveyYear instead */\n/* (where=(surveyYear = max(surveyYear))) */\nrun;\n\nA:\n\nTo filter for the max you can first get hte max and then apply a filter.\nproc sql noprint;\nselect max(year) into :latest_year from have;\nquit;\n\nThen use it in your filter.\ndata want;\nset have (where=(year=&latest_year.));\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29433,"cells":{"text":{"kind":"string","value":"Q:\n\nIn a RESTFul API, what's the correct http verb to a revert / rollback action?\n\nImagine a simple document management webservice strutured like this:\ndocument/ \n GET -> retrieves all documents\n POST -> creates a new document\n\ndocument/[id]\n GET -> retrieves the \"latest\" revision of document specified by ID\n POST -> creates a new revision of the document\n\ndocument/[id]/revision\n GET -> retrieves all revisions of the document\n POST -> Alias to POST->document/[id]\n\ndocument/[id]/revision/[revisionID]\n GET -> retrieves the specified revision of the document\n\nNow, let's say I want to rollback a document to a previous arbitrary revision (for instance, from revision 5 to 3).\nIn a RESTful point of view, what ROUTE and what VERB should be used for this kind of operation? Should I create a new verb for rollback operations?\nKeep in mind that in a rollback operation nothing is deleted. Internally, the server just recognises a different revision number as the latest.\n\nA:\n\nSince you have the representations for each revision available, and the rollback operation should be idempotent, the most straightforward approach would be simply doing a PUT to document/[id] with the contents of GET document/[id]/revision/[revisionid], for the revisionid you want document/[id] to be set to.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29434,"cells":{"text":{"kind":"string","value":"Q:\n\nLoading state in react: Too many re-renders. React limits the number of renders to prevent an infinite loop\n\nHow do I prevent the following error:\n\nToo many re-renders. React limits the number of renders to prevent an infinite loop.'\n\nMy code:\nfunction App() {\n const [items, setItems] = useState([]);\n const [isLoading, setIsLoading] = useState(true);\n if (items.length == 0) loadMore()\n return
\n {isLoading\n ?
Loading...
\n :
    {items.map(i =>
  1. {i}
  2. )}
\n }\n \n
;\n\n function loadMore() {\n setIsLoading(true); // ⚠ errors!\n const uri = \"https://www.reddit.com/r/reactjs.json\";\n fetch(uri)\n .then(r => r.json())\n .then(r => {\n const newItems = r.data.children.map(i => i.data.title);\n items.push(...newItems);\n setItems([...items]);\n setIsLoading(false);\n });\n }\n}\n\nStackblitz link.\n\nA:\n\nThat's because of this condition if (items.length == 0) loadMore().\nBecause at the beginning the length is 0, loadMore is called in which you set the state and you enter the condition again which call loadMore and so on.\nUse the useEffect hook with an empty array of dependencies instead of the condition which will call the function once when the component mount.\nuseEffect(loadMore, [])\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29435,"cells":{"text":{"kind":"string","value":"Q:\n\nIs there an alternative to a purchase order that sellers can use?\n\nThe only thing I can find is a sales order, but the problem with that is it isn't legally binding. To be more specific on what I mean:\nSay that we want to sell someone business cards that includes a specific amount of time for graphic design. And we want to get paid after the graphic design, but before printing. Is there a way before graphic design starts to have a client binded to an agreement that they'll pay us for work done, and if/when design is approved, printing?\nI know a contract would work, but for something as common as business cards - it seems like overkill and would put people off. Purchase orders from customers would be great, but most of them are too small to use them. Are there any options that are simple like a PO, can state a list of terms, and be very easy for customers to get through?\nEvery contract we've had written has been so long that customers don't fully understand the terms. Simple is better for a quick job like this so they DO get the terms clearly.\n\nA:\n\nThere's a tradeoff in written contracts: The more precise and comprehensive, the longer they have to be.\nThe basics of a contract are described here, and it's possible to have a legally valid contract without writing anything at all.\nBut the more you care about avoiding ambiguity and covering \"corner cases,\" the more you need an experienced attorney to write your contract.\nYou can ask an attorney to avoid \"legalese\" to the extent possible, and to try to make a contract as \"easy to read and understand\" as possible. Some are better at that than others.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29436,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy can't I be happy in the pursuit of Nirvana?\n\nIf you are happy, you will have to face sorrow right? So I am being told to just observe everything with equanimity or Anapana. TBH which is very boring So I observed that instead of thinking of everything leads to sorrow in this world, why not enjoy this moment. (Is is necessary to keep observing when you are happy.) \nAfter all we want Nirvana because we are looking for a being in a state of something eternal, Which is equanimity.\nAccording to me Equanimity is not happiness for sure. \nIn this Video Philosopher and writer Jim Holt says we can't live like dead humans as per Buddhism and think like a western.\nI have experienced intoxication occasionally and I was in to Anapana for nearly a week and I have kept myself safe from any kind of intoxication for a year, everything was going smooth breathing while walking, lying, sitting, talking not always but I was satisfied with my pace of being aware.\nBut this weekend I had nothing to do and suddenly a teeny tiny thought arises which says to get drunk and at the same time one of my friend said the same thing and we get drunk.\nI was still trying to figure out what is happening in mind, Why I am feeling different now.\nI know I should not be drinking is there anyway I can punish myself. I was actually scared of getting attacked by mind when alone. It attacked.\nShould i keep in doing Anapana as i believes that it cuts your Karmic chain for the moment.\n\nA:\n\nIf you are happy, you will have to face sorrow right? So I am being told to just observe everything with equanimity or Anapana. TBH which is very boring So I observed that instead of thinking of everything leads to sorrow in this world, why not enjoy this moment. (Is is necessary to keep observing when you are happy.)\n\nTo answer this section:\nYou are temporarily right to try to be happy this moment. A wise person would think \"How can I maintain this happiness forever without changing?\". A sensible person, upon contemplating the matter for some time, realizes there is nothing created that he or she can retain forever. He or she furthermore realizes such possessions can't be guaranteed to be with oneself beyond death. Thus, a wise person decides the boring path provides freedom from such a mass, sorrow and disappointment.\n\nAfter all we want Nirvana because we are looking for a being in a\nstate of something eternal, Which is equanimity\nAccording to me Equanimity is not happiness for sure.\n\nTo answer this section:\nEternity is a word used to describe something that was created and lasts for ever. Nirvana isn't such a thing that is created. Nirvana has not been described as equanimity in the Tipitaka to my knowledge.\n\nI have experienced intoxication occasionally and I was in to Anapana\nfor nearly a week and I have kept myself safe from any kind of\nintoxication for a year, everything was going smooth breathing while\nwalking, lying, sitting, talking not always but I was satisfied with\nmy pace of being aware.\nBut this weekend I had nothing to do and suddenly a teeny tiny thought\narises which says to get drunk and at the same time one of my friend\nsaid the same thing and we get drunk.\nI was still trying to figure out what is happening in mind, Why I am\nfeeling different now.\n\nTo answer this section:\nWhere is that thought now? Did it come to your mind out of your own will? Can you control it? If you can't control it, is it suitable to think the thought is me, mine, or my soul?\n\nI know I should not be drinking is there anyway I can punish myself. I\nwas actually scared of getting attacked by mind when alone. It\nattacked.\n\nTo answer this section:\nI suggest your reward yourself by contemplating the benefits of avoiding drinking rather than punishing yourself. I'm sure there's plenty online resources to explain these benefits apart from a Buddhist context.\n\nShould i keep in doing Anapana as i believes that it cuts your Karmic\nchain for the moment.\n\nTo answer this section:\nFalse. If a person can cut the karmic chain for a moment as such and dies, he'll attain Nirvana. There is no moment a lay person is void of Karmic chain (sankhara). This is what binds us to bhava (world, so to speak).\nI suggest your practice Satipattana Meditating which includes Anapana Sathi and extends a more insightful consciousness to day to day activity.\nBuddha has asked us (citation needed) to travel in the Noble Eightfold Path even if it means crying along the way. Why Buddha says so is because he knows, and intelligent people understand that if someone missed the opportunity to understand the Four Noble Truths, the resultant suffering can be extremely large.\nBuddha has said\n\nNibbanam Paraman Sukhan\n\nWhich translates to\n\nUltimate Luxury is Nibbana\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29437,"cells":{"text":{"kind":"string","value":"Q:\n\nTrue or false:if $A\\subset B$, then $P(A) 0);\n\n Bundle bundle = new Bundle();\n bundle.putString(\"str\", mMathString.toString());\n\n Intent in = new Intent();\n in.putExtras(bundle);\n setResult(1, in);\n\nnew View.OnClickListener() { \n @Override\n public void onClick(View v) {\n // TODO Auto-generated method stub \n finish();\n }\n };\n break;\n\ncan anyone help me to understand where I went wrong as program does not close and give an answer?\n\nA:\n\nHave you verified that your onClick method is being called? The reason I ask is that you show the code for onClick but you don't show that you set this for the equals button by calling setOnClickListener.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29440,"cells":{"text":{"kind":"string","value":"Q:\n\nfile uploading to folder with current time\n\nI've created successful a file uploading-system.\nbut how do I move the uploaded-file to a folder with a random name? (current time)\nindex.php:\n\n\n
\n \n \n \n
File:
&nbsp;
\n
\n \n\n\n\nfile-up.php:\nformat('YmdHis'); \n\n$upload_dir = \"uploads/\";// . $time;\nif (isset($_FILES[\"myfile\"])) {\n if ($_FILES[\"myfile\"][\"error\"] > 0) {\n echo \"Error: \" . $_FILES[\"file\"][\"error\"] . \"
\";\n } else {\n move_uploaded_file($_FILES[\"myfile\"][\"tmp_name\"], $upload_dir . $_FILES[\"myfile\"][\"name\"]);\n echo \"Uploaded File: \" . $_FILES[\"myfile\"][\"name\"];\n }\n}\n?>\n\nA:\n\nTry this Working Code \n format('YmdHis'); \n\n//$upload_dir = \"uploads/\";// . $time;\n$folder_name=date('mds');\n$new_folder=mkdir($folder_name, 0777, true);\nif(file_exists($new_folder)){\n\n echo \"Folder already exist\";\n}\n$upload_dir = $folder_name.'/';\nif (isset($_FILES[\"myfile\"])) {\n if ($_FILES[\"myfile\"][\"error\"] > 0) {\n echo \"Error: \" . $_FILES[\"file\"][\"error\"] . \"
\";\n } else {\n if(move_uploaded_file($_FILES[\"myfile\"][\"tmp_name\"], $upload_dir. $_FILES[\"myfile\"][\"name\"])){\n echo \"Uploaded File: \" . $_FILES[\"myfile\"][\"name\"];\n } else {\n echo $new_folder .'/'. $_FILES[\"myfile\"][\"name\"];\n echo \"Folder created file not uploaded\";\n }\n\n }\n}\n?>\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29441,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to implement like-HtmlHelper\n\nHtmlHelpers are really useful, also i was using AjaxHelpers untill i wanted to do something they can't... so now i'm prefering jquery+javascript, but i don't like to write in javascript (mayby because i never know it as good as i wanted) and to make life easier i wanted to implement something like JQueryHelper, but right now i don't know how\nI wanted to use inside of \"Helper\" resolved URL's, because most methods would just pass data to controllers etc... and update some parts of UI, so i'd like to create something like AjaxHelper, but based on JQuery, not MSScripts.\nWhat should I include in such class? how can i get context, url's and generate proper javascript code which can by dynamicly injected into \nex. \n
\", \"\", new { param1, param2}, )> My Div
\n\nHow is it implemented in HtmlHelper or AjaxHelper?\nEdit:\nI've tried few simple implementation, but i think I'm lack of knowledge and don't know how to implement class with extensions exacly.\nI've ClassA(class) and ClassAExt(extensions):\nI've something like that:\nstatic public class ClassAExt{\n public static MvcHtmlString Method(this ClassA classA) {\n\n }\n}\n\nBut in View(), when I'm using ClassAExt.Method() i have to pass also instance of ClassA (in helpers Ajax and Html this argument is grey (optional? not needed?), how to get such effect).\n\nA:\n\nI am not sure if I understand your question correctly.\nThe HtmlHelper also get instantiated (i.e. new HtmlHelper()) during the course of page rendering and user control rendering. Ajax and URL helpers also get instantiated and this is what give one access to the various variables such HttpContext etc.\nSo in order for you to use your helper class related to ClassA you too will need to instantiate it. I think then the question leads to how do I do this? You will probably need to extend the ViewPage, ViewUserControl and ViewMasterPage classes. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29442,"cells":{"text":{"kind":"string","value":"Q:\n\nPuppet does not honor 'require' modules\n\nI have created a module to add a user as follows:\nuser { 'test':\n ensure => 'present',\n comment => 'Test User',\n home => '/home/test',\n shell => '/bin/bash',\n managehome => 'true',\n gid => 'postgres',\n groups => 'users',\n password => '$1$PIp.c9J6$gdAyd76OhBk7n9asda80wm0',\n require => [ Package['rubygem-ruby-shadow'], Class['postgres'] ],\n}\n\nIt requires the class postgres as I need its primary group to be assigned to postgres, and the rubygem-ruby-shadow dependency is for the password setup.\nMy problem is puppet does not honor these requirements. Puppet will always execute the useradd module first before rubygem-ruby-shadow, and this causes the password setup to fail. I have also tried to include rubygem-ruby-shadow in the same class as useradd but to no avail.\nThe output upon running puppet agent -t:\nlinux-z14x:~ # puppet agent -t\ninfo: Caching catalog for linux-z14x.playground.local\ninfo: /User[test]: Provider useradd does not support features manages_passwords; not managing attribute password\ninfo: Applying configuration version '1425978163'\nnotice: /Stage[main]/Users/Package[rubygem-ruby-shadow]/ensure: created\nnotice: /User[test]/ensure: created\nnotice: Finished catalog run in 78.19 seconds\n\nRunning it the second time:\nlinux-z14x:~ # puppet agent -t\ninfo: Caching catalog for linux-z14x.playground.local\ninfo: Applying configuration version '1425978163'\nnotice: /Stage[main]/Users/User[test]/password: changed password\nnotice: Finished catalog run in 74.79 seconds\n\nMy rubygem-ruby-shadow class:\npackage { 'rubygem-ruby-shadow':\n ensure => 'installed',\n require => Class['myrepo'],\n provider => 'zypper',\n}\n\nHow do I get rubygem-ruby-shadow module to run first before the useradd?\nPuppet master version is 3.7.4-1 (on CentOS) and puppet client is 2.6.12-0.10.1 (on SLES 11 SP2).\nThanks.\n\nA:\n\nThis is unfortunate. The provider detects the absence of ruby-shadow during agent initialization, and does not update its capabilities during the transaction.\nThis may be limitation of Puppet that might be fixed in a more recent version (what are you using?)\nI do try and make sure to provide ruby-shadow along with Puppet itself everywhere, to avoid this very issue.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29443,"cells":{"text":{"kind":"string","value":"Q:\n\nPHP variable changes itself although not passed by reference\n\nIn the following code, I am having trouble understanding why the variable $service_category_tree changes by itself. Somehow, the subscription_tree alter's the parameter variable although it is not passed by reference.\n$service_category_tree = $this->service_category_model->with_request_forms();\nforeach ($this->view_data['users'] as &$user) {\n echo md5(serialize($service_category_tree)).\"
\"; // To check if the variable is changed.\n $user->service_categories = $this->merchant_model->subscription_tree($user->id, $service_category_tree);\n}\n\nThe output of the MD5 statement, as you can see shows that the variable is changed:\n10066a31bb6e191fbb94b8dc61fd6e55\n10066a31bb6e191fbb94b8dc61fd6e55\nfd1e22aa74c048e88751c85528d23254\n752e0cef4357d7a33e47b90ef207d396\n8b5b6ea856080bf32b9bfecc4e43a3f6\n8b5b6ea856080bf32b9bfecc4e43a3f6\n8b5b6ea856080bf32b9bfecc4e43a3f6\n3f3e7619e59e3776c395065e4278c3f8\n3f3e7619e59e3776c395065e4278c3f8\ndbfebae62d65bd04ce4ce74f2046f90e\n34498709256b34ce4d843c1f735c4c6a\n\nThe method subscription_tree does not have an ampersand on the second parameter as seen in the following code.\nfunction subscription_tree($merchant_id, $tree_array = NULL){\n if($tree_array === NULL){\n $this->load->model('service_category_model');\n $tree_array = $this->service_category_model->with_request_forms();\n }\n if(is_array($tree_array) && count($tree_array)){\n $my_request_forms = $this->request_forms($merchant_id)->result();\n $my_service_categories = $this->service_categories($merchant_id)->result();\n foreach ($tree_array as &$sc) {\n\n // Indicate subscribed service categories\n $sc->subscribed = FALSE;\n if(is_array($my_service_categories) && count($my_service_categories)) {\n foreach ($my_service_categories as $my_sc_key => $my_sc) {\n if($my_sc->id == $sc->id){\n $sc->subscribed = TRUE;\n unset($my_service_categories[$my_sc_key]);\n }\n }\n }\n\n // Indicate subscribed request forms\n if(is_array($sc->request_forms) && count($sc->request_forms)) {\n foreach ($sc->request_forms as &$rf) {\n $rf->subscribed = FALSE;\n if(count($my_request_forms)) {\n foreach($my_request_forms as $mrf_key => $my_request_form){\n if ( $my_request_form->id == $rf->id ) {\n $rf->subscribed = TRUE;\n unset($my_request_forms[$mrf_key]);\n break;\n }\n }\n }\n }\n }\n\n }\n }\n return $tree_array;\n}\n\nA:\n\nIn PHP objects are always passed by reference:\nThus lines\nforeach ($tree_array as &$sc) {\n\n // Indicate subscribed service categories\n $sc->subscribed = FALSE;\n\ncould change the $tree_array object, which is a reference to $service_category_tree\nYou could also make a deep-copy of your array:\n$new_tree = array();\n\nforeach ($service_category_tree as $k => $v) {\n $new_tree[$k] = clone $v;\n}\n\nand pass it to the function. Or make a deep-copy in the function...\nMore info at http://php.net/manual/en/language.oop5.references.php\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29444,"cells":{"text":{"kind":"string","value":"Q:\n\nComparing two fields using LINQ\n\nI'm facing a weird problem. As shown in the image actually I selected record number 37 but lightswitch is highlighting as record number 1.\n\n1) The FristName,LastName & HospitalName are unique indexes in the table Doctors since each doctor can have multiple addresses.\n2) I'm validating this drop down field as below to avoid user from selecting doctors who are not part of the hospital patient belongs to. \npartial void DoctorsMasterItem_Validate(EntityValidationResultsBuilder results)\n {\n if (this.DoctorsMasterItem != null)\n {\n\n if (this.HospitalName != this.DoctorsMasterItem.HospitalName)\n {\n\n results.AddPropertyError(\"Make Sure the Hospital Patient belongs to and Doctor is also part of that hospital else your letters address would be wrong\");\n\n }\n\n }\n\n }\n\nThe data model is\n\nA:\n\nA better approach would be to filter the dropdown box, so the user isn't presented with invalid choices.\nHave a look at these two articles. This is what I believe you should be doing, nested (or cascading) comboboxes:\nNested AutoCompleteBox For Data Entry\nNested AutoCompleteBox for data entry Part 2\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29445,"cells":{"text":{"kind":"string","value":"Q:\n\nThe filter does not return anything even after match in Javascript\n\nso I am trying use this Filter in one of my functions but the filter return empty array even though there are few matches .\ncode \nfilteredCardList: function () {\n\n if (this.monthFilter.length > 0) {\n return this.cardList.filter((card) => {\n this.monthFilter.forEach(function (val) {\n if (val.toString() == card.months) {\n console.log('Matched')\n return true;\n } else {\n console.log('NoMatch')\n return false;\n }\n });\n })\n } else {\n return this.cardList\n }\n}\n\nAny ideas , most welcome\nthanks\n\nA:\n\nOk, assuming monthFilter is an array and you want to filter cardList by the values inside using an any sort of match, try using Array.prototype.some\nfilteredCardList: function () {\n if (this.monthFilter.length > 0) {\n return this.cardList.filter(card => {\n return this.monthFilter.some(val => {\n return val.toString() == card.months\n })\n })\n } else {\n return this.cardList\n }\n}\n\nYour problem was that your return true / return false was simply returning from the forEach callback and nothing was returned in the filter callback.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29446,"cells":{"text":{"kind":"string","value":"Q:\n\nActionMailer observers not working with delayed_job\n\nI have an ActionMailer observer that's working just fine during normal sends, but when I send the delivery to delayed_job, it doesn't get called at all. Is this a function of delayed_job itself, or something specific with my observer?\nController:\nBulkMailer.delay.blast(recipients, email, template)\n\nInitializer:\nActionMailer::Base.register_observer(MailObserver)\n\nObserver\nclass MailObserver\n def self.delivered_email(message)\n Rails.logger.debug 'Message: finished'\n end\nend\n\nA:\n\nThe code itself was fine, Delayed Job and ActionMailer observers are compatible. My problem was solved by restarting the workers.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29447,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat kind of indexing are used in MyISAM and InnobDB engines?\n\nI read that InnobDB uses B+ Tree and Clustered indexing on Primary Key and Hash(H) Tree and Non Clustered indexing on multiple keys (unique key).\nBut I did not get any explanation for MyISAM..\nAnd what I read for InnobDB is correct ?\n\nA:\n\nYes you are correct regarding the InnoDB. For MyISAM see below \nB-tree indexes Yes T-tree indexes No Hash indexes No\n\nRead Here more \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29448,"cells":{"text":{"kind":"string","value":"Q:\n\nAvoid DD anomalies\n\nI have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece.\nThe case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don't like several returns on a method.\npublic String getBingLocation(Coordinate... data)\n{\n String response = \"Not Retrieved\";\n final Coordinate location = data[0];\n JSONObject locationData;\n try {\n locationData = NetworkManager.getJSONResult(ApiFormatter\n .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));\n if (null != locationData) {\n final String address = this.getAddressFromJSONObject(locationData);\n response = address;\n }\n } catch (final ClientProtocolException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n return response;\n } catch (final JSONException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n return response;\n } catch (final IOException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n return response;\n } finally {\n location.Street = response;\n }\n return response;\n}\n\nOther example:\npublic static Object loadObject(final String fileName, final Context context) {\n Object object = null;\n try {\n ObjectInputStream objectInputStream = null;\n try {\n final FileInputStream fileStream = context.openFileInput(fileName);\n objectInputStream = new ObjectInputStream(fileStream);\n object = objectInputStream.readObject();\n } catch (final ClassNotFoundException catchException) {\n LoggerFactory.consoleLogger().printStackTrace(catchException);\n } catch (final ClassCastException catchException) {\n LoggerFactory.consoleLogger().printStackTrace(catchException);\n } catch (final Exception catchException) {\n LoggerFactory.consoleLogger().printStackTrace(catchException);\n } finally {\n if (objectInputStream != null) {\n objectInputStream.close();\n }\n }\n } catch (final IOException catchException) {\n LoggerFactory.consoleLogger().printStackTrace(catchException);\n }\n return object;\n}\n\nA:\n\nPart of the problem is your functions have more than one responsibility. They are both getting a result and handling errors. You're also getting unnecessarily hung up trying to avoid multiple return points, which is a vestigial practice from C programming where it can cause memory leaks. You should use multiple returns if it clarifies your code, especially in short functions. I'm also guessing that your logging code is getting repeated all over the place. If you separate those concerns and try to avoid repeating yourself, you get something like this:\npublic JSONObject getLoggedJSONResult(String api)\n{\n try {\n return NetworkManager.getJSONResult(api);\n } catch (final ClientProtocolException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n } catch (final JSONException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n } catch (final IOException e) {\n LoggerFactory.consoleLogger().printStackTrace(e);\n }\n\n return null;\n}\n\npublic String getBingLocation(Coordinate... data)\n{\n final Coordinate location = data[0];\n\n JSONObject locationData = getLoggedJSONResult(\n ApiFormatter.generateBingMapsReverseGeocodingURL(\n location.Latitude, location.Longitude));\n\n if (null == locationData) {\n return \"Not Retrieved\";\n } else {\n return this.getAddressFromJSONObject(locationData);\n }\n}\n\nAs a general principle, most DD anomalies can be fixed by splitting the function. It's mostly a matter of figuring out where to split it.\nYour second example is trickier. That sort of situation is why try-with-resources statements were invented. You can use an early return to eliminate the DD anomaly on object, but you're not going to be able to do much about objectInputStream without a try-with-resources.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29449,"cells":{"text":{"kind":"string","value":"Q:\n\nWebview app code security\n\nI have an app which runs mostly in webview and opens an html file from my server and most of the logic happens in its javascript files. If you open the html file on your browser you will have all the code with a simple inspect element. I wanted to ask how can I secure my application and prevent my code from being seen and copied.\nThanks\n\nA:\n\nBy default WebView doesn't allow debugging of its contents (unlike Chrome), unless it runs on a debug build of Android. Thus if you don't reveal the URL anywhere, users will simply not know what to open in a browser.\nYou can also minify/obfuscate your JavaScript code to make it barely readable, even if anyone somehow opens it. This also has a benefit of reducing download size.\nA radical approach would be to generate all the results on the server and send them to clients. This way, your clients will not have any code at all on them. But this will greatly complicate any attempts to make the results interactive.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29450,"cells":{"text":{"kind":"string","value":"Q:\n\nLWJGL 3 Shaders version 150 and above rendering nothing\n\nI'm using LWJGL 3 on OSX. The shaders work fine when using a version <150 but porting the code to 330 nothing renders.\nMy shaders are as simple as possible:\nvertex shader:\n#version 330 core\n\nin vec3 position;\n\nvoid main(void) {\n gl_Position = vec4(position, 1.0);\n}\n\nfragment shader:\n#version 330 core\n\nout vec4 outColour;\n\nvoid main(void) {\n outColour = vec4(1.0, 0.0, 0.0, 1.0);\n}\n\nI create a simple triangle like this (Scala):\nval vertices = Array(\n 0.0f, 0.5f, 0.0f,\n -0.5f, -0.5f, 0.0f,\n 0.5f, -0.5f, 0.0f\n)\nval vertexBuffer = BufferUtils.createFloatBuffer(vertices.length)\nvertexBuffer.put(vertices)\nvertexBuffer.flip()\n\nval buffer = GL15.glGenBuffers()\nGL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer)\nGL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBuffer, GL15.GL_STATIC_DRAW)\n\nand I draw it like this:\nGL20.glUseProgram(shader)\nGL20.glEnableVertexAttribArray(0)\n\nGL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer)\nGL20.glBindAttribLocation(shader, 0, \"position\")\nGL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0)\nGL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 9)\n\nGL20.glDisableVertexAttribArray(0)\nGL20.glUseProgram(0)\n\nThe shaders compile fine and the program runs but I just get a blank screen! Is there anything obviously wrong with my code?\n\nA:\n\nVertex Array Objects (VAOs) are required for rendering in a Core context. In Compatibility contexts they're optional.\nHowever, you can just generate one at startup and leave it bound if you're feeling lazy :)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29451,"cells":{"text":{"kind":"string","value":"Q:\n\nSignificance of Proton Tunneling\n\nIt has been repeatedly emphasized that proton transfers \"involving\" three or four membered ring transition states are not favorable and should not be drawn as the primary mechanism for any reaction. \nHowever, with regard to a recent discussion involving $\\ce{H3CSH}$ it was noted that the rate of proton tunneling in the anionic form $\\ce{H3CS-}$ was likely extremely high. \nCarbon-Sulfur Bond Lengths; Resonance Effects (Or Lack Thereof)\nSo:\na) Is this a valid rule of thumb: avoid intramolecular proton transfers unless the transition state has 5 or 6 members in its ring?\nb) What's more significant with regard to proton transfer - proton tunneling or physical proton transfer? Or is the answer an \"it depends\"? \n\nA:\n\na) Is this a valid rule of thumb: avoid intramolecular proton\n transfers unless the transition state has 5 or 6 members in its ring?\n\nYes\n\nb) What's more significant with regard to proton transfer - proton\n tunneling or physical proton transfer? Or is the answer an \"it\n depends\"?\n\nIt depends, at temperatures around absolute zero, tunneling can become significant. At ambient temperatures or above, physical proton transfer is much more common. \nAs to the methyl mercaptan anionic example you cite, to the extent that the various carbon-sulfur double bond resonance structures contribute, I would expect a lowering of the barrier around carbon anion planarization - and consequently a lowering of the barrier to inversion at the carbon atom in the anion. Therefore, it is not clear to me that tunneling of the sulfur bound proton would be preferred to carbon inversion in order to bring about the syn-anti interconversion, especially since any presumed experiments to generate the anion would not be performed near absolute zero.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29452,"cells":{"text":{"kind":"string","value":"Q:\n\nUniformization of Kodaira fibered surfaces\n\nConsider a Kodaira fibration. i.e. a smooth non-isotrivial fibration $X\\rightarrow C$ with $X$ a smooth complex surface and $C$ a smooth complex curve, such that both the genus of $C$ and genus of the fibers (which are complex curves) are at least $2$. By abuse of notation I call $X$ a Kodaira fibered surface. What is known about the structure of the universal cover of $X$? In particular, when is it a bounded symmetric domain? I know that $X$ is a minimal algebraic surface of general type and that the universal cover of $X$ can never be a ball in $\\mathbb{C}^{2}$. \n\nA:\n\nHere are the arguments to exclude polydisk and the ball (there are no other complex 2-dimensional bounded symmetric domains: In fact, one can do without this and argue that any domain other than the ball would have rank $\\ge 2$ and, hence, Margulis superrigidity theorem would apply). \n\nKefeng Liu (\"Geometric height inequalities\", Math. Research Letters, 3 (1996), 693–702) proved that a compact complex-hyperbolic surface cannot admit a holomorphic submersion to a Riemann surface. This excludes the complex ball. \nConsider the 2-dimensional polydisk $D^2$ and a group $\\Gamma$ acting discretely, holomorphically and cocompactly on $D^2$. Then $\\Gamma$ is a lattice in $Isom(D^2)$ and by Margulis' superrigidity theorem either $\\Gamma$ is reducible or it is superrigid, and , ehnce, does not admit an epimorphism to a surface group. The second is impossible in the case of fibrations over Riemann surfaces, the first contradicts non-isotriviality assumption in the question.\n\nOn the other hand, the universal cover of your complex manifold $X$ is a certain bounded domain in ${\\mathbb C}^2$: This result could be found in \nP.A. Griffiths, Complex-analytic properties of certain Zariski open sets on algebraic varieties. Ann. of Math. (2) 94 (1971), 21–51. \nwho proves it using Bers' simultaneous uniformization. \n\nA:\n\nIf an algebraic surface has the bidisk as universal cover, then, by Hirzebruch's proportionality theorem, its topological index is 0 (the index is 1/3 (c_1^2 - 2 c_2)).\nBut Kodaira proved that for Kodaira fibrations the index is strictly positive.\nTo exclude the case that the universal covering is the ball, where \nc_1^2 = 3 c_2, again by Hirzebruch's theorem, is harder and was done by Kefeng Liu. You may look in my article with Rollenske for more results on Kodaira fibrations. \nRegards, Fabrizio Catanese.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29453,"cells":{"text":{"kind":"string","value":"Q:\n\nHaving an issue with callback function\n\nSo I have some code like this \n\nconst getAPIData = (symbol, callback) => {\r\n var options = {\r\n url: \"https://api.binance.com/api/v3/ticker/price\",\r\n method: \"GET\",\r\n qs: {\r\n symbol\r\n },\r\n };\r\n request(options, (err, res, body) => {\r\n body = JSON.parse(body);\r\n callback(body);\r\n });\r\n};\r\n\r\nvar isValid = 0;\r\ngetAPIData(symbol, (body) => {\r\n console.log(body);\r\n if (body.symbol) {\r\n console.log(\"yes\");\r\n isValid = 1;\r\n } else {\r\n console.log(\"no\");\r\n }\r\n});\n\nAfter this callback is executed the \"isValid\" variable still remains 0 no matter what the outcome is. Although the console gets logged with yes and no both. The isValid variable still remains 0 when I debug the program.\nHow can the console.log function work and not set the isValid to 1? it's like it's just skipping that line or I'm not sure. Please help me out!\n\nA:\n\nThis is the way asynchronous calls work.\n var isValid = 0;\n getAPIData(symbol, (body) => {\n console.log(body);\n if (body.symbol) {\n console.log(\"yes\");\n isValid = 1;\n console.log(isValid); // 1\n } else {\n console.log(\"no\");\n }\n });\n\nconsole.log(isValid); // 0\n// when the JS engine gets here, isValid will still be 0\n// since getAPIData is asynchronous and it's still in progress at this point\n// also, you cannot use any results of getAPIData here\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29454,"cells":{"text":{"kind":"string","value":"Q:\n\nXmlAttribute value and innertext\n\nI have a piece of code that fills a hashtable with strings, per example: (\"name\", Oscar). I want to use them to fill (just by memory usage) values and innertexts of XMLAtributes. But there is one problem.\nXmlElement Co = newDoc.CreateElement(\"Co1\");\n\n XmlAttribute series = Co.Attributes.Append(newDoc.CreateAttribute(\"series\"));\n series.InnerText = (string)vector[\"series\"];\n series.Value = (string)vector[\"series\"];\n MessageBox.Show((string)vector[\"series\"]);\n MessageBox.Show(Co.Attributes[\"series\"].InnerText.ToString());\n MessageBox.Show(Co.Attributes[\"series\"].Value.ToString());\n\nWhen ever I want the system to show me the value or the innertext (within the xml create method this piece of code is in) it has it returns nothing. Then It passes to the next atribute and returns a \"Object reference not set to an instance of an object.\". The next piece of code is this one:\nXmlAttribute folio = Co.Attributes.Append(newDoc.CreateAttribute(\"folio\"));\n folio.InnerText = vector[\"folio\"].ToString();\n\nThe error hits in the last line.\nIn any other place of the class I can see and retrieve the values of the hastable by the .ToString() method and the cast.\nIt seems that Im not properly getting the value out of my hashtable or there is something I am missing with the XMLAtributes... ¿What is the proper way to do so?\n\nA:\n\nYou are doing this the hard way:\nvar folio = Convert.ToString(vector[\"folio\"]);\nCo.SetAttribute(\"folio\", folio);\n\nThere is no need to worry about things like InnerText.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29455,"cells":{"text":{"kind":"string","value":"Q:\n\nIntegrating Factor - Not getting the answer given?\n\n$y' - 4y = t$ \nMy integrating factor is $e^{-4t}$\n$\\int e^{-4t}y'$ - $\\int 4e^{-4t}y$ = $\\int te^{-4t}$\n$\\int (e^{-4t}y)'$ = $\\int te^{-4t}$\n$e^{-4t}y$ = $-4te^{-4t}$ - $e^{-4t}$ \nI end up with $y' = -4t -1 + ce^{4t}$\nWhere did I go wrong?\n\nA:\n\nYou integrated $\\int te^{-4t}\\mathrm dt$ incorrectly. It should be\n$$\\int te^{-4t}\\mathrm dt=-\\dfrac{t}{4}e^{-4t}-\\dfrac{1}{16}e^{-4t}+c$$\nThen multiplying both sides by $e^{4t}$ gives you \n$$y=-\\dfrac{t}{4}-\\dfrac{1}{16}+ce^{4t}$$\n\nA:\n\nLet $u=t$, $du=dt$, $dv=e^{-4t}$, and $v=-\\cfrac{1}{4}e^{-4t}$, then using integration by parts, $\\displaystyle\\int te^{-4t}\\, dt$ should be\n\\begin{align}\n\\int te^{-4t}\\, dt&=-\\cfrac{t}{4}e^{-4t}+\\cfrac{1}{4}\\int e^{-4t}\\,dt\\\\\n&=-\\cfrac{t}{4}e^{-4t}+\\cfrac{1}{4}\\left(-\\cfrac{1}{4}e^{-4t}\\right)+C\\\\\n&=-\\cfrac{t}{4}e^{-4t}-\\cfrac{1}{16}e^{-4t}+C\\\\\n\\end{align}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29456,"cells":{"text":{"kind":"string","value":"Q:\n\nVolumetric rendering fundamental concepts and terminology\n\nLiterature on rendering volumetric materials and effects tends to use a lot of mathematical physics terminology. Let's say that I have a decent handle on the concepts involved in surface rendering. What concepts do I need to understand for volumetric rendering? (Both real-time and offline rendering.)\n\nWhat exactly is meant by light scattering in the context of volumetric rendering? (And why is it split into in-scattering and out-scattering?)\nWhat is the relationship between transmission, attenuation, and absorption?\nWhat is a phase function and how does it play into volumetric rendering? (In particular, the Henyey-Greenstein phase function.)\nWhat is the Beer-Lambert law and how is it related to light scattering?\n\nBasically, how do I make sense out of diagrams like this?\n\nA:\n\nWhen I was first reading about all of this I stumbled upon this link which helped me better understand this large subject. Also this goes into some more detail on things mentioned here.\nLight scattering is a natural phenomenon which arises when light interacts with particles distributed in a media as it travels through it. From Wikipedia:\n\nLight scattering can be thought of as the deflection of a ray from a straight path, for example by irregularities in the propagation medium, particles, or in the interface between two media\n\nIn computer graphics there are models that have been developed to simulate the effect of light traversing volume objects from an entry point (Point A) to an exit point (Point B). As the light travels from A to B it is changed due to interactions with particles and these interactions are often referred to as Absorption, Out Scattering and In Scattering. Often you will see these split into two groups; Transmittance (Absorption and Out Scattering) which I like to think of as 'light lost' and In-Scattering ('light gained').\nAbsorption is basically incident light energy that is transformed into some other form of energy and therefore 'lost'.\nTransmittance\nTransmittance describes how light reflected behind a volume will be attenuated due to Absorption as it travels through a medium from A to B. This is usually calculated with the Beer-Lambert law which relates the attenuation of light to the properties of the material through which it is travelling.\nAs the light travels through the medium there is a chance that the photons can be scattered away from their incident direction and therefore not make it to the eye of the observer and this is referred to as Out-Scattering. In most models the Transmittance equation is changed slightly to introduce the concept of Out-Scattering.\nIn Scattering\nAbove we have seen how light can be lost due to photons been scattered away from the viewing direction. At the same time light can be scattered back into the viewing direction as it is travelling from A to B and this is called In-Scattering.\nParticle In-Scattering itself is a pretty complex topic but basically you can split it into Isotropic and Anisotropic scattering. Modelling Anisotropic scattering would take a considerable amount of time so usually in computer graphics this is simplified by using a Phase Function which describes the amount of light from the incident light direction that is scattered into the viewing direction as it travels from A to B.\nOne commonly used non-isotropic Phase Function is called the Henyey-Greenstein phase function which can model Backward and Forward scattering. It usually has a single parameter, g ∈ [−1,1], that determines the relative strength of forward and backward scattering.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29457,"cells":{"text":{"kind":"string","value":"Q:\n\nConcurrentDictionary\n\nIntroduction\nI'm building an API wrapper for the SE API 2.0\nCurrently, I'm implementing a cache feature, this wasn't an issue until now. Now I'm taking concurrency into account. This would be my test method:\nCode\npublic static void TestConcurrency()\n{\n Stopwatch sw = new Stopwatch();\n sw.Start();\n IList tasks = new List();\n for (int i = 0; i < 1000; i++)\n {\n tasks.Add(Task.Factory.StartNew(p => client.GetAnswers(), null));\n }\n Task.WaitAll(tasks.ToArray());\n sw.Stop();\n Console.WriteLine(\"elapsed: {0}\", sw.Elapsed.ToString());\n Console.ReadKey();\n}\n\nDescription\nInternally, the client has a RequestHandler class, which attempts to fetch a value from the cache, and if it fails to do so, it performs the actual request.\nCode\n/// \n/// Checks the cache and then performs the actual request, if required.\n/// \n/// The strong type of the expected API result against which to deserialize JSON.\n/// The API endpoint to query.\n/// The API response object.\nprivate IApiResponse InternalProcessing(string endpoint) where T : class\n{\n IApiResponse result = FetchFromCache(endpoint);\n return result ?? PerformRequest(endpoint);\n}\n\nDescription\nThe code that actually performs the request is irrelevant to this issue. The code that attempts to access the cache does the following:\nCode\n/// \n/// Attempts to fetch the response object from the cache instead of directly from the API.\n/// \n/// The strong type of the expected API result against which to deserialize JSON.\n/// The API endpoint to query.\n/// The API response object.\nprivate IApiResponse FetchFromCache(string endpoint) where T : class\n{\n IApiResponseCacheItem cacheItem = Store.Get(endpoint);\n if (cacheItem != null)\n {\n IApiResponse result = cacheItem.Response;\n result.Source = ResultSourceEnum.Cache;\n return result;\n }\n return null;\n}\n\nDescription\nThe actual implementation of the cache store works on a ConcurrentDictionary, when the Get() method is invoked, I:\n\nCheck whether the dictionary has an entry for endpoint.\nIf it does, I verify whether or not it holds a response object.\nIf it doesn't already have a response object, the cache item's state will be Processing, and the thread will be put to sleep for a small amount of time, waiting on the actual request being completed.\nOnce or if the response is \"commited\" to the cache store (this happens once the request is completed), the cache item is returned.\nIf the cache item was too old or the request processing timed out, the entry is removed from the store.\nIf the cache didn't have an entry for endpoint, null is pushed into the cache as the response for endpoint, signaling a request on that endpoint is being processed and there is no need to issue more requests on the same endpoint. Then null is returned, signaling an actual request should be made.\n\nCode\n/// \n/// Attempts to access the internal cache and retrieve a response cache item without querying the API.\n/// If the endpoint is not present in the cache yet, null is returned, but the endpoint is added to the cache.\n/// If the endpoint is present, it means the request is being processed. In this case we will wait on the processing to end before returning a result.\n/// \n/// The strong type of the expected API result.\n/// The API endpoint\n/// Returns an API response cache item if successful, null otherwise.\npublic IApiResponseCacheItem Get(string endpoint) where T : class\n{\n IApiResponseCacheItem cacheItem;\n if (Cache.TryGetValue(endpoint, out cacheItem))\n {\n while (cacheItem.IsFresh && cacheItem.State == CacheItemStateEnum.Processing)\n {\n Thread.Sleep(10);\n }\n if (cacheItem.IsFresh && cacheItem.State == CacheItemStateEnum.Cached)\n {\n return (IApiResponseCacheItem)cacheItem;\n }\n IApiResponseCacheItem value;\n Cache.TryRemove(endpoint, out value);\n }\n Push(endpoint, null);\n return null;\n}\n\nThe issue is indeterminately, sometimes two requests make it through, instead of just one like it is designed to happen.\nI'm thinking somewhere along the way something that's not thread safe is being accessed. But I can't identify what that might be. What could it be, or how should I debug this properly?\nUpdate\nThe issue was I wasn't always being thread safe on the ConcurrentDictionary\nThis method wasn't retuning a boolean indicating whether the cache was successfully updated, therefore if this method failed, null would have been returned twice by Get().\nCode\n/// \n/// Attempts to push API responses into the cache store.\n/// \n/// The strong type of the expected API result.\n/// The queried API endpoint.\n/// The API response.\n/// True if the operation was successful, false otherwise.\npublic bool Push(string endpoint, IApiResponse response) where T : class\n{\n if (endpoint.NullOrEmpty())\n {\n return false;\n }\n IApiResponseCacheItem item;\n if (Cache.TryGetValue(endpoint, out item))\n {\n ((IApiResponseCacheItem)item).UpdateResponse(response);\n return true;\n }\n else\n {\n item = new ApiResponseCacheItem(response);\n return Cache.TryAdd(endpoint, item);\n }\n}\n\nDescription\nThe solution was to implement the return value, and changing Get() adding this:\nCode\nif (Push(endpoint, null) || retries > 1) // max retries for sanity.\n{\n return null;\n}\nelse\n{\n return Get(endpoint, ++retries); // retry push.\n}\n\nA:\n\nIApiResponseCacheItem cacheItem = Store.Get(endpoint);\nif (cacheItem != null)\n{\n // etc..\n}\n\nA ConcurrentDirectionary is thread-safe but that doesn't automatically make your code thread safe. The above snippet is the core of the problem. Two threads could call the Get() method at the same time and get a null. They'll both continue on and call PerformRequest() concurrently. You'll need to merge the InternalProcessing() and FetchFromCache() and ensure that only one thread can call PerformRequest by using a lock. That might produce poor concurrency, perhaps you could just drop a duplicate response. In all likelihood, the requests get serialized by the SE server anyway so it probably doesn't matter.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29458,"cells":{"text":{"kind":"string","value":"Q:\n\nCan I untangle this nesting of 'when' promise invocations?\n\nI'm new to the when.js javascript library, but I'm familiar with async programming in C#. That's why I find this code to be unwieldy:\nfilters.doFilter('filter1name', reqAndPosts).then(function(filter1) {\n filters.doFilter('filter2name', filter1).then(function(filter2) {\n filters.doFilter('filter3name', filter2).then(function (posts) {\n renderView(posts); \n });\n });\n return filter1;\n});\n\nI basically want three methods to be called in sequence, with the output of each being piped to the next method. Is there anyway I can refactor this code to be more \"sequence-like\" - i.e. get rid of the nesting? I feel like there's something I'm missing with the when-framework here. I'm not doing it right, right?\n\nA:\n\nSince doFilter returns a promise, we can do\nfilters.doFilter('filter1name', reqAndPosts)\n .then(function(filter1) {\n return filters.doFilter('filter2name', filter1);\n })\n .then(function(filter2) {\n return filters.doFilter('filter3name', filter2);\n })\n .then(renderView);\n\nA:\n\nThere is another option to have both advantages of cleaner indentation and previous results available: using withThis.\nfilters.doFilter('filter1name', reqAndPosts).withThis({}).then(function(filter1) {\n this.filter1 = filter1; // since we used withThis, you use `this` to store values\n return filters.doFilter('filter2name', filter1);\n}).then(function(filter2) {\n // use \"this.filter1\" if you want\n return filters.doFilter('filter3name', filter2);\n}).then(renderView);\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29459,"cells":{"text":{"kind":"string","value":"Q:\n\nDeadlock occurs in broker database while publishing\n\nI am getting deadlock in my broker database(Oracle based) while publishing lot of components/pages in my production environment. The deadlocks occurs in the following statement:\nupdate TAXFACETS set FACET_ISABSTRACT=:1 , FACET_DEPTH=:2 , FACET_HASCHILDREN=:3 , FACET_ID=:4 , FACET_ITEMTYPE=:5 , FACET_KEY=:6 , FACET_LEFT=:7 , FACET_ISNAVIGABLE=:8 , FACET_PARENT=:9 , PUBLICATION_ID=:10 , FACET_RIGHT=:11 , TAXONOMY_ID=:12 , TOTAL_RELATEDITEMS=:13 , FACET_DESCRIPTION=:14 , FACET_NAME=:15 , FACET_ISUSEDFORIDENTIFICATION=:16 where NODE_ID=:17\n\nI can see below message in my deployer cd_core log:\n2015-05-21 11:21:33,491 DEBUG SearchIndexerDeployModule - Processing F:\\tridion\\deployer\\incoming_staging\\Zip\\tcm_0-125870-66560.Content\\components.xml file\n2015-05-21 11:21:33,491 DEBUG JPAComponentPresentationDAO - Removing component presentation from storage.\n2015-05-21 11:21:33,491 DEBUG PreCommitPhase - Executing worker: com.tridion.storage.deploy.workers.ComponentPresentationWorker@1262fa8 on transaction: tcm:0-125868-66560 took: 0\n2015-05-21 11:21:33,491 DEBUG PreCommitPhase - Executing worker com.tridion.storage.deploy.workers.ComponentPresentationMetaWorker@7362351f on transaction: tcm:0-125868-66560 this is worker 20 of: 22\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / ItemMeta / null\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / ComponentPresentationMeta / null\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / DynamicLinkInfo / null\n2015-05-21 11:21:33,491 INFO StorageManagerFactory - While loading caching DAO, no configuration found, returning uncached.\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Storing non cached DAO into caching map as there is no configuration present for the cached version of the DAO\n2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed\n2015-05-21 11:21:33,491 DEBUG JPADynamicLinkDAO - Removing dynamic links with source TCMURI tcm:34-36190-48\n2015-05-21 11:21:33,491 DEBUG CacheChannel - Received event from another VM [CacheEvent eventType=Invalidate regionPath=/com.tridion.storage.ReferenceEntry key=34:tcd:pub[34]/componentmeta[36156]:tcd:pub[34]/pagemeta[36157]]\n2015-05-21 11:21:33,491 ERROR DeployPipelineExecutor - Unable to start processing deployment package with transactionId: tcm:0-125866-66560\ncom.tridion.deployer.ProcessingException: Phase: Deployment Commit Phase failed. \nCommit failed for transaction: tcm:0-125866-66560\n at com.tridion.deployer.phases.DeployPipelineExecutor.runMainExecutePhase(DeployPipelineExecutor.java:209) [cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.phases.DeployPipelineExecutor.doExecute(DeployPipelineExecutor.java:100) [cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.phases.DeployPipelineExecutor.execute(DeployPipelineExecutor.java:64) [cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.TransactionManager.handleDeployPackage(TransactionManager.java:82) [cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.queue.QueueLocationHandler$1.run(QueueLocationHandler.java:180) [cd_deployer-2013SP1.jar:na]\n at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_55]\n at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_55]\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_55]\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_55]\n at java.lang.Thread.run(Thread.java:745) [na:1.7.0_55]\nCaused by: com.tridion.deployer.ProcessingException: Unable to commit transactions\n at com.tridion.deployer.phases.AbstractStorageStep.commitTransaction(AbstractStorageStep.java:34) ~[cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.phases.CommitPhase.execute(CommitPhase.java:77) ~[cd_deployer-2013SP1.jar:na]\n at com.tridion.deployer.phases.DeployPipelineExecutor.runMainExecutePhase(DeployPipelineExecutor.java:198) [cd_deployer-2013SP1.jar:na]\n ... 9 common frames omitted\nCaused by: com.tridion.broker.StorageException: Commit failed for transaction tcm:0-125866-66560 because of Unexpected error ocurred while committing\n at com.tridion.storage.StorageManagerFactory.commitTransaction(StorageManagerFactory.java:358) ~[cd_datalayer-2013SP1.jar:na]\n at com.tridion.deployer.phases.AbstractStorageStep.commitTransaction(AbstractStorageStep.java:32) ~[cd_deployer-2013SP1.jar:na]\n ... 11 common frames omitted\nCaused by: com.tridion.broker.StorageException: Unexpected error ocurred while committing\n at com.tridion.storage.persistence.JPADAOFactory.commitTransaction(JPADAOFactory.java:209) ~[cd_datalayer-2013SP1.jar:na]\n at com.tridion.storage.StorageManagerFactory.commitTransaction(StorageManagerFactory.java:354) ~[cd_datalayer-2013SP1.jar:na]\n ... 12 common frames omitted\nCaused by: javax.persistence.RollbackException: Error while committing the transaction\n at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final]\n at com.tridion.storage.persistence.JPADAOFactory.commitTransaction(JPADAOFactory.java:206) ~[cd_datalayer-2013SP1.jar:na]\n ... 13 common frames omitted\nCaused by: javax.persistence.PersistenceException: org.hibernate.exception.LockAcquisitionException: could not execute statement\n at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final]\n ... 14 common frames omitted\nCaused by: org.hibernate.exception.LockAcquisitionException: could not execute statement\n at org.hibernate.dialect.Oracle8iDialect$2.convert(Oracle8iDialect.java:450) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:189) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3236) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3138) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3468) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:393) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:385) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:302) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:349) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1159) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final]\n ... 14 common frames omitted\nCaused by: java.sql.SQLException: ORA-00060: deadlock detected while waiting for resource\n\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1044) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1329) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3594) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3675) ~[ojdbc6.jar:11.2.0.3.0]\n at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354) ~[ojdbc6.jar:11.2.0.3.0]\n at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:174) ~[weblogic.server.merged.jar:12.1.2.0.0]\n at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final]\n ... 29 common frames omitted\n2015-05-21 11:21:33,491 DEBUG CacheChannel - Received event from another VM [CacheEvent eventType=Invalidate regionPath=/com.tridion.storage.ReferenceEntry key=34:tcd:pub[34]/componentmeta[36154]:tcd:pub[34]/pagemeta[36157]]\n2015-05-21 11:21:33,491 DEBUG JPAComponentPresentationMetaDAO - ComponentPresentationMeta was found for removal\n\nAs this issue occurs in my production environment, I can't do anything to bottleneck the root cause. This issue is redundant(Even with same data) and I am not able to reproduce the same every time on my development environment with similar data. By looking in the above log I can assume that error occurs because of use of many taxonomies in the metadata schema. If anyone faced similar issue, please share the root cause and respective work around. Thanks in advance..\n\nA:\n\nIf you are using Tridion 2013 SP1 HR1, there is a hotfix for a problem that looks very similar to this issue. Have you tried this hotfix ?\n\nCD_2013.1.1.88660\nDeadlock and javax.persistence.OptimisticLockException apparently on\nmetadata leading to a failed transaction\n\nThe description of the hotfix states:\n\nHotfix Description\n(SRQ-3065) Deadlock and javax.persistence.OptimisticLockException apparently on metadata\nleading to a failed transaction\"\nDeadlock and javax.persistence.OptimisticLockException apparently on\nmetadata leading to a failed transaction. There will be a deadlock as\nsuch: 2015-03-02 15:02:14,840 DEBUG SqlExceptionHelper - ORA-00060:\ndeadlock detected while waiting for resource [n/a]\njava.sql.SQLException: ORA-00060: deadlock detected while waiting for\nresource\n\nYou can find the hotfix on the sdl tridion world website https://www.sdltridionworld.com/downloads/hotfixes/SDL_Tridion_2013_SP1_HR1/index.aspx\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29460,"cells":{"text":{"kind":"string","value":"Q:\n\nЗадание по русскому языку\n\nСегодня мне задали вопрос.\nВыражение A B C D употребляется после слова «самый» и усиливает его. Ещё в русском языке есть неопределённое местоимение A E F B G и составные союзы B... B..., F...F... и A B... F... . Напишите слово E.\nЧестно говоря, я вообще не понял суть задания, что за такие выражения, и что надо вписать вместо точек.\nМожет, кто-нибудь разберется?\n\nA:\n\nA B C D — что ни на есть (ср.: самый что ни на есть).\nA E F B G — что бы то ни было; B... B — ни... ни, F... F — то... то, A B... F... — что ни... то (например: что ни встреча, то пьянка). Таким образом, искомое E = бы.\nСуть задания, очевидно, в простой догадке. Точки остаются на месте, вписываются только буквы.\nP. S. Вообще, трудно представить, как выполнить остальные задания (их 19; большая часть из них не менее, а иногда более трудна и сложна) за 1 час...\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29461,"cells":{"text":{"kind":"string","value":"Q:\n\nBatting averages of the Large Hadron Collider\n\nAs I understand it, the Large Hadron Collider's function is to throw particles into each other while avoiding hitting the nucleus? \nIf quantum mechanics dictate the position of a particle can only ever be an educated guess how accurate or reliable is the collider's standard results for a successful observation? Does it miss more than it hits?\nWhat happens if the nuclei collide, would their impact result in a nasty reaction that would destroy the collider at the least? \nI can go on, has it ever done so and what was the effect?\n\nA:\n\nMost of the time, the LHC is focusing opposite traveling bunches of protons, in a vacuum so as to avoid undesired collisions with nuclei, together at the various detector locations. No nucleus is involved unless the LHC is colliding heavy ions in which case, the ion nuclei collide and produce amazing images but no damage to the collider.\n\nAccording to one LHC FAQ:\n\nWhen the bunches cross, there will be only about 20 collisions among\n 200 billion particles. However, bunches will cross about 30 million\n times per second, so the LHC will generate up to 600 million\n collisions per second.\n\nA:\n\n As I understand it, the Large Hadron Collider's function is to throw particles into \n each other while avoiding hitting the nucleus?\n\nNo. In the nuclei are the quarks and trust me, we want to beat the crap out of them (the quarks) with as many direct hits as possible. \n If quantum mechanics dictate the position of a particle can only ever be an educated\n guess how accurate or reliable is the collider's standard results for a successful\n observation? Does it miss more than it hits?\n\nAs far as the uncertainty principal goes, its doesn't forbid you from creating states that still have very small uncertainty in space and momentum. In the case of the LHC the wavefunction of the protons is still fairly localized to a small peak that they send around the collider, outside of which there is a negligibly small chance of detecting the proton. So just because the proton is quantum mechanical doesn't mean there is an equal chance of detecting it anywhere in Geneva.\nFurthermore, what little uncertainty in the proton wave-packets there is, it isn't much of an issue as far as I can tell. Most of the time something is making contact when the beams cross. The real question is, how often does something interesting happen? It turns out not often - they don't bother recording something like >%99 of the data simply because nothing interesting happened. That is, an automated quick check of the data is performed to see if something triggered an interesting channel, if it doesn't they dump that data, and if something (possibly) interesting happens they store the data and look at in detail later all together. \n What happens if the nuclei collide, would their impact result in a nasty reaction that\n would destroy the collider at the least?\n\nThe nuclei collide all the time and the collider is still here. More importantly there is much higher energy processes happening all the time in the universe for a long time and we are still here.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29462,"cells":{"text":{"kind":"string","value":"Q:\n\nUnable to decrypt data - openssl_private_decrypt(): key parameter is not a valid private key\n\n \"C:\\wamp\\bin\\apache\\Apache2.4.4\\conf\\openssl.cnf\",\n \"private_key_bits\" => 2048,\n \"private_key_type\" => OPENSSL_KEYTYPE_RSA,\n );\n\n // Create the private and public key\n $res = openssl_pkey_new($config);\n\n if ($res === false) die('Failed to generate key pair.'.\"\\n\"); \n\n if (!openssl_pkey_export($res, $privKey, \"phrase\", $config)) die('Failed to retrieve private key.'.\"\\n\"); \n\n // Extract the private key from $res to $privKey\n openssl_pkey_export($res, $privKey, \"phrase\", $config);\n\n echo \"
\";\n echo \"Private Key = \".$privKey;\n echo \"
\";\n\n // Extract the public key from $res to $pubKey\n $pubKey = openssl_pkey_get_details($res);\n $pubKey = $pubKey[\"key\"];\n\n echo \"
\";\n echo \"Public Key = \".$pubKey;\n echo \"
\";\n\n $data = 'plaintext data goes here';\n\n // Encrypt the data to $encrypted using the public key\n openssl_public_encrypt($data, $encrypted, $pubKey);\n echo \"
\";\n echo \"Encrypted Data = \".$encrypted;\n echo \"
\";\n\n // Decrypt the data using the private key and store the results in $decrypted\n openssl_private_decrypt($encrypted, $decrypted, $privKey);\n\n echo \"
\";\n echo \"Decrypted Data = \".$decrypted;\n echo \"
\";\n?>\n\nLOGS\n\nPrivate Key = -----BEGIN ENCRYPTED PRIVATE KEY-----\n MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIr2acPfh8YYQCAggA\n MBQGCCqGSIb3DQMHBAiCvohdiWAZ4QSCBMjKJUXF5ShKfW3TazpKYTxEV8JmGYLf\n AJWXzxdi0GrDuddz4aW1FeGwvUm2t/41CTxFsWtgoQJrzCgAQETn54majdrDeF4u\n zCmvFMKSoVP4xsZKke15e1K1LPmFNNuKKyCqMwL+tpQJ7zquvDTKHapUnNzfNXpZ\n D2K1r2qZWeDN1d36DA9wkN5GbpZYAjuHqHUNzorhxIbHGp2WOg8YKdemoTuKIqYC\n DUKncWtxRUOx6IIZuey+uTBzH7Bn9K9a71QTjUdeWgQZFzy9yVpetB+XrJA92IWt\n vMeKXCXNhOgkOvkUPNXSuMOVrECNcbKDAKxmK3EQWqb+8zlYFqjmaL/sCep8ihio\n 1ZWpRaOd5HxnG5rpmz/BYzcF354mM8B4wAIk7MmFq/pHSKLjpr+2Ef1BpMmXfRpG\n Pj1jYDClSIQF6ovKOqhevFwfYrtl2jEOISyAggm/sbD750VBkwhbVAyQcarckAiI\n GlNcQPOC+JYZOV7o/9o+Tg24zwtAQ8y3hNvYyHjqYI5naVS9yuXEqB6zYoGivs/k\n bIblqTFebLEFtihjsa9wpXkyNzKD2NvdSa2oNC7IkCNi8TRNjy7MLylSmCIdhWAV\n YgL1hxShMgbnfiGjFQyYnKzZto9RqRlQBIoBOCfwP1EFnZjCJm02CCeGR+GHKXf7\n rJ0n6lIUEvVnENirAPtOuiE2ccbzmyjWQ9f2vwBSUea5nPTMG4uTVHrQjrgNYIyU\n +vLV6tL+MDKF4JGQGgzBUeqTMobmrOK+V20QIasYaAWHJrL8itBwZ++C8lo7kySa SImMXakI4rjgEmj+HmUJygT1EZWz5yQqOiwAYLhQZg+m6+32Pvt6mIrAXbznrdHP\n JxHb/9HV88mQdRKPBTkSTl71Ics+3oybYPbhSQByXOdtsw6VLYNo4ikgj3tXCz01\n DwVQqeQ5tLD4LY8/QaAHkOUq9K24yfkcN+aQh7cvR/HX53Ls6LsdUwkwSOWVj2na\n Wl4xn+j3ZaPhpgdzcMgknU7BAI2kZP83MxyKnNcnneyX4hTaM5PRZJXKd+onvhff\n nQ3zHDSYmRDKmTXBjCob3Vjg91LcMjg9dEH7aIFWit5dHK4ll/v1IiOFx8d4d/mV\n Oll0c0ujJuPjtyqesM2Bz3Ah5YkIT2Z7kxvRy7rTyytQG7hLNENAki9wW79fcEo7\n ln/OvEpjdWZngkL/UrMOX8DBrs0PLEH9jyDoCQx/LSqxMAXOwVXILfsfsUFu0M0o\n 21YbeC33jOlocJ4Q6pwfRVz8lCQOuIVs1jEpvSmvHgvmHmXUI4Y6nZD4Roi0jIjS\n VvI73eULzc3j0jIptWxzrHWM6iHx1zRxkLMJSZOx0A27ngtSo7g6+aJnMO5FDfdR\n 90vnr+bX4ki+X/N4wVF7eppyapLe/tQ54vAxsyIBrCXPjwBMehiFjOMhzSLW7xQj\n Qg2KcilfW6oKFzDQQ5nKPEXvQYMhQ1MeWKyNv6BMoc4EEpIGhtziUXWhgT4sN1ES\n 5sxVcGVoIe1viO/kk3Zq55hETlZbNWs3V511BcEZCiQNrntnbYv6pwKpoB21ZV2E\n slVhYcslEGliIQKQsWSl5cfc+pqjLteiPrwk14WKJGXl9zX3YH6H7KKB/7SIRZk7 wq8=\n -----END ENCRYPTED PRIVATE KEY-----\nPublic Key = -----BEGIN PUBLIC KEY-----\n MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAriS8qflAjYSYhH2qgC5T\n yf98X1qoLMXIW9mMkhV8LcApBKOfNjUMc9xjD3a8CR/LYwa4MYhevoKcVfPG8XoE\n sDGyHh+h/vtYP0rORB1T3RULVUzDLjX558e2KqPrSN+rV+Jl1NB0SO5Of3JA+AKa\n 0Q3botcjOM3WuFa/s+RzsiCrMMhzOZSTBj+GTP/VcDipF5PM7+/Lxr+edjRXccT2\n WQjsq0sUrtsmpzBE8Niph361RjfIisxKoksQGs7hC/Iv4yhBzZZIpRaZuvDj4ImP\n +4sUQgbdVVCso122kg34UtY5qchuSCcJfsGbD2zMw+8ZftIsJ7dfX1FxujgggDyn 0wIDAQAB -----END PUBLIC KEY-----\n\nEncrypted Data = Uš6/ùÅËæÝmL4²G¾'gr¨Ñ­Ä‰ï‚zêbÀ)[îR0s‹yÝ`t™õ°Þe­Ïd>×o¯rß9ÌÔÅAü!-†D·¨ÎVZ¼?¶éžäýöaØT~=‚Fan¢ºq{M”ƒ¹Cû5N3¹.Ð(·#*ÏRƹñß÷õƒ_ò9c-Ÿ% ×óè2Ꙃõ“ÂÐgNÈ-ˆd«…ºt§¼Ô}yŠ\"7èPš(¶R¤ßJÚ_h¶ðÞK(Cj“7‘Y ÀŠþrôZƒ4)JU•˜„üˆ k0â§Êë^ÚºGÚªúVKø†ë8ÏLÚó „Ÿ¦¿¤\n\n( ! ) Warning: openssl_private_decrypt(): key parameter is not a valid private key in C:\\wamp\\www\\android\\pki_example.php on line 41\nCall Stack\n# Time Memory Function Location\n1 0.0020 252696 {main}( ) ..\\pki_example.php:0\n2 0.2043 258032 openssl_private_decrypt ( ) ..\\pki_example.php:41\n\nDecrypted Data = \n\nA:\n\n// Decrypt the data using the private key and store the results in $decrypted\nopenssl_private_decrypt($encrypted, $decrypted, openssl_pkey_get_private($privKey, \"phrase\"));\n\necho \"
\";\necho \"Decrypted Data = \".$decrypted;\necho \"
\";\n\nopenssl_private_decrypt function is capable to use PEM formatted private key but your key is encrypted and this function does not have an argument for password. You have to use openssl_pkey_get_private instead.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29463,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can I extend the category products Rest API?\n\n/V1/categories/(cat ID)/products\nThis API provides very less detail of all the products. \n{\n \"sku\": \"Nike 3 color half sleeve tshirt\",\n \"position\": 1,\n \"category_id\": \"3\"\n },\n {\n \"sku\": \"Louis Phillipe Blue Jean Size 32\",\n \"position\": 1,\n \"category_id\": \"3\"\n },\n {\n \"sku\": \"Louis Phillipe Shirt Size M\",\n \"position\": 1,\n \"category_id\": \"3\"\n },\n {\n \"sku\": \"UCB shirt Size \",\n \"position\": 1,\n \"category_id\": \"3\"\n },\n\nI can use the sku in a search filter to get all the produts with these sku's. But is there a better way around ?\n\nA:\n\nIt is possible to use filter by category_id during request to Product Repository: \nGET /rest/V1/products\nIf it is necessary to filter by store_id or website_id at the same time, see workaround here.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29464,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to re-initialise (state) array variable in react-native?\n\nI'm making an API call.\nAnd I'm getting response as : \nvar data =\n[\n {a: 'a', b: 'b'}\n]\n\nAnd I want to set value of variable in state as data.\nBut it's not working . Giving error as =>\n\nObjects are not valid as a React child\nEx: -\nstate = {\nstateVariable: []\n}\napiCall.then((data) => {\n this.setState({ stateVariable: data })\n})\n\nA:\n\nObjects are not valid as a React child\n\nIn react, you cannot render an object directly.\nI feel you are trying to do something like this\n{this.state.stateVariable}\n\nIt will not work because the value in there is an array.\nTo fix this, you can map it:\n{this.state.stateVariable.map(data => {data.a} {data.b})}\n\nSecondly, You may already be mapping it or looping it but you're still getting the error. This is because if you render just data as in my map above, it is an object {a:'a', b:'b'} and this is not allowed in react. \nSo you have to make it {data.a} or {data.b}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29465,"cells":{"text":{"kind":"string","value":"Q:\n\nObject History Related List in Lightning Experience\n\nI found that Object History related list isn't supported in Lightning Experience : https://success.salesforce.com/ideaView?id=08730000000LgQWAA0 . I need to show it in Lightning; is there any way to show the Related History on Contact (in lightning) without creating a new object.\n\nThanks!\n\nA:\n\nI tried to track few standard and custom field on Contact using Field History Tracking. In lightning, it doesn't seem to show the \"Contact History\" related list and its history records at all even if you add it to the page layout.\nThe only way I could do is to switch to \"Classic View\" and see the field changes in Contact History related list for the contact record.\nIf you need to see this working in Lightning, We will have to wait till the following idea (https://success.salesforce.com/ideaView?id=08730000000LgQWAA0) gets incorporated by Salesforce.\nUpdate:\nThis has been delivered in Summer 17, for those who are still looking.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29466,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do i get facebook album id from url?\n\nIm trying to publish to an album on a facebook page (I can post to the wall no problem - i have all the permissions). \nThe Facebook graph API says the album id is the value of aid. But the url looks like: https://www.facebook.com/media/set/?set=a.531274833612778.1073741825.193687907371474&type=3\nSo what is the album id?\n\nA:\n\nFor the sake of this question having an answer (I missed out @CBroe comment the first time I landed here).\nThe album ID is the first number right between a. and the next following . (dot).\nIn this case: 531274833612778\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29467,"cells":{"text":{"kind":"string","value":"Q:\n\ntidyr quasiquotation with lexical scoping\n\nI realize that tidy evaluation does not use lexical scoping, but I want the quasiquotation in rlang to look for symbols in the environment I decide.\nCurrent behavior:\nenvir <- new.env(parent = globalenv())\neval(parse(text = \"little_b <- 'b'\"), envir = envir)\neval(rlang::expr(!!little_b), envir = envir)\n\n## Error in (function (x) : object 'little_b' not found\n\nInstead, I want the last line to return \"b\". Bonus points if you find a version of eval() that does the job here AND works like evaluate::try_capture_stack().\nFYI: I am trying to solve this issue. \n\nA:\n\nWe can use with to pass the expression within an environment\nwith(envir, expr(!!little_b))\n#[1] \"b\"\n\nOr another option is local\nlocal(rlang::expr(!!little_b), envir = envir)\n#[1] \"b\"\n\nOr pass via quote in eval (as @lionel mentioned)\neval(quote(expr = rlang::expr(!! little_b)), envir = envir)\n#[1] \"b\"\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29468,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to set y axis limits when using map2(~ggplot...?\n\nHow can I set different y axis limits in each plot when using purrr::map2?\nI would like to set the y-axis lower limit to half the maximum y-axis value, something like: max(y-axis value/2).\ndata(mtcars)\n\nlibrary(tidyverse)\n\nmtcars_split <- \n mtcars %>%\n split(mtcars$cyl)\n\nplots <- map2(\n mtcars_split,\n names(mtcars_split),\n ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + \n geom_jitter() +\n ggtitle(.y)+\n scale_y_continuous(limits=c(max(.y)/2,NA))\n\n)\n\nplots\n\nError in max(.y)/2 : non-numeric argument to binary operator\n\nA:\n\n.y is the name of the dataframe, which is why max(.y)/2 is giving you that error. This should give you what you want:\nplots <- imap(\n mtcars_split,\n ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + \n geom_jitter() +\n ggtitle(.y) +\n scale_y_continuous(limits=c(max(.x$mpg)/2,NA))\n)\n\nNote that imap(x, ...) is just shorthand for map2(x, names(x), ...).\n\nA:\n\nThis doesn't work based on the y-axis value, but it gets the job done if you don't mind specifying your y-column twice:\nplots <- map2(\n mtcars_split,\n names(mtcars_split),\n ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + \n geom_jitter() +\n ggtitle(.y)+\n scale_y_continuous(limits=c(max(.x$mpg)/2,NA))\n\n)\n\nOr maybe a safer option:\nplots <- map2(\n mtcars_split,\n names(mtcars_split),\n ~{\n ploty <- 'mpg'\n plotx <- 'wt'\n ggplot(data = .x, mapping = aes_string(y = ploty, x = plotx)) + \n geom_jitter() +\n ggtitle(.y)+\n scale_y_continuous(limits=c(max(.x[[ploty]])/2,NA))\n }\n)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29469,"cells":{"text":{"kind":"string","value":"Q:\n\nNode.js Ubuntu Installation\n\nI am following instructions from as someone suggested on stackoverflow:\n\nhttp://www.giantflyingsaucer.com/blog/?p=2284\n\nAfter following all the steps when I command \ngit clone https://github.com/joyent/node.git && cd node\n\nit shows \ncloning..... \nerror: RPC failed; result=56, HTTP code = 100\nfatal: The remote end hung up unexpectedly\n\nI am using Ubuntu, terminals, etc. for the very first time. Can you please suggest what to do? Is there any problem with the configuration?\nThanks in advance for bearing such a question...\n\nA:\n\nIf you are new to using node, I would suggest instead of bothering with git just download the source straight from nodejs.org.\nChoose the 0.4.11 branch, its more stable.\nFrom there, follow these directions:\nsudo apt-get install libssl-dev (may not be needed, but good idea anyways)\ncd *your download dir*\ntar xvf node-v0.4.11.tar.gz\ncd node-v0.4.11\n./configure\nmake\nsudo make install\n\nIf that still seems to cause problems, this site allows you to quickly create an install script for node, your mileage may vary with it.\n\nA:\n\nAs others stated above, what's included in the standard repo is quite old.\nThe following is a decent solution on Ubuntu 11 or higher:\nsudo add-apt-repository ppa:chris-lea/node.js\nsudo apt-get update\nsudo apt-get install nodejs\n\nA:\n\nYou're on Ubuntu. Is there a reason not to install the package?\nsudo apt-get install nodejs\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29470,"cells":{"text":{"kind":"string","value":"Q:\n\nCreating a formula which references a Variable in WEBI Business Objects\n\nI am using a formula to successfully convert a number of minutes into \"HH:mm\" format-\n=ToDate(If((IsNull([Totalmins])) Or([Totalmins] = 0 )) Then (\"00:00\") Else FormatNumber(Floor([Totalmins] /60) ;\"00\") + \":\" + FormatNumber(Floor(Mod([Totalmins] ;60)/1) ;\"00\");\"HH:mm\")\n\nThis works fine where Totalmins is an absolute number. However I also want to convert the SUM of the Totalmins column into HH:mm format, but I can't get it to work.\nI have tried creating a variable called TotalMinSum which is \"=Sum([Totalmins])\", and referenced it from the same formula- \n=ToDate(If((IsNull([TotalMinSum])) Or([TotalMinSum] = 0 )) Then (\"00:00\") Else FormatNumber(Floor([TotalMinSum] /60) ;\"00\") + \":\" + FormatNumber(Floor(Mod([TotalMinSum] ;60)/1) ;\"00\");\"HH:mm\")\n\n...but this does not work. It just gives me an #ERROR.\nDoes anybody know how I can do this?\n\nA:\n\nFigured it out myself. Went into Designer and added a variable into the universe with the value of sum(@Select(ProjectTotals\\Totalmins)). I am now able to use this in the report as if it is an absolute value.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29471,"cells":{"text":{"kind":"string","value":"Q:\n\nFor linear quadratic approximation of RBC model, why does matrix $P$ of value function $V = F^TPF$ has to be negative semi-definite matrix?\n\nIn http://www.compmacro.com/makoto/note/note_rbc_lq.pdf page 5, it is said that for value function $V = F^TPF$ (Bellman equation) $P$ has to be negative semi-definite matrix. Why does it have to be negative semi-definite?\n\nA:\n\nP being negative semi-definite would imply that V is a concave function. The reason you would restrict P so that V would be a concave function is because of some of the assumptions you've made about about the model previously tell you that V must be concave.\nIn general, some of the typical assumptions that imply that the value function must be concave are something like the following:\n\nthe graph of the constraint correspondence is convex,\nthe period return function is concave,\nother assumptions about the stochastic transition function having the Feller property and being monotone,\netc...\n\nSorry I'm not giving the full details, but you can read more about them in chapters 4 and 9 of \"Recursive Methods in Economic Dynamics\" by Stokey, Lucas, and Prescott. The point that I'm making is that the assumptions of these kinds of models usually imply that the value function is concave. Therefore, if you check the assumptions and they indeed do so restrict the value function, then you can restrict your search to look only for matrices P that are negative semi-definite.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29472,"cells":{"text":{"kind":"string","value":"Q:\n\nUncaught (in promise) TypeError: Cannot call a class as a function\n\nI recently upgraded my babel versions to latest. After update the normal class is not recognized by babel in my react application and I am getting below error. \n\nUncaught (in promise) TypeError: Cannot call a class as a function\n\n.babelrc\n{\n \"presets\": [\n \"env\", \n \"react\"\n ],\n \"plugins\": [\n \"transform-class-properties\",\n \"transform-object-rest-spread\"\n ]\n}\n\nbabel related libs in my app:\n\"babel-core\": \"^6.26.3\",\n\"babel-eslint\": \"^8.2.6\",\n\"babel-jest\": \"^22.4.3\",\n\"babel-loader\": \"^7.1.5\",\n\"babel-plugin-transform-class-properties\": \"^6.24.1\",\n\"babel-plugin-transform-object-rest-spread\": \"^6.26.0\",\n\"babel-polyfill\": \"^6.26.0\",\n\"babel-preset-env\": \"^1.7.0\",\n\"babel-preset-react\": \"^6.24.1\"\n\nbabel doesn't understand this class\nCRUDTree.js\nconst resourceBoxWidth = 225;\nconst resourceBoxHeight = 85;\nconst halfBoxWidth = resourceBoxWidth / 2;\nconst halfBoxHeight = resourceBoxHeight / 2;\nconst urlLeftMargin = 10;\nconst urlFontSize = 12;\nconst fullPathFontSize = 10;\nexport default class{\n static resourceBoxWidth() { return resourceBoxWidth; }\n static resourceBoxHeight() { return resourceBoxHeight; }\n static halfBoxHeight() { return halfBoxHeight; }\n static halfBoxWidth() { return halfBoxWidth; }\n}\n\nAPITree.js\nimport React, { Component } from 'react';\nimport CRUDTree from './CRUDTree';\n\nclass extends Component{\nrender(){\nreturn(\n \n)\n}\n}\n\nA:\n\nIf your CRUDTree is a React component (it seems as it is to me) then you are defining it wrong. You are missing the extends part.\nexport default class extends React.Component {\n ....\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29473,"cells":{"text":{"kind":"string","value":"Q:\n\nUILabel Subclass appears as UILabel in Objective-C\n\nI'm a experienced C++ programmer trying to create my first Objective-C subclass of UILabel with an added read-only property\n// UINumericlabel.h\n@interface UINumericLabel : UILabel\n\n// Returns true if the numeric display contains a decimal point\n@property (readonly,nonatomic) BOOL hasDecimalPoint;\n@end\n\n// UINumericLabel.m\n\n#import \"UINumericLabel.h\"\n\n@implementation UINumericLabel\n// Returns true if the numeric display contains a decimal point\n- (BOOL) hasDecimalPoint;\n{\n return [self.text rangeOfString:(@\".\")].location != NSNotFound;\n}\n@end\n\nWhen I try to reference the hasDecimalPoint property for an instantiated UINumericLabel I get an abort with error\n\n2012-02-20 18:25:56.289 Calculator[10380:207] -[UILabel hasDecimalPoint]: unrecognized selector sent to instance 0x684c5c0\nIn the debugger it shows my declaration of a UINumericLabel property as being a UILabel *\nDo I need to override the (id)init for UILabel in my UINumericLabel subclass? How do I do that?\n#import \"UINumericLabel.h\"\n\n@interface CalculatorViewController : UIViewController \n@property (weak, nonatomic) IBOutlet UINumericLabel *display0;\n@end\n\nWhen I hover over display0P in the debugger it says it is a UILabel * not a UINumericLabel *\nUINumericLabel * display0P = self.display0;\n\nA:\n\nIn the Interface Builder select the label and then open the Identity Inspector. In the text field \"Class\" it probably says UILabel. Change that to be your new subclass, UINumericLabel.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29474,"cells":{"text":{"kind":"string","value":"Q:\n\nDiscrepancy in using adjective or adverb with “taste”\n\nOne asks “how does x taste,” implying that they’d like an adverb describing the way it tastes. But one answers with an adjective, “it tastes good” instead of “it tastes well,” which would imply that x is tasting something else. What’s the reason for this discrepancy?\n\nA:\n\nIs it good? Or do you feel sick?\nIt’s pretty easy to think of other verbs like this, so there’s no discrepancy. These are linking verbs and the adjective is the subject compliment.\n\nA subject complement is the adjective, noun, or pronoun that follows a linking verb.\nThe following verbs are true linking verbs: any form of the verb be [am, is, are, was, were, has been, are being, might have been, etc.], become, and seem. These true linking verbs are always linking verbs.\nThen you have a list of verbs that can be linking or action: appear, feel, grow, look, prove, remain, smell, sound, taste, and turn. If you can substitute any of the verbs on this second list with an equal sign [=] and the sentence still makes sense, the verb is almost always linking.\nGrammar Bytes — The Subject Complement: Recognize a subject complement when you see one.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29475,"cells":{"text":{"kind":"string","value":"Q:\n\nIssue with Java threads, using Runnable or Thread\n\nI'm trying to implement multi-threading using merge sort. I have it making new threads at the point where it cuts an array in half.\nThe array is sorted depending on the:\n[size of the array] vs [how many times I create new threads]\nFor instance: the array will be sorted if I let it create merely two threads on an array of size 70, but if I let it create 6, it will come back unsorted. One thing I thought it might be is that the threads weren't sync'd, but I used threadName.join()\nhere is some code: merge.java\nimport java.util.Random;\n\npublic class merge implements Runnable {\n int[] list;\n int length;\n int countdown;\n\n public merge(int size, int[] newList, int numberOfThreadReps, int firstMerge) {\n length = size;\n countdown = numberOfThreadReps;\n list = newList;\n if (firstMerge == 1)\n threadMerge(0, length - 1);\n }\n\n public void run() {\n threadMerge(0, length - 1);\n }\n\n public void printList(int[] list, int size) {\n for (int i = 0; i < size; i++) {\n System.out.println(list[i]);\n }\n }\n\n public void regMerge(int low, int high) {\n if (low < high) {\n int middle = (low + high) / 2;\n regMerge(low, middle);\n regMerge(middle + 1, high);\n mergeJoin(low, middle, high);\n }\n }\n\n public void mergeJoin(int low, int middle, int high) {\n int[] helper = new int[length];\n\n for (int i = low; i <= high; i++) {\n helper[i] = list[i];\n }\n\n int i = low;\n int j = middle + 1;\n int k = low;\n\n while (i <= middle && j <= high) {\n if (helper[i] <= helper[j]) {\n list[k] = helper[i];\n i++;\n } else {\n list[k] = helper[j];\n j++;\n }\n k++;\n }\n while (i <= middle) {\n list[k] = helper[i];\n k++;\n i++;\n }\n helper = null;\n }\n\n public void threadMerge(int low, int high) {\n if (countdown > 0) {\n if (low < high) {\n countdown--;\n int middle = (low + high) / 2;\n int[] first = new int[length / 2];\n int[] last = new int[length / 2 + ((length % 2 == 1) ? 1 : 0)];\n for (int i = 0; i < length / 2; i++)\n first[i] = list[i];\n for (int i = 0; i < length / 2 + ((length % 2 == 1) ? 1 : 0); i++)\n last[i] = list[i + length / 2];\n\n merge thread1 = new merge(length / 2, first, countdown, 0);// 0\n // is\n // so\n // that\n // it\n // doesn't\n // call\n // threadMerge\n // twice\n merge thread2 = new merge(length / 2\n + ((length % 2 == 1) ? 1 : 0), last, countdown, 0);\n\n Thread merge1 = new Thread(thread1);\n Thread merge2 = new Thread(thread2);\n merge1.start();\n merge2.start();\n\n try {\n merge1.join();\n merge2.join();\n } catch (InterruptedException ex) {\n System.out.println(\"ERROR\");\n }\n\n for (int i = 0; i < length / 2; i++)\n list[i] = thread1.list[i];\n for (int i = 0; i < length / 2 + ((length % 2 == 1) ? 1 : 0); i++)\n list[i + length / 2] = thread2.list[i];\n\n mergeJoin(low, middle, high);\n } else {\n System.out.println(\"elsd)\");\n }\n } else {\n regMerge(low, high);\n }\n }\n}\n\nproj4.java\nimport java.util.Random;\n\npublic class proj4 {\n public static void main(String[] args) {\n int size = 70000;\n int threadRepeat = 6;\n int[] list = new int[size];\n list = fillList(list, size);\n list = perm(list, size);\n merge mergy = new merge(size, list, threadRepeat, 1);\n // mergy.printList(mergy.list,mergy.length);\n for (int i = 0; i < mergy.length; i++) {\n if (mergy.list[i] != i) {\n System.out.println(\"error)\");\n }\n }\n }\n\n public static int[] fillList(int[] list, int size) {\n for (int i = 0; i < size; i++)\n list[i] = i;\n return list;\n }\n\n public static int[] perm(int[] list, int size) {\n Random generator = new Random();\n int rand = generator.nextInt(size);\n int temp;\n for (int i = 0; i < size; i++) {\n rand = generator.nextInt(size);\n temp = list[i];\n list[i] = list[rand];\n list[rand] = temp;\n }\n return list;\n }\n\n}\n\nso TL;DR my array isn't getting sorted by a multithreaded merge sort based on the size of the array and the number of times I split the array by using threads...why is that?\n\nA:\n\nWow. This was an interesting exercise in masochism. I'm sure you've moved on but I thought for posterity...\nThe bug in the code is in mergeJoin with the middle argument. This is fine for regMerge but in threadMerge the middle passed in is (low + high) / 2 instead of (length / 2) - 1. Since in threadMerge low is always 0 and high is length - 1 and the first array has (length / 2) size. This means that for lists with an odd number of entries, it will often fail depending on randomization.\nThere are also a number of style issues which makes this program significantly more complicated and error prone:\n\nThe code passes around a size of the arrays when Java has a convenient list.length call which would be more straightforward and safer.\nThe code duplicates calculations (see length/2) in a number of places.\nThe code should be able to sort inside the array without creating sub-arrays.\nClasses should start with an uppercase letter (Merge instead of merge)\nfirstMerge should be a boolean\nThe code names the Thread variable merge1 and the merge variable thread1. Gulp.\nThe merge constructor calling threadMerge(0,length -1) is strange. I would just put that call after the new call back in proj4. Then firstMerge can be removed.\nI would consider switching to having high be one past the maximum value instead of the maximum. We tend to think like for (int i = 0; i < 10; i++) more than i <= 9. Then the code can have j go from low to < middle and k from middle to < high. Better symmetry.\n\nBest of luck.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29476,"cells":{"text":{"kind":"string","value":"Q:\n\nAny news on the graduation from beta?\n\nGiven the performance of the beta site. How do we know if and when a graduation is in order?\n\nA:\n\nI've been monitoring this beta's site activity on Area51 Stack Exchange dashboard and Stack Exchange sites overview very closely. From what I can tell, the main statistics I've been looking at is the questions per day indicator and if you only look at this rate (currently around 14 questions asked per day), Ethereum Stack Exchange is the most active beta site in the network (followed by Adruino (13), Mechanics (11) and Gardening (10)).\nHowever, site activity might be the main indicator for graduation, but there are also some other soft factors that also play an important role.\n\nUser base: This site wont graduate until it has a solid (and maintains an active) user base. The stats on Area51 might be misleading as they are probably placing the mininmung requirements too low (compare mechanics user base to our's on Area51 for instance, they are also waiting for graduation). I think we wont recieve a graduation notice unless we have at least 5 users above 10k reputation (a.k.a. access to moderator tools privilege) and a dozen users above 3k reputation (a.k.a. cast open and close votes privilege).\nMeta activity: This site is very active on the main topic, but the activity on meta is currently very low. We need to get more involved with defining what this site actually is, e.g., what is on topic, what is off topic, what is our topic, what should our documentation contain, etc. pp.? See also our current challenge. To get an interesting insight into beta progress updates by the community, you can follow this August 2015 and that January 2016 report on the Adruino beta site.\n\nSo, if you want to speed up graduation process, you can do multiple things for now.\n\nAsk 1 good question a day, this wont keep graduation away.\nVote good content up, vote low quality content down. This will separate the wheat from the chaff, and also will generate reputation for users and maintain a solid userbase.\nGet involved in meta. You are invited to discuss, debate and propose changes to the way the Ethereum Stack Exchange community itself behaves (discussions), as well as how the software itself works (bugs, features, support).\n\nThanks for coming to meta and helping out to mature this site.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29477,"cells":{"text":{"kind":"string","value":"Q:\n\nCSS selector issues\n\nI am very bad with selectors, I am trying to figure out how to make a transition happen on my form when I hover over the \"create one\" link. Can anyone help me?\nhttp://jsfiddle.net/LyZxG/\nbody:hover .form{}\n\nthe fiddle above shows all of my code, I currently have it transitioning from \"body:hover\" so you can see the transition.\nThanks in advance!\nps. I have ready every form about selectors and cant figure it out, I know its simple I'm just not getting it, thank you again.\n\nA:\n\nOK with just css all you need to do is remove the\nbody:hover .form{}\n\nadd and in \n.create-link:hover .form{\nopacity:1.0;\n width:260px;\n}\n\nAfter you do that you will need to update your create link html to this\n
  • \n \n

    Create One

    \n
    \n First name:
    \n Last name:
    \n Password: \n \n
    \n
  • \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29478,"cells":{"text":{"kind":"string","value":"Q:\n\nexistence of de Rham complexes\n\nI have a very basic question about the exterior derivative of differential forms and de Rham complexes. It is very basic, I know that the exterior derivative satisfies $d^2=0$. Knowing that, how is a de Rham complex even possible ?\nMy definition of a de Rham complex is the following :\nLet $M$ be a manifold of dimension $n$, the de Rham complex is the following chain :\n$$ 0 \\xrightarrow[]{d} \\Omega ^{0}(M) \\xrightarrow[]{d} \\Omega ^{1}(M) \\xrightarrow[]{d} ... \\xrightarrow[]{d} \\Omega ^{m}(M) \\xrightarrow[]{d} 0 $$\nMy question : since $d^2 =0$, shouldn't we always have that $\\Omega ^2 (M) = 0$ ?\nThank you very much for your help\n\nA:\n\n$\\Omega^2(M)$ is the space of all the differential $2$-forms on $M$. You have $d(\\Omega^1(M))\\subseteq\\Omega^2(M)$ and $d^2(\\Omega^0(M))\\subseteq d(\\Omega^1(M))\\subseteq\\Omega^2(M)$. As you said, $d^2(\\Omega^0(M))=\\{0\\}$, but there's no reason why $d^2(\\Omega^0(M))$ would be equal to $\\Omega^2(M)$.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29479,"cells":{"text":{"kind":"string","value":"Q:\n\nSolving a pair of ODEs\n\nI'm trying to solve a pair of ODEs for which I've obtained a solution. However, my problem is that my answer is slightly different from mathematica's answer. \n$$ \\frac{dA}{dt} = \\theta - (\\mu + \\gamma)A, \\ \\ A(0) = G$$\n$$ \\frac{dT}{dt} = 2 \\mu A - (\\mu + \\gamma)T, \\ \\ T(0) = B$$\nUsing an integrating factor of $e^{(\\mu + \\gamma)t}$, I got the following solution to the first ODE: \n$$ A(t) = \\frac{\\theta}{\\mu + \\gamma} + \\left(G -\\frac{\\theta}{\\mu + \\gamma}\\right)e^{-(\\mu + \\gamma)t}$$\nFor simplicity, let $\\mu + \\gamma = \\alpha$ such that:\n$$ A(t) = \\frac{\\theta}{\\alpha} + \\left(G -\\frac{\\theta}{\\alpha}\\right)e^{-\\alpha t}$$\nFor the second ODE (again using an integrating factor of $e^{(\\mu + \\gamma)t}= e^{\\alpha t}$ ):\n$$ e^{\\alpha t}\\frac{dT}{dt} + e^{\\alpha t}\\alpha T = 2 \\mu A e^{\\alpha t} $$\n$$ T(t)e^{\\alpha t} = \\int 2 \\mu e^{\\alpha t}\\left(\\frac{\\theta}{\\alpha} + \\left(G -\\frac{\\theta}{\\alpha}\\right)e^{-\\alpha t}\\right)dt $$\n$$ T(t) = \\frac{2 \\mu \\theta}{\\alpha^2} + \\left(B - \\frac{2 \\mu \\theta}{\\alpha^2}\\right)e^{-\\alpha t} $$\nHowever, when I computed these two ODEs in mathematica, it gave back the following solution:\n$$ T(t) = Be^{-\\alpha t} + 2G \\mu te^{-\\alpha t}+ \\frac{2 \\mu \\theta}{\\alpha^2} - \\frac{2 \\mu \\theta e^{-\\alpha t}}{\\alpha^2} - \\frac{2 \\mu \\theta t e^{-\\alpha t}}{\\alpha} $$\nI've tried solving my equation over and over again but I can't seem to understand why my solution is different from mathematica's. The only I thought about was possibly in the substitution of arbitrary constant. Am I missing something obvious here?\n\nA:\n\nYou forgot the integration constant. Following on from your integral for $T(t)$, we find\n\\begin{align}\nT(t)e^{\\alpha t} &= \\int 2 \\mu e^{\\alpha t}\\left(\\frac{\\theta}{\\alpha} + \\left(G -\\frac{\\theta}{\\alpha}\\right)e^{-\\alpha t}\\right)dt \\\\\n&= \\int 2 \\mu e^{\\alpha t}\\left(\\frac{\\theta}{\\alpha}\\right) + 2 \\mu \\left(G -\\frac{\\theta}{\\alpha}\\right) dt \\\\\n&= 2 \\mu e^{\\alpha t}\\left(\\frac{\\theta}{\\alpha^{2}}\\right) + 2 \\mu \\left(G -\\frac{\\theta}{\\alpha}\\right)t + C \\\\\n\\implies T(t) &= 2 \\mu \\left(\\frac{\\theta}{\\alpha^{2}}\\right) + 2 \\mu \\left(G -\\frac{\\theta}{\\alpha}\\right)t e^{-\\alpha t} + Ce^{-\\alpha t} \\\\\nT(0) &= B \\\\\n&= 2 \\mu \\left(\\frac{\\theta}{\\alpha^{2}}\\right) + C \\\\\n\\implies C &= B - 2 \\mu \\left(\\frac{\\theta}{\\alpha^{2}}\\right) \\\\\n\\implies T(t) &= 2 \\mu \\left(\\frac{\\theta}{\\alpha^{2}}\\right) + 2 \\mu \\left(G -\\frac{\\theta}{\\alpha}\\right)t e^{-\\alpha t} + \\bigg(B - 2 \\mu \\left(\\frac{\\theta}{\\alpha^{2}}\\right) \\bigg)e^{-\\alpha t} \\\\\n&= \\frac{2 \\mu \\theta}{\\alpha^{2}} + 2 \\mu G t e^{-\\alpha t} - \\frac{2 \\mu G \\theta}{\\alpha}t e^{-\\alpha t} + B e^{-\\alpha t} - \\frac{2 \\mu \\theta}{\\alpha^{2}} e^{-\\alpha t} \\\\\n&= B e^{-\\alpha t} + 2 \\mu G t e^{-\\alpha t} + \\frac{2 \\mu \\theta}{\\alpha^{2}} - \\frac{2 \\mu G \\theta}{\\alpha}t e^{-\\alpha t} - \\frac{2 \\mu \\theta}{\\alpha^{2}} e^{-\\alpha t}\n\\end{align}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29480,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat is the default 'backup' user for?\n\nI am setting up multiple-machine backup plan and I was hoping to use a user called 'backup' on each machine as the backup destination. \nMy problem is, there is already a user called 'backup' on my machine.\nWhat is it for, and can I hijack it for my own purposes?\nroot@frodo:~# useradd backup\nuseradd: user 'backup' already exists\n\nA:\n\nI can confirm it's in a default installation, see the /usr/share/base-passwd/passwd.master file provided by the base-passwd package.\nAccording to the documentation from that package, it is used for backup accounts without requiring full root permissions (which is available at /usr/share/doc/base-passwd/users-and-groups.txt.gz, /usr/share/doc/base-passwd/users-and-groups.html and online):\n\nbackup\nPresumably so backup/restore responsibilities can be locally delegated to\n someone without full root permissions?\nHELP: Is that right? Amanda reportedly uses this, details?\n\nNote the keyword locally, for remote backups you have to enable a login shell first. You are free to use it for your own purposes, but note the above guide lines. Do not grant sudo policies for example that would allow the backup user to escalate its privileges to root.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29481,"cells":{"text":{"kind":"string","value":"Q:\n\nTestNG class with Factory and Dataprovider never works\n\nI have a jar calculator library. I made a simple class to test 'sum' function with Factory and DataProvider like in many examples. But when i run it i see: no test's executed. If i delete Factory and write DataProvider to a Test annotation - everything works fine.\npublic class SumTest {\n\n Calculator calc = new Calculator();\n private final double a;\n private final double b;\n\n @Factory(dataProvider = \"getValues\")\n public SumTest(double aValue, double bValue) {\n this.a = aValue;\n this.b = bValue;\n this.calc = new Calculator();\n }\n\n @Test\n public void testSum() {\n Assert.assertEquals(a + b, calc.sum(a, b));\n }\n\n @DataProvider\n public Object[][] getValues() {\n return new Object[][]{\n {10, 5},\n {-10, 5},\n {11.55, -10.55},\n {-5, -6},\n {99999.8d, 1l},\n {9223372036854775807L, 9223372036854775807L}\n };\n }\n\n}\n\nA:\n\nDataProvider needs to be Static to make Factory Work.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29482,"cells":{"text":{"kind":"string","value":"Q:\n\nglBindAttribLocation whats next?\n\nI'm struggling to find OpenGL/GLSL examples that don't require glew or glut or what have you.\nI'm trying to work with only using glfw3 (if possible I would like to use no other libraries) and I'm struggling to understand what to do once I use glBindAttribLocation? I've written code to pass an image as a texture into shaders, but I can't figure how to pass vertices.\nI have a vertex shader and fragment shader I want to make a triangle and then color it red, I can create the shader programs and object program and link everything, but how do I pass things to the shaders.\n// vert\nin vec3 vPosition;\n\nvoid main()\n{\n gl_Position = vec4(vPosition,1.0);\n}\n\n// Frag\nout vec4 color;\nvoid main()\n{\n color = vec4(1.0,0.0,0.0,1.0);\n}\n\nI don't understand what I need to do after I call glBindAttribLocation\nglBindAttribLocation(p,0,\"vPosition\");\nglUseProgram(p);\n\nnow how do I pass the vertices of a triangle into the shader?\nmore code, I'm calling my own library to read in the files so the textread won't work if anyone tries to run it\n#include \n\n#include \n#include \n\n#include \"src/textfile.h\"\n\nGLuint v,f,p;\n\nvoid printLog(GLuint obj)\n{\n int infologLength = 0;\n int maxLength;\n\n if(glIsShader(obj))\n glGetShaderiv(obj,GL_INFO_LOG_LENGTH,&maxLength);\n else\n glGetProgramiv(obj,GL_INFO_LOG_LENGTH,&maxLength);\n\n char infoLog[maxLength];\n\n if (glIsShader(obj))\n glGetShaderInfoLog(obj, maxLength, &infologLength, infoLog);\n else\n glGetProgramInfoLog(obj, maxLength, &infologLength, infoLog);\n\n if (infologLength > 0)\n printf(\"%s\\n\",infoLog);\n}\n\nstatic void error_callback(int error, const char* description)\n{\n fputs(description, stderr);\n}\n\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GL_TRUE);\n}\n\nvoid setShaders() {\n\n char *vs = NULL,*fs = NULL;\n\n v = glCreateShader(GL_VERTEX_SHADER);\n f = glCreateShader(GL_FRAGMENT_SHADER);\n\n vs = textFileRead(\"toon.vert\");\n fs = textFileRead(\"toon.frag\");\n\n const char * ff = fs;\n const char * vv = vs;\n\n glShaderSource(v, 1, &vv,NULL);\n glShaderSource(f, 1, &ff,NULL);\n\n free(vs);free(fs);\n\n glCompileShader(v);\n glCompileShader(f);\n\n p = glCreateProgram();\n glAttachShader(p,f);\n glAttachShader(p,v);\n\n glLinkProgram(p);\n //glUseProgram(p);\n}\n\nint main(void)\n{\n GLFWwindow* window;\n\n glfwSetErrorCallback(error_callback);\n\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\n window = glfwCreateWindow(640, 480, \"Simple example\", NULL, NULL);\n\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n\n glfwMakeContextCurrent(window);\n\n glfwSetKeyCallback(window, key_callback);\n\n while (!glfwWindowShouldClose(window))\n {\n int height, width;\n float ratio;\n glfwGetFramebufferSize(window, &width, &height);\n ratio = width / (float) height;\n glViewport(0, 0, width, height);\n setShaders();\n\n glBindAttribLocation(p,0,\"vPosition\");\n glUseProgram(p);\n /* Now What */\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n glfwDestroyWindow(window);\n\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n\nA:\n\nyou \"pass vertices into the shaders\" by making a draw call, most typically glDrawArrays().\nwhen glDrawArrays() hits, the currently bound vertex array gets sent off to GPU-land. the vertices will be processed by the currently bound program (which you seem to have figured out) and each vertex attribute will flow into the vertex shader variables based on whether or not the shader variable's attribute index matches the vertex attribute's glVertexAttribPointer() \"index\" parameter (which you seem on the way to figuring out).\nso, look into glVertexAttribPointer() to describe your array of vertices, glEnableAttributeArray() to enable your array of vertices to be sent on the next draw call, and then glDrawArrays() to kick off the party.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29483,"cells":{"text":{"kind":"string","value":"Q:\n\nProving that the derivative of an odd function is even.\n\nFor an assignment I had, I had to prove that the derivative of an odd function is even. In the assignment we also had to prove that $F(x)=\\int_0^x f(t)dt$ is odd given that $f$ is even, which I did do. Using that fact I stated the following:\nLet us define $F(x)=\\int_0^xf(t)dt$ such that $F(x)$ is odd.\n\\begin{equation}\nF'(x)=\\frac{d}{dx}\\int_0^xf(t)dt=f(x) \\nonumber\n\\end{equation}\nUsing 1.1 (the section where I proved that $F(x)=\\int_0^x f(t)dt$ is odd given that $f$ is even) we know that $f(x)$ is even.\nHowever, the teacher felt that the answer was not rigorous enough and that I was simply going backwards. Am I indeed simply moving backwards and not proving anything in which case: could someone point out places where I could make it more succinct and rigorous or alternatively supply better proof altogether.\n\nA:\n\nThe proof is quite simple from the definition of the derivative: if $f$ is odd then\n$$\r\nf'(-x) = \\lim\\limits_{h\\to 0}\\frac{f(-x+h)-f(-x)}{h} = -\\lim\\limits_{h\\to 0}\\frac{f(x-h)-f(x)}{h} = -f'(x).\r\n$$\nW.r.t. your proof. You have showed that if $f$ is even, then $F = \\int f$ is odd. You proved it - but you didn't prove that any odd function is an anti-derivative of the even function. That would be a reverse statement, as Alex has already told you. \nGenerally, you have $A\\Rightarrow B$ where $A = \\{f\\text{ is even}\\}$ and $B = \\{F\\text{ is odd}\\}$ but to prove that the derivative of the odd function is even you need $B\\Rightarrow A$ which you don't know at the moment.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29484,"cells":{"text":{"kind":"string","value":"Q:\n\nFlask WTForms validate_on_submit not working\n\nI am new in Web Development and I am using Flask to create a property price prediction website.\nI have a function validate_on_submit that is not working. It does not show any error, the form is submitted, it just does not validate. When the submit form is clicked, it needs to go to the next page. Here is the code:\n@app.route('/route1', methods=['POST', 'GET'])\ndef predict():\n form = Form_1()\n\n # These errors, submitted and validated just for some context, not in the actual code\n\n print(form.errors) # Returns {}\n\n if form.submit():\n print(\"submitted\") # Returns \"submitted\"\n\n if form.validate():\n print(\"validated\") # Page shows error 'NoneType' object is not iterable\n\n # more code\n\n if form.validate_on_submit():\n print(\"validated on submit\") # This is not working\n\n # more code\n\n return redirect(url_for('page_x'))\n return render_template('page_x.html', title='Page X', form=form)\n\nHere is the HTML:\n
    \n
    \n
    \n {{ form.hidden_tag() }}\n \n \n \n \n \n \n \n \n \n \n \n
    {{ form.select_field.label() }}:{{ form.select_field() }}
    {{ form.submit() }}
    \n
    \n
    \n
    \n\nIt is weird because I have another code similar to this that worked:\n@app.route('/route2', methods=['POST', 'GET'])\ndef add_data():\n form = Form_2()\n if form.validate_on_submit():\n\n # more code\n\n return redirect(url_for('page_y')\n return render_template('page_y.html', title='Page Y', form=form)\n\nHTML:\n
    \n

    Help Us Improve by Uploading a New Dataset

    \n
    \n
    \n {{ form.hidden_tag() }}\n {{ form.add_file() }} {{ form.submit() }}\n
    \n
    \n
    \n\nI am not sure what went wrong. Any help would be appreciated. Thank you.\n\nA:\n\nI found the problem. It is with the SelectField form that I use. I place a coerce arguments and it works.\nArticle that helped me: Not a Valid Choice for Dynamic Select Field WTFORMS\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29485,"cells":{"text":{"kind":"string","value":"Q:\n\njQuery - Event by scroll\n\nThe goal of my script is that when user scrolls down, my page should scroll to the next div. For this, the script distinguishes if the user scrolls up and down. After, when he scrolls, it should remove the class active of my first div and add to the next. Then it's scrolling to the new div with the class active. The problem is that it's working for the first scroll only, not the next.\nMy code:\n$(window).load(function() {\n var tempScrollTop, currentScrollTop = 0;\n var $current = $(\"#container > .active\");\n var next = $('.active').next();\n var prev = $('.active').prev();\n\n $(window).scroll(function() {\n currentScrollTop = $(window).scrollTop();\n\n if (tempScrollTop < currentScrollTop) { //scrolling down \n $current.removeClass('active').next().addClass('active'); \n $.scrollTo(next, 1000);\n }\n else if (tempScrollTop > currentScrollTop ) { //scrolling up\n $current.removeClass('active').prev().addClass('active');\n $.scrollTo(prev, 1000);\n }\n\n tempScrollTop = currentScrollTop;\n }); \n});\n\nCan anybody help me?\n\nA:\n\nI found the answer\nvar lastScrollTop = 0;\nvar isDoingStuff = false;\n$(document).scroll(function(event) {\n //abandon \n if(isDoingStuff) { return; }\n\n if ($(this).scrollTop() > lastScrollTop) {\n //console.log('down');\n $('.active').removeClass('active').next('div').addClass('active');\n isDoingStuff = true;\n $('html,body').animate( {scrollTop: $('.active').offset().top }, 1000, function() {\n setTimeout(function() {isDoingStuff = false;}, 100);\n console.log('off');\n });\n } else {\n //console.log('up');\n }\n lastScrollTop = $(this).scrollTop();\n})​\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29486,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to implement a Web UI feature to insert default sentences in an textarea\n\nWe are talking about implementing a system that easily generates sales reports for our sales employees. We want to create a web application with one or maybe more text area's to gather the input data from the employee.\nThere are a few sentences that will return time and time again. Something like: \"customer xyz decided to buy the products advised by consultant abc\"\nWhat options do I have to implement a feature like that. What I already thought of:\n\nClick RMB in text area to pop the sentences or categories of sentences which can be selected. Feels a bit outdated to me.\nShortcuts, like an IDE. When I type psvm[tab] I get \"public static void main...\". Probably to technical for most users.\nPresent a box with sentences next to the text area from which you can drag and drop the sentences. This will take up a lot of real estate.\nWhen the system recognizes the start of a sentence that is in the default sentences it pops the sentence and can be clicked (something like the tag functionality here on SE). This will give a lot of false true's which might be annoying for the user.\n\nI understand that there is not a single right answer to this question. Please post answers preferably with an example (of some other site)\n\nA:\n\nWhen the system recognizes the start of a sentence that is in the default sentences it pops the sentence and can be clicked (something like the tag functionality here on SE). This will give a lot of false true's which might be annoying for the user.\n\nI would go with this one. It's done in Microsoft Excel (which is fairly ubiquitous). The only time this might get annoying is if the user had to take extraordinary measures to change it. (If they kept typing something else, the default would disappear)\nIf you are unsure about it, test it with a few people who will be using the system. It's the only way to be sure.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29487,"cells":{"text":{"kind":"string","value":"Q:\n\nBest PHP Webserver for Development\n\nI'm starting to work with PHP more these days and I've been wondering what the best PHP webserver might be for a dev environment. Ideally, it would be easy to build, live only in the project deps directory and be easy to configure. Also, decent performance would be a plus. \nIn python land, werkzeug would be an equivalent of the type of server I'm thinking of. \n\nA:\n\nIn my opinion, the best webserver for the dev environment is as close as you can come to exactly the webserver in production. PHP is a lot less 'stand-alone' in some cases then Python, and it prevents nasty errors and surprises when pushing code to the production server. All kinds of havoc can ensue when a $_SERVER array is just that essential bit different, or something runs as (fast)cgi instead of as a module.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29488,"cells":{"text":{"kind":"string","value":"Q:\n\nReportlab: Is it possible to have internal links in Platypus?\n\nI know that I can internally link with canvas, but my whole doc's set up with Platypus. Does Platypus support internal linking? How hard is migrating to canvas if it doesn't?\nThanks in advance!\n\nA:\n\nYou can use intra-paragraph markup to create anchors ( tag) and links ( tag), as explained in the section 6.3 Intra-paragraph markup (chapter 6, page 72) of the ReportLab 2.6 User Manual PDF, which also contains the following example:\nThis is a link to an\nanchor tag ie here.\nThis is\nanother link to the same anchor tag.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29489,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat's the relationship between an SVM and hinge loss?\n\nMy colleague and I are trying to wrap our heads around the difference between logistic regression and an SVM. Clearly they are optimizing different objective functions. Is an SVM as simple as saying it's a discriminative classifier that simply optimizes the hinge loss? Or is it more complex than that? How do the support vectors come into play? What about the slack variables? Why can't you have deep SVM's the way you can't you have a deep neural network with sigmoid activation functions?\n\nA:\n\nI will answer one thing at at time\n\nIs an SVM as simple as saying it's a discriminative classifier that simply optimizes the hinge loss? \n\nSVM is simply a linear classifier, optimizing hinge loss with L2 regularization.\n\nOr is it more complex than that?\n\nNo, it is \"just\" that, however there are different ways of looking at this model leading to complex, interesting conclusions. In particular, this specific choice of loss function leads to extremely efficient kernelization, which is not true for log loss (logistic regression) nor mse (linear regression). Furthermore you can show very important theoretical properties, such as those related to Vapnik-Chervonenkis dimension reduction leading to smaller chance of overfitting.\nIntuitively look at these three common losses:\n\nhinge: max(0, 1-py)\nlog: y log p\nmse: (p-y)^2\n\nOnly the first one has the property that once something is classified correctly - it has 0 penalty. All the remaining ones still penalize your linear model even if it classifies samples correctly. Why? Because they are more related to regression than classification they want a perfect prediction, not just correct.\n\nHow do the support vectors come into play? \n\nSupport vectors are simply samples placed near the decision boundary (losely speaking). For linear case it does not change much, but as most of the power of SVM lies in its kernelization - there SVs are extremely important. Once you introduce kernel, due to hinge loss, SVM solution can be obtained efficiently, and support vectors are the only samples remembered from the training set, thus building a non-linear decision boundary with the subset of the training data.\n\nWhat about the slack variables? \n\nThis is just another definition of the hinge loss, more usefull when you want to kernelize the solution and show the convexivity. \n\nWhy can't you have deep SVM's the way you can't you have a deep neural network with sigmoid activation functions?\n\nYou can, however as SVM is not a probabilistic model, its training might be a bit tricky. Furthermore whole strength of SVM comes from efficiency and global solution, both would be lost once you create a deep network. However there are such models, in particular SVM (with squared hinge loss) is nowadays often choice for the topmost layer of deep networks - thus the whole optimization is actually a deep SVM. Adding more layers in between has nothing to do with SVM or other cost - they are defined completely by their activations, and you can for example use RBF activation function, simply it has been shown numerous times that it leads to weak models (to local features are detected).\nTo sum up:\n\nthere are deep SVMs, simply this is a typical deep neural network with SVM layer on top.\nthere is no such thing as putting SVM layer \"in the middle\", as the training criterion is actually only applied to the output of the network.\nusing of \"typical\" SVM kernels as activation functions is not popular in deep networks due to their locality (as opposed to very global relu or sigmoid)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29490,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to compare two objects in a dictionary\n\nI just wonder that how to compare two objects in a dictionary:\na = {}\nwhile z:\n if a[z] == a[s]:\n print(\"Correct!\")\n else:\n print(\"You don't know that country.\")\n z = input(\"Enter a country: \")\n s = input(\"What is the capital of \" + z + \" ? \")\n\nI want to print Correct when z = s; when z not in a, print You don't know that country.\n\nA:\n\nAssuming that a is a dictionary with the country as the key, and the capital as the value, you should make two separate checks: First you want to make sure that the entered country exists as a key in the dictionary. For that you should use the in operator. Second, you want to check whether the entered capital matches the capital in the dictionary. For that you perform an index access using the country on the dictionary and check whether the value equals the entered capital:\ncapitals = {\n 'Austria': 'Vienna',\n 'Belgium': 'Brussels',\n 'Denmark': 'Copenhagen',\n 'France': 'Paris',\n 'Germany': 'Berlin',\n 'Netherlands': 'Amsterdam',\n 'Norway': 'Oslo',\n 'Sweden': 'Stockholm',\n 'Switzerland': 'Bern',\n 'United Kingdom': 'London'\n}\n\nwhile True:\n country = input(\"Enter a country: \")\n\n # abort the loop if the user didn’t enter anything\n if not country:\n break\n\n # check whether we know that country\n if country in capitals:\n capital = input(\"What is the capital of {}? \".format(country))\n\n if capital == capitals[country]:\n print('That was correct!')\n else:\n print('You made a mistake there.')\n\n else:\n print('I do not know that country, sorry.')\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29491,"cells":{"text":{"kind":"string","value":"Q:\n\nBrute-force algorithm to find the set of all empty triangles\n\nGiven a set P of points in the plane, specify a naive brute-force algorithm to find the set of all empty triangles with vertexes in P. (A triangle with vertexes a, b, c belong to P is empty if it contains no other point d which belongs to P.)\nHow shall I start solving this type of problem? Are there any existing algorithm which I should look up or you think I would have to sketch it out with a few points?\n\nA:\n\nGiven a set P of points in the plane, specify a naive brute-force\nalgorithm to find the set of all empty triangles with vertexes in P.\n(A triangle with vertexes a, b, c belong to P is empty if it contains\nno other point d which belongs to P.)\nHow shall I start solving this type of problem?\n\nWell bottom up:\n\nFor a single triangle and a single point, write a function contains, which tests, whether the point is in the triangle.\nFor a single triangle and a group of points, look whether whether there is no point contained in the triangle. Call this isEmpty.\nFor a group of triangles, test each.\n\nKeywords are: iteration, predicate, filter.\n\nYou should write tests on each stage, points in the triangle, outside, bordercases. Test as early as possible.\nWrite testmethods, to make testing easy.\nThen Triangle.isEmpty or how this would look in your language.\n\nTop down would work too. Then you might need mock-functions for testing. But I don't see advantages vs. bottom up.\nPseudocode:\nTriangle.contains (p: Point) : Boolean ()\n\nTriangle.isEmpty (ps: Pointset) : Boolean = \n ps.forAll (p => ! t.contains (p))\n\ntriangleset.filter (t => t.isEmpty (pointset))\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29492,"cells":{"text":{"kind":"string","value":"Q:\n\nApply bootstraps tr hover effect to a div\n\nI am using Bootstrap for my css themes. The themes are compiled and saved into the database for use later on. This means that the pages only have access to the compiled css and not the less files.\nGiven that, how can I apply Bootstrap’s tr:hover effect to various divs? I need the color to be the same as what is defined for tr:hover and I can’t use less variables.\nBootstrap's style:\n.table tbody tr:hover td,\n.table tbody tr:hover th {\n background-color: #f5f5f5;\n}\n\nIs it possible to define a css element based on another one that is assigned to a tr? Is there a way to grab the style using jQuery?\nAny suggestions?\n\nA:\n\nPure CSS Way:\nHave a class for the div as .hoverDiv and the CSS for this:\n.hoverDiv {background: #fff;}\n.hoverDiv:hover {background: #f5f5f5;}\n\nFiddle: http://jsfiddle.net/bD5kS/\njQuery Way:\n$(document).ready(function(){\n $(\".hoverDiv\").hover(function(){\n $(this).css(\"background\", \"#f5f5f5\");\n }, function(){\n $(this).css(\"background\", \"#fff\");\n });\n});\n\nFiddle: http://jsfiddle.net/KQzwc/\nTo get the colour dynamically, use $(\".table tbody tr:hover\").css(\"background-color\"):\n$(document).ready(function(){\n $(\".hoverDiv\").hover(function(){\n $(this).css(\"background\", $(\".table tbody tr:hover\").css(\"background-color\"));\n }, function(){\n $(this).css(\"background\", $(\".table tbody tr\").css(\"background-color\"));\n });\n});\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29493,"cells":{"text":{"kind":"string","value":"Q:\n\nMy PC doesn't want to make a final rebooting to end up the installation of Ubuntu 16.04\n\nsmarty people,\nI'm a total noob on OS subject, so I'll be very thankful if you excuse me for the elementary lvl of my question.\nI've tried to install the last update desktop version of Ubuntu 17.10, but it refuses to make the last installation (after the settings and all of the questions) to finish the process. I didn't find any similar questions on the Internet, so I've decided that maybe the problem is very unpopular or perhaps I've done something wrong (which is kindda funny, considering how easy should it be). \nAnyway, I've downloaded the older version since 16.04.2017, but that didn't fixed the situation. I click on the button \"restart\" and the desktop freezes with no possibility to click again. The only option available is to shut-down the PC and the whole operation repeat itself all over again. \nI've used USB Flash Drive for the booting and I want to make Ubuntu pioneer OS on my PC.\nSo, where exactly the root of the problem should be? (is in the ground, someone could say, but I've dig the whole place yet)\n\nA:\n\nSysRq R E I S U B - graceful reboot\nSometimes, at the very end of the installation, the system justs hangs, does not reboot, does not shut down. This can be caused by a 'race condition', that things cannot be done in the correct sequence.\nWhen this happens it might help with the SysRq R E I S U B method. This causes the computer to reboot gracefully (if it can listen to the request).\nSee more details in the following link and links from it,\nRestart Ubuntu via keyboard\n\nSysRq is often on the PrintScreen key:\nPress Alt + PrintScreen continuously, sometimes\n the Fn key is involved too (in laptops),\nand then slowly (one key after another) the keys R\nE I S U B to\n reboot.\nWhen you press the 'letter keys' you need not specify caps lock or\n shift.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29494,"cells":{"text":{"kind":"string","value":"Q:\n\nHas the Url Shortener in Google Apps Script changed?\n\nI've been using this simple function to create shortened links in Google Apps Script. It's been working for the past few months but stopped working few days ago. Has there been a change?\n function getShortenedUrl(url){ \n\n var longUrl = UrlShortener.newUrl()\n .setLongUrl(url);\n\n var shortUrl = UrlShortener.Url.insert(longUrl);\n\n return shortUrl.getId();\n}\n\nA:\n\nYes. It has. I figured it out the hard way. Just make a small change for it to work \nfunction getShortenedUrl(url){ \n\n var longUrl = UrlShortener.newUrl();\n longUrl.setLongUrl(url);\n\n var shortUrl = UrlShortener.Url.insert(longUrl);\n\n return shortUrl.getId();\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29495,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to get manufacturer name for each product\n\nI have to get some attributes for each product I've gotten most of them but I don't know how to get manufacturer name and the upc or ean barcode value in adminhtml.\nI've tried with this code\n $name = 'Manufacturer';\n $attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem();\n $attributeId = $attributeInfo->getAttributeId(81);\n $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);\n $attributeOptions = $attribute ->getSource()->getAllOptions(false);\n var_dump($attribute);\n\nBut I can Just print (like in the image) $attribute level and then the $attributeOptions goes empty.\n\nA:\n\n$productId='your_product_id';\n$product=Mage::getModel('catalog/product')->load($productId);\n\n$manufaturer=$product->getAttributeText('manufacturer');\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29496,"cells":{"text":{"kind":"string","value":"Q:\n\nPass file from file() to Perl program PHP\n\nI have a PHP code that stores contents of a url by file() method like \n$contents=file(\"http://www.rcsb.org/pdb/files/2AID.pdb\"); \n\nI need to pass these $contents to a perl program by shell_exec() method , something like following \n$result=shell_exec(\"perl_prog.pl $contents\");\n\nMy question is how to pass this $contents to Perl program. I tried like following \n@file=<@ARGV>;\n\nbut its not working. Please help me.\n\nA:\n\nThat shell_exec() code is utterly vulnerable to shell injection - you're trusting that the remote service won't include something like:\n; rm -rf /\n\nAs well, file() returns the file contents as an array - you can't pass arrays over the command line directly. Only strings.\nA moderately safer version is:\n$contents = file_get_contents('http://etc....');\n$safe_contents = escapeshellarg($contents);\n$result = shell_exec('perl_prog.pl $safe_contents');\n\nOn the Perl side, you'd use\nmy ($contents) = @ARGV;\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29497,"cells":{"text":{"kind":"string","value":"Q:\n\nRails - Alphanumeric field validation\n\nIn rails 4, I need to validate the alphanumeric field which can accept only dot(.), hyphen(-), slash(/) and space in between the characters. \nEg: AB123-GH345 or AB45.NH744 or KHJ3/SD34 or HJS23 JKA34\nI have tried with /^[0-9]+#$/ and /^\\d+([.,]\\d+)?$/ and /^[0-9]+#$/ but it is not working as per the requirement.\nValue should be accept as per the examples. Please help me to validate this field.\n\nA:\n\nI think this might help you:\n/^[A-Za-z0-9-\\/\\.\\s]+$/\n\nThis worked for all the examples you have provided\nAB123-GH345 or AB45.NH744 or KHJ3/SD34 or HJS23 JKA34\nand rejected when I inserted a character like ? in the middle(HJS23?JKA34).\n\nUpdate\nIf you don't want multiline anchors then you can use it like this:\n/\\A[A-Za-z0-9-\\/\\.\\s]+\\z/\n\nYou can use this Rubular site to validate your Regex codes.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29498,"cells":{"text":{"kind":"string","value":"Q:\n\nSorting Color in C# on the basis of brightness or YIQ scale\n\nI am looking for sorting some colors in our project on the basis of the brightness, so probably I need YIQ representation of the color on basis of which I can sort.\nSo I am pricesely looking for the YIQ representaion of some given RGB format color in C#\nI found this formula on wiki and some other sites for conversion from RGB to YIQ scale:\nHere is the RGB -> YIQ conversion:\n[ Y ] [ 0.299 0.587 0.114 ] [ R ]\n[ I ] = [ 0.596 -0.275 -0.321 ] [ G ]\n[ Q ] [ 0.212 -0.523 0.311 ] [ B ]\n\nBut now how to get the Color value in C# from this Y, I and Q values which we would get from this formula.\nSo if I have this color: #FF832727 which is in RGB format, how to get its corresponding color in YIQ scale.\n\nA:\n\nPossible implementation, if I´ve understood your right\nList colors = new List {\n Color.Wheat,\n Color.Black,\n Color.Red,\n Color.FromArgb(unchecked ((int)0xFF832727U))\n};\n\n// You don't need convert colors into YIQ (i.e. matrix multiplication)\n// just compare brightness (Y component)\ncolors.Sort((Comparison) (\n (Color left, Color right) => \n (left.R * 299 + left.G * 587 + left.B * 114).CompareTo(\n right.R * 299 + right.G * 587 + right.B * 114)\n ));\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29499,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to determine where biggest files/directories on my system are stored?\n\nI was wondering how do you know where the largest files in my system are stored.\nFor example---\nDisk Space Used: 1GB\nJava: 500MB\nJava Percentage: 50% maybe represented in a pie chart. Maybe?\nI know this maybe a feature overkill. I sometimes forget having stored things and wonder why my disk is so full. \nSo basically a command that will allow me to run on the file system and provide me with information on disk space used.\nPlease and thank you.\n\nA:\n\nThe Disk Usage Analyzer is available under Ubuntu > Accessories > Disk Usage Analyzer. It provides you with a snazzy pie graph showing what files and folders take up the most space:\n\nThe documentation on it is a little sparse, but you can find more information on the Ubuntu wiki, and the project page.\nIf you're interested in using the command line, there's du which is described here.\n\nA:\n\nUnless it changed recently, baobab only shows directories; check out kdirstat for an alternative that actually shows files, coloured by type.\nA commandline alternative is\ndu -a | sort -nr | head\n\nA:\n\nThe solution that @UncleZeiv proposed is not working when there is really no more space left, since sort is using the /tmp folder when there are multiple lines to sort.\ndu -a | sort -nr | head\nsort: write failed: /tmp/sortuCYq8E: No space left on device\n\nAn alternative is a combination of the answer from @UncleZeiv and @Yoav Weiss, plus adding another path for the temporary location:\nsudo du -a | sort -nr -T /media/usb-key\n\nFinally, my preferred solution will be a human-readable one that doesn't depend on temp folder and list root directory (/):\nsudo du -ah --max-depth=1 / | sort -hr\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":294,"numItemsPerPage":100,"numTotalItems":29950,"offset":29400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzg1MzkwMiwic3ViIjoiL2RhdGFzZXRzL3N1b2x5ZXIvcGlsZV9zdGFja2V4Y2hhbmdlIiwiZXhwIjoxNzU3ODU3NTAyLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.S9dcgBOvGzN9qDpi3nbn1xJ-ZL85FtLF8oGSuw9ow1odhPUDySg1QmqOvTjNScZdbdnUnEV-lfcMHo5ZKk5JBw","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: Minimum number of Jumps Given a sequence of numbers, find the minimum number of jumps to go from the starting position to the end and come back to the starting position again. Each element of the sequence denotes the maximum number of moves that one can move from that position. At any position, you can make a jump of at max k moves, where k is the value stored at that position. After reaching the end, you can use only those positions for jumping which have not been used previously for jumping. The input will be given as a sequence of numbers separated by single-spaces. Output should be a single number which is the minimum number of jumps used. If its not possible to go to the end and come back to the starting position, then print -1 Input: 2 4 2 2 3 4 2 2 Output: 6 (3 to reach end and 3 to come back) Input 1 0 Output -1 Note Assume all the numbers of the sequence are non-negative EDIT 1 The line "Thus, it should be clear that one can always jump from the last position." might be confusing, so I removed it from the question. It will have no effect on the question. Winning Criteria : The winner will be the one with the shortest code. A: Mathematica, 197 193 chars Brute force. Min[Length/@Select[Join[{1},#,{n},Reverse@#2]&@@@Tuples[Subsets@Range[3,n=Length[i=FromDigits/@StringSplit@InputString[]]]-1,2],{}⋃#==Sort@#∧And@@Thread[i[[#]]≥Abs[#-Rest@#~Append~1]]&]]/.∞->-1 A: APL(Dyalog), 116 f←{{⊃,/{2>|≡⍵:⊂⍵⋄⍵}¨⍵}⍣≡1{(⍴⍵)≤y←⊃⍺:⍵⋄⍵[y]=0:0⋄x←⍵⋄x[y]←0⋄∇∘x¨,∘⍺¨y+⍳y⌷⍵},⍵} {0≡+/⍵:¯1⋄(⌊/+/0=⍵)-+/0=x}↑⊃,/f¨⌽¨f x←⎕ Test cases 2 4 2 2 3 4 2 2 6 1 0 ¯1 1 1 1 1 ¯1 3 1 2 0 4 3 1 0 Approach The approach is a brute force search using a recursive function. Starting from position 1, set value at the current position to 0 and generate an array of the positions which can be jumped to from the current position. Pass the new position and the modified array to itself. Base cases are when the value at the current position is 0 (can't jump) or reaching the end. Then, for each of the array generated, reverse it and do the search again. Because jumped positions are set to 0, we can't jump from there again. For those array which we reached the end, find the ones which have the minimum number of 0's. Subtracting from it the number of 0's in the initial array gives the actual number of jumps performed. A: Mathematica 351 [Note: This is not yet fully golfed; Also, the input needs to be adjusted to fit the required format. And the no-jumping-on-the-same-position-twice rule needs to be implemented. There are also some code formatting issues that need addressing. But it's a start.] A graph is constructed with nodes corresponding to each position, i.e. each input digit representing a jump. DirectedEdge[node1, node2] signifies that it is possible to jump from node1 to node 2. Shortest paths are found from start to end and then from end to start. f@j_:= (d={v=FromCharacterCode/@(Range[Length[j]]+96),j}\[Transpose]; w[n_,o_:"+"]:={d[[n,1]],FromCharacterCode/@(ToCharacterCode[d[[n,1]]][[1]]+Range[d[[n,2]]] If[o=="+",1,-1])}; y=Graph[Flatten[Thread[DirectedEdge[#1,#2]]&@@@(Join[w[#]&/@Range[8],w[#,3]&/@Range[8]])]]; (Length[Join[FindShortestPath[y,v[[1]],v[[-1]]],FindShortestPath[y,v[[-1]],v[[1]]]]]-2) /.{0-> -1}) Usage f[{2,4,2,2,3,4,2,2}] f[{3,4,0,0,6}] f[{1,0}] 6 3 -1
    { "pile_set_name": "StackExchange" }
    Q: How do I export an existing play framework into Heroku? I have been reading and following: http://eclipse-plugin.herokuapp.com/ to export my existing play applications to Heroku. When running heroku create, git push heroku master in my terminal everything works like a charm and my project is created and I can browse it at: xxx.herokuapp.com. But when I enter Eclipse the project is not "hooked" to Heroku. E.g I'm not able to Push to Upstream If I go the other way and import the Heroku project with Eclipse, the project is downloaded and "hookup" to Heruko but then the project is located in my git repo and not workspace. So my question is: How do I connect my project that are located in my workspace to Heroku so that it's treated like a Eclipse Heroku app? EDIT: There is no share option: A: To setup the project so you can do the Git operations from Eclipse, you need to do the following: Right-click on the project in the Project Explorer and select Team Select Share Project... Select Git and then Next Leave the defaults as they are and select Finish To upload the app to Heroku, do the following (after your changes are committed to the Git repo): Right-click on the project in the Project Explorer and select Team Go to the Remote sub-menu and select Push... Leave the defaults as they are (the Heroku Remote Git repo should be selected) and select Finish
    { "pile_set_name": "StackExchange" }
    Q: Angular 6 Observable and subscribe I have some data in angular services coming from REST API info.services.ts getCustomerDetails() { this.http.get(this.localUrl + this.customerUrl + this.options).pipe(map((response: Response) => response.json())) } my homepage.ts getData(){ this.infoServices.getCustomerDetails().subscribe(data=>{ if(data) { this.name = data[0].customerInfo.name; } }) } and my home.html <input type="text" value="{{this.name}}" formControlName="name" /> my question is there any better way to fetch data instead of doing data[0]? endpoint: router.post("/request/customer", (req, res) => { var pendingRequest = new Customer({ name: req.body.name, age: req.body.age, isNewCustomer: true, requestInfo: { customerType: req.body.customerType, sendTo: { email: req.body.sendTo_email, company: req.body.sendTo_company }, returnTo: { email: req.body.returnTo_email, company: req.body.returnTo_company } }, }); pendingRequest .save() .then(result => { console.log(result); res.status(200).json({ message: "Handling POST request to /pending", createdRequest: result }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); A: I have found the solution, so in ts file: customerData:any = [] getData(){ this.customerData = []; this.infoServices.getCustomerDetails().subscribe(data=>{ if(data) { this.customerData = data; } }) } and in your html template simply <div *ngFor="let data of customerData; let i = index"> {{data.name}} </div>
    { "pile_set_name": "StackExchange" }
    Q: How to display plain text only from redactor without any line break or format Is there a way to display plain text only without any line break or format style. I have an input field using the redactor. I want the result to shows plain text without any formatting for this particular page. How can I modify it? {% set desc = desc|slice(0,150) %} {% set _desc = desc|split(' ') %} {% set __desc = _desc|slice(0,-1) %} {% set desc = __desc|join(' ') %} {{desc|raw}} Thanks. A: If you're trying to remove HTML tags from the output completely, you can use Twig's striptags filter: https://twig.symfony.com/doc/2.x/filters/striptags.html. If you want to retain the tags but show the output without any styling, you're going to have to handle that with your CSS by negating any of the existing styling you don't want.
    { "pile_set_name": "StackExchange" }
    Q: Why does my batch file not copy hidden system files to USB drive? I have been struggling over this question for a while now. I have a batch file that, when started, searches for any USB drive and if it finds one, it searches for some files and copies them to the USB. However it is not working for me in this case. Please note that the files I am copying have +H and +S attributes, I do hope that wont make a difference. Here is the code of the batch file: @echo off :loop set INTERVAL=5 for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do ( for %%c in (%%b) do ( for /F "tokens=3" %%d in ('fsutil fsinfo drivetype %%c') do ( if %%d equ Removable ( echo %%c is Removable cd %SYSTEMROOT%\system32\SystemSettingsUpdate copy "Whatsapp,Inc.exe" "%%c" copy "Configure.exe" "%%c" copy "HL~Realtime~Defense.exe" "%%c" ATTRIB +H -R +S %%cConfigure.exe ATTRIB +H -R +S %%cHL~Realtime~Defense.exe timeout /nobreak /t 59 goto :loop ) ) ) ) Please note that the %%c is the letter of the USB drive. So now what happens is that when I start it, it gives me an error that it cannot locate the files I specified. However I double checked the location and the files exist. Any suggestions why getting the file not found error message? A: COPY does not copy files with either system or hidden attribute set as the following batch code demonstrates: @echo off cls pushd "%TEMP%" md TestTarget 2>nul echo Just a copy/xcopy test for hidden and system files.>TestFile.tmp attrib +h TestFile.tmp echo TRY TO COPY HIDDEN FILE ... echo. echo copy TestFile.tmp TestTarget\ copy TestFile.tmp TestTarget\ echo. echo. echo TRY TO XCOPY HIDDEN FILE ... echo. echo xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y echo. pause cls attrib -h +s TestFile.tmp echo TRY TO COPY SYSTEM FILE ... echo. echo copy TestFile.tmp TestTarget\ copy TestFile.tmp TestTarget\ echo. echo. echo TRY TO XCOPY SYSTEM FILE ... echo. echo xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y echo. pause cls attrib +h +s TestFile.tmp echo TRY TO COPY HIDDEN SYSTEM FILE ... echo. echo copy TestFile.tmp TestTarget\ copy TestFile.tmp TestTarget\ echo. echo. echo TRY TO XCOPY HIDDEN SYSTEM FILE ... echo. echo xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y xcopy TestFile.tmp TestTarget\ /H /I /Q /R /Y echo. del /A TestFile.tmp rd /Q /S TestTarget popd pause One solution for copying hidden system files is using command XCOPY with parameter /H. But usage of XCOPY for copying a single file is a little bit tricky. Copying with XCOPY a single file to an existing directory with a new file name results in a prompt if the target is a file or a directory. For this task the prompt can be avoided by using option /I and making sure the target specification ends with a backslash and is therefore interpreted as directory path. See also answers on BATCH file asks for file or folder for details on XCOPY and file or directory prompt. Additionally argument /Y is needed to avoid the prompt on overwriting an already existing file in target directory with same name as current source file. Then XCOPY outputs an access denied error message if the file already exists in target directory but has hidden attribute set. The copying is successful for this case with using also flag /R (second copy done by demonstration batch file). Parameter /Q should be also used for copying the files without showing their names. And last it would be good to use >nul at end of each line with XCOPY if the success message should be suppressed which was not done on demonstration batch code as we want to see absolutely the success message here. XCOPY without using /K removes automatically the read-only attribute.
    { "pile_set_name": "StackExchange" }
    Q: Assembly Pointer and base address As i am a assembly language beginner and studying purpose, I am trying scan memory address and pointer in a game. I am kind of confusing about pointer and address. I found the pointer by a tutorial on youtube, but i want some depth understanding of this pointers and offset. I don't understand how those offset and address add up together and give a final address that stored a value of 1000. What I understand is that 00F8EBE0 is base address, " 22,20,10,C,20" are five offset. 00F8EBE0 -> 11DA0924 = 1000 How this happen? How could I read 00F8EBE0 value with C++? Do I need those offset to help me to get the final value? A: In the process's virtual memory space, the image file ("something.exe") is loaded. If you add 0x00F8EBE0 to that address and read that location, you'll get 0x127B5450. Read the arrows as "points to" and the values in square brackets as "address plus offset". You can programatically get the image base using the ToolHelp32 API. What you have here is a chain of pointers to object structs, with each offset giving you where the next pointer is in the struct/object. To use this information from another program you can use ReadProcessMemory. Starting from the first offset (the image base), call ReadProcessMemory and then add the relevant offset to it, then repeat. The general process is as follows: //assuming you've calculated the image base of the target //and acquired a handle to the process: LPVOID base = ImageBase + 0x00F8EBE0; //note: EntryPoint needs obtaining properly LPVOID value; ReadProcessMemory(hnd,base,(LPVOID) &value,sizeof value, NULL); base = value + 0x20; ReadProcessMemory(hnd,base,(LPVOID) &value,sizeof value, NULL); base = value + 0xc; ReadProcessMemory(hnd,base,(LPVOID) &value,sizeof value, NULL); base = value + 0x10; ReadProcessMemory(hnd,base,(LPVOID) &value,sizeof value, NULL); base = value + 0x20; ReadProcessMemory(hnd,base,(LPVOID) &value,sizeof value, NULL); base = value + 0x44; ReadProcessMemory(hnd,base,buf,sizeof value, NULL); //value will now contain the number 1000. Note that there aren't any guarantees the process' address space will look the same each time it runs; if it allocates any memory the first offset to the entry point (0x00F8EBE0) won't be the same.
    { "pile_set_name": "StackExchange" }
    Q: Retrieving React state value via dynamic variables I am building a simple rgba selector which allows users to toggle the individual values via the arrow-up and arrow-down keys. Below is a snippet of my code. class App extends Component { constructor(){ super(); this.state = { red: 0, green: 200, blue: 0, opacity: 1, }; this.handleValueChange = this.handleValueChange.bind(this); this.handleArrowKeysInput = this.handleArrowKeysInput.bind(this); // for using up and down arrows to adjust the values handleArrowKeysInput = e => { const keyPressed = e.keyCode; let {id} = e.target; console.log(id); //returns red OR green OR blue console.log(this.state.id); // if up button is pressed if(keyPressed === 38){ // if value is already 255, stop increment if(this.state.green >= 255) return; console.log(`up button is pressed`); this.setState({[id]: this.state.id + 1}); } // if down button is pressed else if(keyPressed === 40){ // if value is already 0, stop decrement if(this.state.id <= 0) return; console.log(`down button is pressed`); this.setState({[id]: this.state.id - 1}); } } <input value={this.state.red} type="text" id="red" onChange= {this.handleValueChange} onKeyDown={this.handleArrowKeysInput}/> console.log(id) returns the desired value red or green or blue. However when i tried to console.log(this.state.id). It shows undefined. Why is this so? A: Your code is a bit confusing probably because its not a Complete Example but I try to give you some options to fix it. There is no id value on you initial state construction. Example this.state = { red: 0, green: 200, blue: 0, opacity: 1, id: 0 // This should be here if you are going to use it }; Secondly you are trying to add up 1 to a undefined value below; this.setState({[id]: this.state.id + 1}); Because this.state.id is undefined, this.state[id] will be undefined too. But from what I understand from your code you are trying to set red, green and blue values, so your code should be like below; this.setState({[id]: this.state[id] + 1}); Because you are trying to get a state value on the above code it is a better practice to use functional setState; this.setState((prevState) => ({[id]: prevState[id] + 1}));
    { "pile_set_name": "StackExchange" }
    Q: How to validate user and password on macOS programmatically? I have an application that asks for the username and password of the user. Currently, for Unix systems (most of them) I read the password hash from /etc/shadow but for macOS is way more cumbersome (they use their own standard) so I wanted to know if there is an easy way to validate usernames and passwords. I was thinking of using the login program in a weird way for this but it's not the best solution. I'm using golang but a solution in C or C++ would be useful too. Edit The answer from @TheNextman is exactly what I asked for but talking with other people they suggest me to use PAM because it works with multiple OS. It took me some effort to understand it because I was looking for a simple API to verify users and passwords, something like verify(username string, password string) -> boolean but I get that PAM is more general and hence more complex. But this is the code I ended up using, it's made in GO with C bindings. package Authentication import "C" import ( "encoding/json" "fmt" "github.com/vvanpo/golang-pam" ) func ValidateUser(username, password string) (bool, error) { // TODO correct handle of errors UserPssword := userPassword{ Username : username, Password : password, } b, _ := json.Marshal(UserPssword) conn := myConHand{ username:C.CString(string(b)), } tx, _ := pam.Start("sshd", username, conn) r := tx.Authenticate(0) if r == pam.SUCCESS{ return true, nil } else { return false, nil } } type userPassword struct { Username string Password string } type myConHand struct { username *C.char } //C.GoString func (m myConHand) RespondPAM(msg_style int, msg string) (string, bool) { str := C.GoString(m.username) var UserPssword userPassword _ = json.Unmarshal([]byte(str), &UserPssword) switch msg_style { case pam.PROMPT_ECHO_OFF: fmt.Println("Password!!") return UserPssword.Password, true case pam.PROMPT_ECHO_ON: fmt.Println("Username!!") return UserPssword.Username, true case pam.ERROR_MSG: fmt.Println(msg) return "", true case pam.TEXT_INFO: fmt.Println(msg) return "", true default: return "", true } } It has some problems, for example I'm using the /etc/pam.d/sshd service because I know that the computers I'll be using have the same service, but I don't know which OS has /etc/pam.d/sshd, the other option will be to create my own service but I'll have to create one for every different standard which I found 3 Linux PAM, openPAM (macos) and Solaris PAM. But overall I think this is a robust solution because I'm reusing the existing authentication mechanism. A: a solution in C or C++ would be useful too Here is an example in C using CoreServices. Error and result checking are omitted for brevity: void on_logon(const char* username, const char* password) { CSIdentityQueryRef query; CFArrayRef idArray = NULL; CSIdentityRef result; CFStringRef cfUsername = NULL; CFStringRef cfPassword = NULL; cfUsername = CFStringCreateWithCString(NULL, username, kCFStringEncodingUTF8); query = CSIdentityQueryCreateForName(kCFAllocatorDefault, cfUsername, kCSIdentityQueryStringEquals, kCSIdentityClassUser, CSGetDefaultIdentityAuthority()); CSIdentityQueryExecute(query, kCSIdentityQueryGenerateUpdateEvents, NULL); idArray = CSIdentityQueryCopyResults(query); if (CFArrayGetCount(idArray) != 1) { // Username didn't match... } result = (CSIdentityRef) CFArrayGetValueAtIndex(idArray, 0); cfPassword = CFStringCreateWithCString(NULL, password, kCFStringEncodingUTF8); if (CSIdentityAuthenticateUsingPassword(result, cfPassword)) { // Username and password are valid!! } CFRelease(cfUsername); CFRelease(idArray); CFRelease(cfPassword); CFRelease(query); }
    { "pile_set_name": "StackExchange" }
    Q: How to use shell exec grep to search multiple words in a file in php Here is my code $words=$_GET['word']; $words=explode(' ',$words); $words=implode('|',$words); $search=shell_exec( 'grep -E '.$words.' /home/jitu/data.txt'); $search=explode('\n',$search); foreach($search as $line){echo '<p>'.$line.'</p>';} This code works best for single search word but is not working in multiple words A: When using the $words variable in shell_exec you need to enclose it within quotes. The '|' (pipe symbol) passes the result of the command on the left to the command on the right. Your shell is executing this: $: grep -E one|two|three data.txt bash: two: command not found bash: three: command not found When it should be executing this: $: grep -E 'one|two|three' data.txt one two Code: <?php $words="one two three"; $words=explode(' ',$words); $words=implode('|',$words); $search=shell_exec( "grep -E '{$words}' data.txt"); $search=explode('\n',$search); foreach($search as $line){echo '<p>'.$line.'</p>';}; On a side note, as your passing user supplied input to shell_exec without sanitizing it first you are leaving yourself vulnerable to code execution.
    { "pile_set_name": "StackExchange" }
    Q: Получение значения инпутов в массив Доброго времени суток. Представим, что есть 3 текстовых инпута, в которые вводят какие-то значения (не обязательно во все, а допустим только в 2 из 3х), как эти значения закинуть в массив для дальнейшего использования? A: Можем просто использовать .val(). Потом для каждый элемент записываем в массив, если он не пустой. // Нужный нам массив var a = []; // Для удобства $('#add').on('click', function() { // Для каждого поля запоминаем значение введённое пользователем $('.input').each(function() { var input = $(this).val(); // Получаем значение из текстового поля if (input != '') { // Если не пустая строка a.push(input); // Добавляем значение в конец массива } }); console.log('Added'); }); // При нажатии на вторую кнопку... $('#show').on('click', function() { // Вывод массива. Для каждого элемента выводить... a.forEach(function(item, index, array) { console.log('a[' + index + '] = ' + item); }); }); input { display: block; margin-bottom: 5px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input"> <input type="text" class="input"> <input type="text" class="input"> <button id="add">Добавить в массив</button> <button id="show">Показать массив</button>
    { "pile_set_name": "StackExchange" }
    Q: Prevent HTML5 autofocus from displaying soft-keyboard on smaller (mobile) screens Using the HTML5 attribute "autofocus" can be a really useful thing for web pages. However, using - for example - Firefox (37.0.1) on Android devices results in the soft keyboard being displayed on page load. <input type="text" name="q" autofocus> The soft-keyboard takes up a lot of space and therefore I'd like to prevent this from opening. At the same time, autofocus is a very useful feature that we need for normal screens/devices. I tried removing the "autofocus" attribute based on screen width via jQuery on page load, however, that's too late. At this point, the browser apparently already accepted the attribute and shows the soft keyboard: $(function(){ if (window.innerWidth < 600) $('*[autofocus]').removeAttr('autofocus'); }); Any suggestions? A: Try this, it works on desktop, I haven't test it on mobile. Delete the attribute autofocus <input type="text" name="q"> and the JS function setFocus() { if (window.innerWidth > 600) $("input[name=q]").focus(); } $(document).ready(function() { setFocus(); });
    { "pile_set_name": "StackExchange" }
    Q: Fit the text in text object when passing the values from parameter I have text object in which I am passing parameter value (names) in this form: Name1, Name2, Name3.... Name n The problem I am facing is the fitting inside that object, so I have a situation like this: ---------------------------------------------------------------------------------------------- Name1, Name2, Name3.......................................................Name m, Name m+1, Name m+2............................................................... ................................................................................. ................................................................................. ...........................................................................Name n ----------------------------------------------------------------------------------------------- So, there is that white space in the right (right from Name m and Name n) side and I am not sure how to handle that. So the problem is fitting in one row. A: Assuming that the parameter field is a string, do the following: create a formula field {@names} enter the following text: Join({?parameter_field}, ", ") add this field to the details section; mark it can grow
    { "pile_set_name": "StackExchange" }
    Q: jQuery - if two classes - get the first one Example: Here we have <p class="tab1 current"></p> How can I get only the first class? var GetFirstClass = $('p').attr('class').filter(':first'); ?? Any help much appreciated. A: Use JavaScript's split function: $('p').attr('class').split(' ')[0] Demo A: $('p').attr('class').split(' ')[0]
    { "pile_set_name": "StackExchange" }
    Q: Check if user is logged in first time How can i check if user is logged in for the first time on site? If it is, i want to show him a message... Can someone help me? Thank you! A: ** UPDATE ** As suggested by oknate, using hook_user_login: function hook_user_login(&$edit, $account) { if(!$account->access) { drupal_set_message(t('This is your first login. Welcome!')); } } ** Original less optimal method ** You can use hook_init() in D7, and check if they have a value for last access: function hook_init() { global $user; $first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField(); if($first_login) { drupal_set_message(t('This is your first login. Welcome!')); } } A: In both Drupal 7 and 8, there is hook_user_login, where you can can check whether the current user has accessed the site before, but the parameters are slightly different. Drupal 7 version: function mymodule_user_login(&$edit, $account) { if ($account->access == 0) { drupal_set_message(t('This is your first login. Welcome!')); } } Drupal 8 version: function mymodule_user_login($account) { if (!$account->getLastAccessedTime()) { drupal_set_message(t('This is your first login. Welcome!')); } } hook_user_login in Drupal 8.
    { "pile_set_name": "StackExchange" }
    Q: Android Studio - Gradle assemble task I'm currently struggling with a build process in gradle. My goal is to not have a specific java class in the final .apk for a specific flavor. The logic goes like this: 1.) before compiling my project delete MyClass.java and copy it to a temp folder 2.) after assembling the apk copy back MyClass.java to my original folder 3.) delete the temp folder This happens only if I build a specific flavor, so it doesn't happen for all build variants. My code works perfectly when I build only one flavor and one build variant e.g. assembleFlavorRelease, but if I wan't to make my code work for multiple build types; if I run assembleFlavor it should build flavorDebug the same way it does flavorRelease. However my logic goes trough only the first time and after that it stops, so flavorDebug is build with MyClass and it shouldn't be, while flavorRelease doesn't include MyClass in the .apk because my code runs the first time. Here is what the code looks like: task copyResource << { copy { from 'src/main/java/MyClass.java' into 'src/temp' } } task deleteResource << { delete { 'src/main/java/MyClass.java' } } task deleteTemp << { delete { 'src/temp' } } task copyBackToSource << { copy { from 'src/temp/MyClass.java' into 'src/main/java' } deleteTemp.execute() } android.applicationVariants.all { variant -> if (variant.name.contains('flavor')) { deleteResource.dependsOn copyResource variant.javaCompile.dependsOn deleteResource variant.assemble.doLast { copyBackToSource.execute() } } } I think that the directories which I use in my code are somehow locked when trying to execute the whole process the second time? A: I feel that you are approaching the problem in the wrong way. Instead of thinking Put the java file in src/main/java and remove it from flavorX You should instead be approaching it as Add an extra source directory to the source sets for flavorY and flavorZ Once you approach the problem like this it becomes much easier If you only want the file in one flavor, you can put the file in the flavor specific source folder using the built in conventions (ie src/flavorX/java) If you want the file in more than one flavor you could put MyClass.java in src/common/java and do something like android { productFlavors { flavor1 { } flavor2 { } flavor3 { } } } sourceSets { flavor1.java = ['src/flavor1/java','src/common/java'] flavor2.java = ['src/flavor2/java','src/common/java'] }
    { "pile_set_name": "StackExchange" }
    Q: Submitting one value of the Hidden input in the current row clicked How to pass one value of the current row of multiple hidden input in PHP. I have the following code: foreach($portfolio as $portfolio){ echo "<tr class ='table-comments'>"; echo "<td>".$portfolio['portfolio_title']."</td>"; echo "<td class = 'comment-content'>".$portfolio['portfolio_client']."</td>"; echo "<td><a target = '_blank' href = ".$portfolio['portfolio_link'].">".$portfolio['portfolio_link']."</a></td>"; echo "<td>"; echo "<input type='hidden' name='portfolio_id' value='" . $portfolio['portfolio_id'] . "' />"; echo "<input type = 'submit' value = 'Edit'>"; echo "<input type = 'submit' value = 'Move to Trash' class = 'action-button'>"; echo "</td>"; echo "</tr>"; } I also have submit button each row that triggers the form. When I click the submit button, it submits all the value of the row of the hidden input. I only want the clicked button row value. URL is like this: /portfolio?portfolio_id=1&portfolio_id=2&portfolio_id=3&portfolio_id=4 and so on I only want /portfolio?portfolio_id=3 A: Have a new form for each row... <form method="get"> </form> Like this: foreach($portfolio as $portfolio){ echo "<tr class ='table-comments'>"; echo "<td>".$portfolio['portfolio_title']."</td>"; echo "<td class = 'comment-content'>".$portfolio['portfolio_client']."</td>"; echo "<td><a target = '_blank' href = ".$portfolio['portfolio_link'].">".$portfolio['portfolio_link']."</a></td>"; echo "<td>"; echo '<form method="get">'; echo "<input type='hidden' name='portfolio_id' value='" . $portfolio['portfolio_id'] . "' />"; echo "<input type = 'submit' value = 'Edit'>"; echo "<input type = 'submit' value = 'Move to Trash' class = 'action-button'>"; echo "</form>"; echo "</td>"; echo "</tr>"; }
    { "pile_set_name": "StackExchange" }
    Q: How to grep a string after a specified line number? I have a large text file, I want to see the lines containing "time spent" in this text file, I use: grep -in "time spent" myfile.txt But I'm interested only in the lines after 50000. In the output I want to see lines after 50000 and that contain "time spent". Is there a way to do this? A: You can tail it, then grep: tail -n +50000 myfile.txt | grep -in "time spent" A: Alternatively you can use sed. sed can be used to mimic grep like this: sed -n 's/pattern/&/p' By default sed prints every line even if no substitution occurs. The combinations of -n and /p makes sed print only the lines where a substitution has occured. Finally, we replace pattern by & which means replace pattern by itself. Result: we just mimicked grep. Now sed can take a range of lines on which to act. In your case: sed -n '50000,$s/time spent/&/p' myfile.txt The format to specify the range is as follow: start,end We just instruct sed to work from line 50000 to $ which means last line. A: Answer for grepping between any 2 line numbers: Using sed and grep: sed -n '1,50000p' someFile | grep < your_string >
    { "pile_set_name": "StackExchange" }
    Q: C# Webbrowser navigating links in order I'm trying to teach myself C# and to start I'm trying to convert a program I originally wrote in Autoit. I'm using a Windows Application Form and the program is suppose to take one or two links as input. Navigate to those to pages, grab some links from a table, then visit each of those pages to grab some content. If only one link is entered it seems to go to that page and grab the links from a table like it is suppose to. If two links are entered it seems to only grab the links from the second table. So if two links are passed this method private void getPageURLList(string site1, string site2) { getPageURLList(site1); getPageURLList(site2); } Calls the same method that gets called when there is only one link private void getPageURLList(string site) { webBrowser.DocumentCompleted += createList; webBrowser.Navigate(site); } I'm pretty sure the issue is "Navigate" is getting called a second time before createList even starts the first time. The reason I am using WebBrowser is because these pages use Javascript to sort the links in the table so HTTPRequests and the HTMLAgilityPack don't seem to be able to grab those links. So I guess my question is: How can I keep my WebBrowser from navigating to a new page until after I finish what I'm doing on the current page? A: You have to make a bool variable to know when the first proccess has completed. And then start the other. Application.DoEvents() will help you. Note that all this events run in the main thread.
    { "pile_set_name": "StackExchange" }
    Q: Where is "to do a magical turn" used to describe an illegal U-turn? There's this expression in Spanish, "hacer una pirula", used to describe a U-turn in a zone not designed to do so. While reading a thread on WordReference to determine the English equivalent, I found the following post: in the US I once heard someone say "to do a magical turn", which in my opinion is what best suits "hacer una pirula" in a driving context. The poster wasn't a native speaker, as per their profile. I haven't been able to find any evidence of the expression "doing a magical turn", so I'm skeptical. Is "to do a magical turn" used in any region of the United States to describe a prohibited U-turn? A: In AmE, performing a U-turn where it is not permitted is simply called an illegal U-turn there is nothing "magical" about it, unless the police "magically" appear and hand you a driving violation.
    { "pile_set_name": "StackExchange" }
    Q: CSS z-index property Really hoping someone can help a z-index novice. I'm trying to position a div on top of everything else on my page: http://www.designbyantony.com/bipf/index.html The div (you can probably see the problem) is the roun blue circle with 'March 6-8 2015'. I'd like it to sit on top of everything else properly - ie: run over the nav bar a bit and chip over the area which has the repeating 'arch' design. I've tried using z-index but I'm obviously going wrong somewhere. CSS is at http://www.designbyantony.com/bipf/styles.css Can anyone help me? A: Change into your CSS like that.Remove the both position:relative from CSS #page_content { width: 970px; margin: auto; height: auto; padding-top: 15px; padding-left: 5px; padding-right: 5px; /* position: relative; */ background-color: #FFFFFF; overflow: hidden; /* position: relative; */ z-index: 2; } and again change your CSS of #dates.remove left position left:1046;top: 171px; and put there right:0 #dates { position: absolute; left: 1046px; top: 171px; z-index: 10000; height: 140px; width: 140px; display: block; background-color: none; } A: Remove overflow: hidden in the #page_content in styles.css at Line 245: #page_content {overflow: visible;} Or if you would like to have clearing after the #page_content, you can use something like this: #page_content:after {display: block; clear: both; content: " ";} Reason: The parent of #dates is been cropped by #page_content, which has overflow: hidden, that doesn't allow contents to be hanging.
    { "pile_set_name": "StackExchange" }
    Q: Unable to get good example of using memcached from Java boot I am using java boot for my development. For now I have used 'EhCache' for caching , it is directly supported from Java boot. This is "in-process" cache, i.e., becomes part of your process. It is okay for now. But my server will run on multiple nodes in near future. Hence want to switch to 'Memcached' as common caching layer. After spending good amount of time, I could not get good sample of using Memcached from java boot. I have looked at 'Simple Spring Memcached' which comes close to my requirement. But still it gives example using XML configuration in Spring way. Java boot does not use such XML configuration as far as possible. At least I could not map the example quickly to java boot world. I want to use Memcahed ( directly or via cache-abstraction-layer) from java boot. If anybody points me to a relevant java boot example, it will save a lot of time for me. A: You can find some materials how to configure SSM using Java configuration instead of XML files here and here. Basically you have to move definitions of all beans from XML to Java.
    { "pile_set_name": "StackExchange" }
    Q: Options basics: How to realize profit from a long call position I'm studying the basics of options trading and just read a 'crash course' book where the author states the following: ...you won't walk away from a call option with cash in hand. The profit we are talking about in this case is "intrinsic value". You can now take that stock and write a buy contract on it, selling it on and making that tangible profit in the process. ... as an options trader, you're not looking to keep hold of a stock portfolio. You're purchasing stocks through contracts to turn around and sell for a profit. So I have a fundamental question about long call options. Is the author here alluding to a requisite purchase of the underlying shares before a "buy contract" can be written against them? Surely, this is implied, because without executing the contract, you would have nothing to sell, right? My confusion is compounded by a statements just a couple of paragraphs prior Buying calls also allows you to consider shares that would ordinarily be out of your price range. ... Buying options on those stocks is a whole lot less expensive than buying the stocks themselves, ... This is call "leverage": the ability to control thousands of dollars in stock for just hundreds of dollars in premium. Here again I'm lost - if you have to execute the position in order to profit, then you need the full amount of the contract to ultimately purchase those shares, right? Lastly, if I have a long call that becomes valuable, whereby the strike price + premium is less than the current price of the stock, I then need to execute the option, buy buying the stock, before I can actually sell those shares (immediately after purchase) for a profit, right? Or is there some other way to realize the profit without actually purchasing the stock? A: It's no wonder that you're confused. The first paragraph that you quoted is a disaster. In clearer words: If a call appreciates in price and you sell it, you walk away with cash in hand and a profit That profit can be from intrinsic or extrinsic premium (the call's price must simply appreciate) There is no such thing as writing a buy contract. Writing is synonymous with selling to open (STO). If you were to sell a call against the original long call, you would be creating a spread (vertical, calendar, diagonal). There are two reasons to exercise an ITM call: 1) You want to own the stock. 2) If a call is ITM and it trades for less than parity (bid is less than intrinsic value) or as you wrote, the "strike price + premium is less than the current price of the stock", you can try for some price improvement with your STC order but there is no incentive for the market maker or anyone else to give you the full intrinsic value. While waiting for a better fill, the price of XYZ could drop and you could give back some of your call's gain. To avoid this haircut, you can perform perform the same Discount Arbitrage that a market maker would. If you have the margin to cover a short sell, short the stock and then exercise the call. That locks in the intrinsic value and avoids the haircut (short the stock first to avoid possible underlying price slippage). If you don't have the margin then you're going to have to work the order and take whatever you can get. If you need an example, ask away.
    { "pile_set_name": "StackExchange" }
    Q: ASP.NET MVC 4 Intranet Template - Show Users Full Name I am using the Intranet template for MVC 4 under the VS 2012 RC. The top right hand corner shows domain\username, and I want it to show full name instead. I was able to get this working in _Layout.cshtml. I included the following helper in the body - @helper AccountName() { using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain)) { try { var principal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, User.Identity.Name); @String.Concat(principal.GivenName, " ", principal.Surname) } catch { } } } (I also had to include System.DirectoryServices.AccountManagement in the References) I could then use the helper in the greeting code as follows - <section id="login"> Hello, <span class="username">@AccountName()</span>! </section> This works ok, but I don't like having the code in the _Layout.cshtml. I tried to put the helper in a seperate file under a Helpers directory, but @AccountName() no longer resolved then. Ideally the code should really be in a straight CS file. Can anyone suggest a better way to set this up? A: You can certainly put the code in a regular C# file, e.g. AccountUtil.AccountName() In that case, you need to include the namespace your helpers are in by placing @using My.App.Helpers @* Change to your own namespace *@ at the top of any view that wants to reference that code. Alternatively, you can make that namespace available to all views by editing the web.config file in the Views directory (not the one at the project level) <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <!-- Don't edit out the stuff that's already here! --> <add namespace="My.App.Helpers" /> <!-- Add your own namespace here --> </namespaces> </pages> </system.web.webPages.razor>
    { "pile_set_name": "StackExchange" }
    Q: Flutter : PageView keep Stay in previous Screen I use PageView in my screen to Navigate to another screen. I have 3 screen Home,History and History Detail. Everything is fine i can move to history screen. Until i redirect to History Detail from History Screen and i back with Navigator.of(context).pop , I redirect to Home Screen. I want after Back from History Detail i keep stay in History Screen. I already initialize initialPage is 0 , and change the initialPage with onPageChanged but nothing happens, i still redirect to Home Screen. How can i do for my case? It's My Source Code. PageController _pageController; int currentPage = 0; @override void initState() { _pageController = PageController(initialPage: currentPage); super.initState(); } Widget build(BuildContext context) { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); double mqHeight = MediaQuery.of(context).size.height; return Scaffold( key: _scaffoldKey, body: FutureBuilder( future: Hive.openBox("debt_box"), builder: (ctx, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) return Text(snapshot.error.toString()); else return Scaffold( body: PageView( scrollDirection: Axis.vertical, onPageChanged: (index) { currentPage = index; print(currentPage); }, physics: NeverScrollableScrollPhysics(), controller: _pageController, children: <Widget>[ CustomScrollView( slivers: <Widget>[ SliverAppBarHome(), SliverListHome(_scaffoldKey), ], ), HistoryDebt(), ], ), ); } else { return Center(child: CircularProgressIndicator()); } }, ), bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), child: Container( height: mqHeight * 0.08, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ IconButton( icon: Icon(Icons.home), onPressed: () => functionHelper.previousButtonPageView(_pageController), ), IconButton( icon: Icon(Icons.insert_chart), onPressed: () => functionHelper.nextButtonPageView(_pageController), ), ], ), ), ), } A: I found the issue. When you press back button it re-builds your main widget. In the build method you have FutureBuilder which also gets rebuild. So it will show you CircularProgressIndicator. Since Hive.openBox("debt_box") gives the result instantaneously, you are not able to see it. While showing CircularProgressIndicator your PageView got deactivated (removed from widget tree). So _pageController loses its client. After the CircularProgressIndicator, a new PageView gets created. That is why it showed Home page Solution: As per the document we should not directly assign future: Hive.openBox("debt_box") during the build. Instead create a Future variable and initialize it in the initState, then pass that variable to future property of FutureBuilder PageController _pageController; int currentPage = 0; Future _openBox; @override void initState() { _pageController = PageController(initialPage: currentPage); _openBox = Hive.openBox("debt_box"); //initialize here super.initState(); } Widget build(BuildContext context) { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); double mqHeight = MediaQuery.of(context).size.height; return Scaffold( key: _scaffoldKey, body: FutureBuilder( future: _openBox, //pass the future variable here builder: (ctx, snapshot) { ...
    { "pile_set_name": "StackExchange" }
    Q: smtplib - No connection could be made because the target machine actively refused it although I can find a lot of similar questions regarding this failure, the suggestions/answers dont help my case so I am looking for some help. I have the following function which works perfectly fine on my development machine(Windows 7) but when I try to run it on another machine which is running a Windows Server 2012 R2 Standard OS, I get the "Errno 10061 - No connection could be made because the target machine actively refused it" failure. I have tried disabling the firewall on the machine but that didnt help. I know the port and SMTP server are correctly listening as the same code on my development machine works. How do I go about resolving this? Any help is appreciated def send_email(user, pwd, recipient, subject, body): gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465) server_ssl.ehlo() # server_ssl.starttls() server_ssl.login(gmail_user, gmail_pwd) server_ssl.sendmail(FROM, TO, message) server_ssl.close() print 'successfully sent the mail' except: print "failed to send mail" A: the problem was the firewall blocking the connection. Once that was removed the script works
    { "pile_set_name": "StackExchange" }
    Q: Why should one study English in India? I'm a teacher teaching English in a village school.I need a concrete reason to continue to do so.I am looking for opinions,facts,references & even specific expertise. A: English is one of the two official languages of India, the second being Hindi. If any of your students want a job in any official government post, or a job where they have to deal with the government, speaking English will be a huge advantage to them. Being able to speak any other language is good for ones job prospects, and is in any case a fulfilling enterprise which broadens the mind. English is widely used across the world as a lingua franca. So being able to speak English enables you to communicate with people from many different parts of the world, including many other people for whom English isn't their first language.
    { "pile_set_name": "StackExchange" }
    Q: Gradle multiple android apps I want with help of gradle build 2-3 different APKs where the app name changes and some lines of code. I don't want to change whole directories or whole files, only snippets of code, is this possible? I have tried to understand Build variants and Product flavor. but can't figure out how it works. Also this tutorial. Thanks A: This is just a suggestion. We faced the same thing and this is how we got it to work. In my opinion it's very clean and yes it does use product flavors. So let's say you have a class Address, which is formatted differently from country to country, but of course has a lot of common code. For the sake of simplicity let's say you have only street_number and street_name, but on country A the address should be formatted as street_number street_name and on country B it should be formatted as street_name, street_number. The way we did this was having a project structure like so: src | |\ main |\ countryA |\ countryB So the project has 2 flavors - countryA and countryB. Here's the relevant build.gradle part: productFlavors { countryA { applicationId "com.countryA" } countryB { applicationId "com.countryB" } } Now for the code part. So Address is a common class which we placed inside main and would look more or less like: public abstract class AbstractAddress { private String streetNumber; private String streetName; // ... your favorite getters and setters plus some common methods public abstract String getFormattedAddress(); } The key here is that the class is abstract and the sub-classes need to implement getFormattedAddress(). Now in the countryA folder you'd have: package com.myapp.addresses; public class Address extends AbstractAddress { public String getFormattedAddress() { return getStreetNumber() + " " + getStreetName(); } } Now in the same package as in countryA but in countryB's folder, you'd have the same class, but with a different implementation: package com.myapp.addresses; public class Address extends AbstractAddress { public String getFormattedAddress() { return getStreetName() + ", " + getStreetNumber(); } } Gradle will take care of generating the tasks for you. Something on the lines of assembleCountryA and assembleCountryB (It also depends on the build variants you have). Of course you can also generate all apks using only one task.
    { "pile_set_name": "StackExchange" }
    Q: How to run android app in emulator by rewriting old databases? When I always run app to test in emulator from Eclipse , by default it never uninstalls previous one. It will maintain previous copy of database and files of the same app and run a new compiled code. What if I want to remove all app related files, databases every time I compile and run it to test? Any settings for this in Eclipse ? I want to avoid the step of manually uninstalling it before every run. Thanks. A: You can have a command prompt window open, and before launching, execute: adb uninstall your.project.package when using adb install with the -r modifier, the app re-installs and its data is saved. I haven't found any place in Eclipse to change this configuration, but I think this is done inside the SDK's Ant tasks. Take a look at this class for more information
    { "pile_set_name": "StackExchange" }
    Q: Change password profile I'm running CiviCRM under Wordpress. I want to create a donor area, where they can change their information. But I can't find way to let them change their password. Why is not possible to add a "password" field in profiles? A: CiviCRM does not maintain logins or credentials. It instead opts to let the CMS (WordPress in your case) to manage it all. CiviCRM can maintain the link between a user account on the CMS with a contact in CiviCRM though. As Andrew West points out, you need to manage the password via WordPress. A: You can't put this into a profile afaik. I use Profile Builder to create a separate front-end WP page. Theme My Login works ok too.
    { "pile_set_name": "StackExchange" }
    Q: extend images across slide active slide I am creating a website for a school project and we were asked to choose a company to design a mock promotional website for. I chose CVS but you could choose anyone. I managed to use a template which I had done completing some codecamdemy classes but the tutorials didn't appear to be helpful in regards to changing the length of the images. What I want to do is to extend the images called "nyse", "mentor" and "mountain" across the length of the whole slide container, but so far, when I change it, the image doesn't seem to do anything. Can anyone tell me where it is going wrong or where to put my code to extend the images? I have tried numerous divs but no luck so far. My code is presented below. HTML <!doctype html> <html> <head> <link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet'> <link href="http://s3.amazonaws.com/codecademy-content/courses/ltp2/css/bootstrap.min.css" rel="stylesheet"> <link href="style.css" rel="stylesheet"> </head> <body> <div class="header"> <div class="container"> <a href="#" class="logo-icon"> <img src="img/cvs.png"> </a> <div class="headerNi"> <div class="container"> <a href="#" class="logo-icon"> <p><a href title="Click this link to view the scheme.">NIDC Graduate Scheme</a></p> </a> <div id ="headerMission">CVS Health's Northern Ireland Development Centre, which opened in 2012,<br> creates software solutions for all parts of the US company,<br> with particular focus on internet and mobile applications.</div></div> <ul class="menu"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Curriculum</a></li> <li><a href="#">Staff Profiles</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Register</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle">More <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Graduate Scheme</a></li> <li><a href="#">What we look for</a></li> <li><a href="#">Links</a></li> </ul> </li> </ul> </div> </div> </div> </div> <div class="slider"> <div id="nyse-slide" class="slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>CVS is now hiring</h1> <p>We will soon have a nice new building.</p> <ul class="get-app"> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/ios.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/android.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/windows.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/blackberry.png"></a></li> </ul> </div> <div class="slide-img col-xs-7"> <img src="img/nyse.jpg" width="540px"> </div> </div> </div> </div> <div class="slide slide-feature"> <div class="container"> <div class="row"> <div class="col-xs-12"> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <a href="#">Accountability</a> <p>Take responsibility for your actions.</p> </div> </div> </div> </div> <div id="mountain-slide" class="slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>Collaboration</h1> <p>At CVS, it's important to work together with your mentor!</p> </div> <div class="slide-img col-xs-7"> <img src="img/mountain.png"> </div> </div> </div> </div> <div id="pharm-slide" class="slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>Tenacity</h1> <p>Be determined.</p> <ul class="get-app"> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/ios.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/android.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/windows.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/blackberry.png"></a></li> </ul> </div> <div class="slide-img col-xs-7"> <img src="img/pharm.jpg" width="540px"> </div> </div> </div> </div> </div> <div class="slider-nav"> <a href="#" class="arrow-prev"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/arrow-prev.png"></a> <ul class="slider-dots"> <li class="dot active-dot">&bull;</li> <li class="dot">&bull;</li> <li class="dot">&bull;</li> <li class="dot">&bull;</li> </ul> <a href="#" class="arrow-next"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/arrow-next.png"></a> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="app.js"></script> </body> </html> CSS .container { width: 960px; color: gray; } /* Header */ .header { background-color: rgba(255, 255, 255, 0.95); border-bottom: 1px solid #ddd; font-family: 'Oswald', sans-serif; font-weight: 300; font-size: 17px; padding: 15px; } /* Menu */ .header .menu { float: right; list-style: none; margin-top: 5px; } .menu > li { display: inline; padding-left: 20px; padding-right: 20px; } .menu a { color: #898989; } /* Dropdown */ .dropdown-menu { font-size: 16px; margin-top: 5px; min-width: 105px; } .dropdown-menu li a { color: #898989; padding: 6px 20px; font-weight: 300; } /* Carousel */ .slider { position: relative; width: 100%; height: 470px; border-bottom: 1px solid #ddd; } .slide { background: transparent url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/feature-gradient-transparent.png') center center no-repeat; background-size: cover; display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .slide { text-align: center; height: 550px; } #nyce-slide{ background-image: url('nsce.jpg'); } #pharm-slide-feature{ background-image: url('pharm.jpg'); } #mountain-slide-feature{ background-image: url('mountain.jpg'); } .active-slide { display: block; } .slide-copy h1 { color: #363636; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 40px; margin-top: 105px; margin-bottom: 0px; } .slide-copy h2 { color: #b7b7b7; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 40px; margin: 5px; } .slide-copy p { color: #959595; font-family: Georgia, "Times New Roman", serif; font-size: 1.15em; line-height: 1.75em; margin-bottom: 15px; margin-top: 16px; } .slide-img { text-align: right; } /* Slide feature */ .slide-feature { text-align: center; background-image: url('http://devonsstudio.com/businesspeople.png'); height: 550px; } .slide-feature img { margin-top: 112px; margin-bottom: 28px; } .slide-feature a { display: block; color: #6fc5e0; font-family: "HelveticaNeueMdCn", Helvetica, sans-serif; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 20px; } .slide-feature p { color: red; } .slider-nav { text-align: center; margin-top: 80px; } .arrow-prev { margin-right: 45px; display: inline-block; vertical-align: top; margin-top: 9px; } .arrow-next { margin-left: 45px; display: inline-block; vertical-align: top; margin-top: 9px; } .slider-dots { list-style: none; display: inline-block; padding-left: 0; margin-bottom: 0; } .slider-dots li { color: #bbbcbc; display: inline; font-size: 30px; margin-right: 5px; } .slider-dots li.active-dot { color: #363636; } /* App links */ .get-app { list-style: none; padding-bottom: 9px; padding-left: 0px; padding-top: 9px; } .get-app li { float: left; margin-bottom: 5px; margin-right: 5px; } .get-app img { height: 40px; } color: #898989; padding: 6px 20px; font-weight: 300; } /* Carousel */ .slider { position: relative; width: 100%; height: 470px; border-bottom: 1px solid #ddd; } .slide { background: transparent url('http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/feature-gradient-transparent.png') center center no-repeat; background-size: cover; display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .active-slide { display: block; } .slide-copy h1 { color: #363636; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 40px; margin-top: 105px; margin-bottom: 0px; } .slide-copy h2 { color: #b7b7b7; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 40px; margin: 5px; } .slide-copy p { color: #959595; font-family: Georgia, "Times New Roman", serif; font-size: 1.15em; line-height: 1.75em; margin-bottom: 15px; margin-top: 16px; } .slide-img { text-align: right; } /* Slide feature */ .slide-feature { text-align: center; background-image: url('http://devonsstudio.com/businesspeople.png'); height: 550px; } .slide-feature img { margin-top: 112px; margin-bottom: 28px; } .slide-feature a { display: block; color: #6fc5e0; font-family: "HelveticaNeueMdCn", Helvetica, sans-serif; font-family: 'Oswald', sans-serif; font-weight: 400; font-size: 20px; } .slide-feature p { color: red; } .slider-nav { text-align: center; margin-top: 80px; } .arrow-prev { margin-right: 45px; display: inline-block; vertical-align: top; margin-top: 9px; } .arrow-next { margin-left: 45px; display: inline-block; vertical-align: top; margin-top: 9px; } .slider-dots { list-style: none; display: inline-block; padding-left: 0; margin-bottom: 0; } .slider-dots li { color: #bbbcbc; display: inline; font-size: 30px; margin-right: 5px; } .slider-dots li.active-dot { color: #363636; } /* App links */ .get-app { list-style: none; padding-bottom: 9px; padding-left: 0px; padding-top: 9px; } .get-app li { float: left; margin-bottom: 5px; margin-right: 5px; } .get-app img { height: 40px; } JAVASCRIPT var main = function() { $('.dropdown-toggle').click(function() { $('.dropdown-menu').toggle(); }); $('.arrow-next').click(function(e) { e.preventDefault(); var currentSlide = $('.active-slide'); var nextSlide = currentSlide.next(); var currentDot = $('.active-dot'); var nextDot = currentDot.next(); if(nextSlide.length === 0) { nextSlide = $('.slide').first(); nextDot = $('.dot').first(); } currentSlide.fadeOut(600).removeClass('active-slide'); nextSlide.fadeIn(600).addClass('active-slide'); currentDot.removeClass('active-dot'); nextDot.addClass('active-dot'); }); $('.arrow-prev').click(function(e) { e.preventDefault(); var currentSlide = $('.active-slide'); var prevSlide = currentSlide.prev(); var currentDot = $('.active-dot'); var prevDot = currentDot.prev(); if(prevSlide.length === 0) { prevSlide = $('.slide').last(); prevDot = $('.dot').last(); } currentSlide.fadeOut(600).removeClass('active-slide'); prevSlide.fadeIn(600).addClass('active-slide'); currentDot.removeClass('active-dot'); prevDot.addClass('active-dot'); }); } $(document).ready(main); A: Heres a DEMO FIDDLE (You only need to add your images URLS to the CSS) The first thing you need to do is to add e.preventDefault(); to your click evennts like this: $('.arrow-next').click(function(e) { e.preventDefault(); //..more code }); $('.arrow-prev').click(function(e) { e.preventDefault(); //..more code }); Then you need to give each slide a unique ID and give it a background for the image, just like you have a background for the .slide-feature like this: HTML: <div id="nyce-slide" class="slide"> <!-- ...code.. --> </div> <div id="mountain-slide" class="slide"> <!-- ...code.. --> </div> <div id="mentor-slide" class="slide"> <!-- ...code.. --> </div> CSS: .slide { text-align: center; height: 550px; } #nyce-slide{ background-image: url('nyce.jpg'); } #mentor-slide{ background-image: url('mentor.jpg'); } #mountain-slide{ background-image: url('mountain.jpg'); } Heres the final edit: <body> <div class="header"> <div class="container"> <a href="#" class="logo-icon"> <img src="img/cvs.png"> </a> <div class="headerNi"> <div class="container"> <a href="#" class="logo-icon"> <p><a href title="Click this link to view the scheme.">NIDC Graduate Scheme</a></p> </a> <div id ="headerMission">CVS Health's Northern Ireland Development Centre, which opened in 2012,<br> creates software solutions for all parts of the US company,<br> with particular focus on internet and mobile applications.</div></div> <ul class="menu"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Curriculum</a></li> <li><a href="#">Staff Profiles</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Register</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle">More <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Graduate Scheme</a></li> <li><a href="#">What we look for</a></li> <li><a href="#">Links</a></li> </ul> </li> </ul> </div> </div> </div> <div class="slider"> <div id="nyce-slide" class="slide active-slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>CVS is now hiring</h1> <p>We will soon have a nice new building.</p> <ul class="get-app"> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/ios.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/android.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/windows.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/blackberry.png"></a></li> </ul> </div> </div> </div> </div> <div id="accountability-slide" class="slide"> <div class="container"> <div class="row"> <div class="col-xs-12"> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <a href="#">Accountability</a> <p>Take responsibility for your actions.</p> </div> </div> </div> </div> <div id="mountain-slide" class="slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>Collaboration</h1> <p>At CVS, it's important to work together with your mentor!</p> </div> </div> </div> </div> <div id="mentor-slide" class="slide"> <div class="container"> <div class="row"> <div class="slide-copy col-xs-5"> <h1>Tenacity</h1> <p>Be determined.</p> <ul class="get-app"> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/ios.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/android.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/windows.png"></a></li> <li><a href="#"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/blackberry.png"></a></li> </ul> </div> </div> </div> </div> </div> <div class="slider-nav"> <a href="#" class="arrow-prev"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/arrow-prev.png"></a> <ul class="slider-dots"> <li class="dot active-dot">&bull;</li> <li class="dot">&bull;</li> <li class="dot">&bull;</li> <li class="dot">&bull;</li> </ul> <a href="#" class="arrow-next"><img src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/flipboard/arrow-next.png"></a> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var main = function() { $('.dropdown-toggle').click(function() { $('.dropdown-menu').toggle(); }); $('.arrow-next').click(function(e) { e.preventDefault(); var currentSlide = $('.active-slide'); var nextSlide = currentSlide.next(); var currentDot = $('.active-dot'); var nextDot = currentDot.next(); if (nextSlide.length === 0) { nextSlide = $('.slide').first(); nextDot = $('.dot').first(); } currentSlide.fadeOut(600).removeClass('active-slide'); nextSlide.fadeIn(600).addClass('active-slide'); currentDot.removeClass('active-dot'); nextDot.addClass('active-dot'); }); $('.arrow-prev').click(function(e) { e.preventDefault(); var currentSlide = $('.active-slide'); var prevSlide = currentSlide.prev(); var currentDot = $('.active-dot'); var prevDot = currentDot.prev(); if (prevSlide.length === 0) { prevSlide = $('.slide').last(); prevDot = $('.dot').last(); } currentSlide.fadeOut(600).removeClass('active-slide'); prevSlide.fadeIn(600).addClass('active-slide'); currentDot.removeClass('active-dot'); prevDot.addClass('active-dot'); }); } $(document).ready(main); </script> </body>
    { "pile_set_name": "StackExchange" }
    Q: How can I retrieve all property values from a list of common objects? I want to retrieve all single properties from a collection as an array: class Foo{ public string Bar { get; set; } public string Baz { get; set;} } I want to get i.e. all Bar properties from the collection var list = new List<Foo>(); string[] allBars = list. .... and how does it go on??? Thanks for any help. A: You can use: string[] allBars = list.Select(foo => foo.Bar).ToArray(); I would only convert this to an array if you specifically need it to be in an array. If your goal is just to output the "Bar" list, you could just do: var allBars = list.Select(foo => foo.Bar); // Will produce IEnumerable<string> foreach(var bar in allBars) { // Do something with bar }
    { "pile_set_name": "StackExchange" }
    Q: Get the full exception type/message and stack trace I've written an API which returns Json in the following format... {"Success": true, Result: {...}} {"Success": false, ExceptionId: "(some uuid)"} The exceptions are logged. This is fine in principle for allowing someone to discuss an error without us ever telling them what it is (as a security measure). During debugging I also want to output the error message to stop me having to refer to a database all the time. As things stand, the problem is getting useful information from the exception (either to return or log in the db) I'm doing something like this... try: Ret['Result'] = <Blah> Ret['Success'] = True except Exception as e: # ... Logging/ExceptionId if Settings.DebugMode: Ret['Exception'] = str(e) If I put a breakpoint on the last line and inspect e in eclipse's watch window, I get KeyError: 'Something', but str(e) results in 'Something' which is very unhelpful. I've googled and I can't find any way to get a proper message from an exception. Apparently there used to be a .message in v<2.4 but that's no help to me in 3.3 As an alternative, I tried doing: Ret['Exception'] = str(type(e)) + ": " + str(e) Which resulted in <class 'KeyError'>: 'job' which is a little closer but it's starting to feel more and more hackish. I also want to include a Stack Trace but have had even less luck there - I can get the __traceback__ but of course it's not serializable and calling str() on it just results in a description of the object eg <traceback object at 0x0000000004024E48> How can I get a decent/comprehensive error message? A: You probably want repr: Ret['Exception'] = repr(e) For the traceback, use the traceback module: from traceback import format_exc Ret['Traceback'] = format_exc()
    { "pile_set_name": "StackExchange" }
    Q: SAS - How to filter by max value from one column in a datastep I have a yearly survey that I do some validations on. I only want to do the validations for the current year (max year in the column surveyYear). The survey comes every year so I want to have it automatised instead of writing the current year. So when the survey for 2019 comes I do not need to change the code. Is it possible to filter surveyYear in the set statement to only take the largest number in the column? I have tried different combinations but do not sucseed. And if it is not possible, how could I solve it otherwise I would also like to do it in a datastep and not in proc as the validation code comes in the want datastep after the set statement. data have; input surveyYear id score varChar$10. ; datalines; 2016 1 10 Yes 2016 2 6 Yes 2016 3 8 Yes 2016 4 . No 2017 5 6 No 2017 6 5 No 2017 7 12 IU 2017 8 3 IU 2017 9 2 IU 2017 10 15 99999 2018 11 0 . 2018 12 . No 2018 13 10 Yes 2018 14 8 No 2018 15 11 No 2018 16 3 IU ; run; data want; set have (where=(surveyYear > 2017)); /* I would like to have something that states the max surveyYear instead */ /* (where=(surveyYear = max(surveyYear))) */ run; A: To filter for the max you can first get hte max and then apply a filter. proc sql noprint; select max(year) into :latest_year from have; quit; Then use it in your filter. data want; set have (where=(year=&latest_year.));
    { "pile_set_name": "StackExchange" }
    Q: In a RESTFul API, what's the correct http verb to a revert / rollback action? Imagine a simple document management webservice strutured like this: document/ GET -> retrieves all documents POST -> creates a new document document/[id] GET -> retrieves the "latest" revision of document specified by ID POST -> creates a new revision of the document document/[id]/revision GET -> retrieves all revisions of the document POST -> Alias to POST->document/[id] document/[id]/revision/[revisionID] GET -> retrieves the specified revision of the document Now, let's say I want to rollback a document to a previous arbitrary revision (for instance, from revision 5 to 3). In a RESTful point of view, what ROUTE and what VERB should be used for this kind of operation? Should I create a new verb for rollback operations? Keep in mind that in a rollback operation nothing is deleted. Internally, the server just recognises a different revision number as the latest. A: Since you have the representations for each revision available, and the rollback operation should be idempotent, the most straightforward approach would be simply doing a PUT to document/[id] with the contents of GET document/[id]/revision/[revisionid], for the revisionid you want document/[id] to be set to.
    { "pile_set_name": "StackExchange" }
    Q: Loading state in react: Too many re-renders. React limits the number of renders to prevent an infinite loop How do I prevent the following error: Too many re-renders. React limits the number of renders to prevent an infinite loop.' My code: function App() { const [items, setItems] = useState([]); const [isLoading, setIsLoading] = useState(true); if (items.length == 0) loadMore() return <div> {isLoading ? <div>Loading...</div> : <ol>{items.map(i => <li>{i}</li>)}</ol> } <button disabled={isLoading} onClick={loadMore} style={{ width: "100%" }}> {isLoading ? "Loading..." : "Load again"} </button> </div>; function loadMore() { setIsLoading(true); // ⚠ errors! const uri = "https://www.reddit.com/r/reactjs.json"; fetch(uri) .then(r => r.json()) .then(r => { const newItems = r.data.children.map(i => i.data.title); items.push(...newItems); setItems([...items]); setIsLoading(false); }); } } Stackblitz link. A: That's because of this condition if (items.length == 0) loadMore(). Because at the beginning the length is 0, loadMore is called in which you set the state and you enter the condition again which call loadMore and so on. Use the useEffect hook with an empty array of dependencies instead of the condition which will call the function once when the component mount. useEffect(loadMore, [])
    { "pile_set_name": "StackExchange" }
    Q: Is there an alternative to a purchase order that sellers can use? The only thing I can find is a sales order, but the problem with that is it isn't legally binding. To be more specific on what I mean: Say that we want to sell someone business cards that includes a specific amount of time for graphic design. And we want to get paid after the graphic design, but before printing. Is there a way before graphic design starts to have a client binded to an agreement that they'll pay us for work done, and if/when design is approved, printing? I know a contract would work, but for something as common as business cards - it seems like overkill and would put people off. Purchase orders from customers would be great, but most of them are too small to use them. Are there any options that are simple like a PO, can state a list of terms, and be very easy for customers to get through? Every contract we've had written has been so long that customers don't fully understand the terms. Simple is better for a quick job like this so they DO get the terms clearly. A: There's a tradeoff in written contracts: The more precise and comprehensive, the longer they have to be. The basics of a contract are described here, and it's possible to have a legally valid contract without writing anything at all. But the more you care about avoiding ambiguity and covering "corner cases," the more you need an experienced attorney to write your contract. You can ask an attorney to avoid "legalese" to the extent possible, and to try to make a contract as "easy to read and understand" as possible. Some are better at that than others.
    { "pile_set_name": "StackExchange" }
    Q: Why can't I be happy in the pursuit of Nirvana? If you are happy, you will have to face sorrow right? So I am being told to just observe everything with equanimity or Anapana. TBH which is very boring So I observed that instead of thinking of everything leads to sorrow in this world, why not enjoy this moment. (Is is necessary to keep observing when you are happy.) After all we want Nirvana because we are looking for a being in a state of something eternal, Which is equanimity. According to me Equanimity is not happiness for sure. In this Video Philosopher and writer Jim Holt says we can't live like dead humans as per Buddhism and think like a western. I have experienced intoxication occasionally and I was in to Anapana for nearly a week and I have kept myself safe from any kind of intoxication for a year, everything was going smooth breathing while walking, lying, sitting, talking not always but I was satisfied with my pace of being aware. But this weekend I had nothing to do and suddenly a teeny tiny thought arises which says to get drunk and at the same time one of my friend said the same thing and we get drunk. I was still trying to figure out what is happening in mind, Why I am feeling different now. I know I should not be drinking is there anyway I can punish myself. I was actually scared of getting attacked by mind when alone. It attacked. Should i keep in doing Anapana as i believes that it cuts your Karmic chain for the moment. A: If you are happy, you will have to face sorrow right? So I am being told to just observe everything with equanimity or Anapana. TBH which is very boring So I observed that instead of thinking of everything leads to sorrow in this world, why not enjoy this moment. (Is is necessary to keep observing when you are happy.) To answer this section: You are temporarily right to try to be happy this moment. A wise person would think "How can I maintain this happiness forever without changing?". A sensible person, upon contemplating the matter for some time, realizes there is nothing created that he or she can retain forever. He or she furthermore realizes such possessions can't be guaranteed to be with oneself beyond death. Thus, a wise person decides the boring path provides freedom from such a mass, sorrow and disappointment. After all we want Nirvana because we are looking for a being in a state of something eternal, Which is equanimity According to me Equanimity is not happiness for sure. To answer this section: Eternity is a word used to describe something that was created and lasts for ever. Nirvana isn't such a thing that is created. Nirvana has not been described as equanimity in the Tipitaka to my knowledge. I have experienced intoxication occasionally and I was in to Anapana for nearly a week and I have kept myself safe from any kind of intoxication for a year, everything was going smooth breathing while walking, lying, sitting, talking not always but I was satisfied with my pace of being aware. But this weekend I had nothing to do and suddenly a teeny tiny thought arises which says to get drunk and at the same time one of my friend said the same thing and we get drunk. I was still trying to figure out what is happening in mind, Why I am feeling different now. To answer this section: Where is that thought now? Did it come to your mind out of your own will? Can you control it? If you can't control it, is it suitable to think the thought is me, mine, or my soul? I know I should not be drinking is there anyway I can punish myself. I was actually scared of getting attacked by mind when alone. It attacked. To answer this section: I suggest your reward yourself by contemplating the benefits of avoiding drinking rather than punishing yourself. I'm sure there's plenty online resources to explain these benefits apart from a Buddhist context. Should i keep in doing Anapana as i believes that it cuts your Karmic chain for the moment. To answer this section: False. If a person can cut the karmic chain for a moment as such and dies, he'll attain Nirvana. There is no moment a lay person is void of Karmic chain (sankhara). This is what binds us to bhava (world, so to speak). I suggest your practice Satipattana Meditating which includes Anapana Sathi and extends a more insightful consciousness to day to day activity. Buddha has asked us (citation needed) to travel in the Noble Eightfold Path even if it means crying along the way. Why Buddha says so is because he knows, and intelligent people understand that if someone missed the opportunity to understand the Four Noble Truths, the resultant suffering can be extremely large. Buddha has said Nibbanam Paraman Sukhan Which translates to Ultimate Luxury is Nibbana
    { "pile_set_name": "StackExchange" }
    Q: True or false:if $A\subset B$, then $P(A)<P(B)$? They ask me if this statement is true or false, and explain why. They suggest I write an example showing why it is false or true. The statement is: if $A\subset B$, then $P(A)<P(B)$. What I tried was to draw a Venn diagram and show that and show that $pa(A)=p(B)$, so then the answer is false. But I want to know if there is a better way to show this, or something a little bit more formal (not too much). Thanks. A: False: In a normal distribution, $P(\Bbb R)=P(\Bbb R\setminus\{0\})=1$ A: $$B=A\cup (B-A)\,\,\,,\,\,A\cap (B-A)=\varnothing\quad,P(B-A)\ge 0$$ $$P(B)=P(A)+P(B-A)\implies P(A)\le P(B)$$
    { "pile_set_name": "StackExchange" }
    Q: Using sed to find and replace a range of numbers first poster here. Trying to use sed to find and replace a word. Code is as follows: configFile=ConnectionConfig.xml sed 's/30??\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile And I'd run the file like this: ./choosePort.sh 3001 When I run this code, there are no errors given like bad regex format, it just doesn't replace anything and the contents of tempXml.xml are just the contents of ConnectionConfig, unchanged. What I'd like to be able to do is recognise any number 3000 - 3099 in the 30?? part of the expression, which I thought was what the '?' did. The input line I'm trying to change is: <host id="0" address="someip" port="3001" authentication="someauthkey" Thanks in advance. (Ip and authkeys in file blanked out for security reasons). A: Use [0-9] instead of ? to match a single digit. sed 's/30[0-9][0-9]\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile
    { "pile_set_name": "StackExchange" }
    Q: get result using startActivityForResult() I am trying to open my calculator and value from it then I am done here is my code for my page (where the main point is as it shows how I tried to get result) TextView.OnClickListener listener = new TextView.OnClickListener() { public void onClick(View v) { startActivityForResult(new Intent("com.easyPhys.start.calculator"), 1); } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if(resultCode==1) { Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show(); } } this is how I tried to give a result from calculator.java: mClickListener = new ButtonClickListener(); int idList[] = { R.id.button0, R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.button6, R.id.button7, R.id.button8, R.id.button9, R.id.buttonLeftParen, R.id.buttonRightParen, R.id.buttonPlus, R.id.buttonDone, R.id.buttonMinus, R.id.buttonDivide, R.id.buttonTimes, R.id.buttonDecimal, R.id.buttonBackspace, R.id.buttonClear, R.id.buttonPow, R.id.buttonSin, R.id.buttonCos,R.id.buttonTan,R.id.buttonAcos,R.id.buttonAtan,R.id.buttonAsin,R.id.buttonLog,R.id.buttonLog10,R.id.buttonComma,R.id.buttonToradians,R.id.buttonTodegrees }; for(int id : idList) { View v = findViewById(id); v.setOnClickListener(mClickListener); } private class ButtonClickListener implements OnClickListener { @Override public void onClick(View v) { case R.id.buttonDone: if(mMathString.length() > 0); Bundle bundle = new Bundle(); bundle.putString("str", mMathString.toString()); Intent in = new Intent(); in.putExtras(bundle); setResult(1, in); new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }; break; can anyone help me to understand where I went wrong as program does not close and give an answer? A: Have you verified that your onClick method is being called? The reason I ask is that you show the code for onClick but you don't show that you set this for the equals button by calling setOnClickListener.
    { "pile_set_name": "StackExchange" }
    Q: file uploading to folder with current time I've created successful a file uploading-system. but how do I move the uploaded-file to a folder with a random name? (current time) index.php: <!doctype html> <body> <form action="file-up.php" method="post" enctype="multipart/form-data"> <table> <tr><td>File:</td><td><input type="file" name="myfile"></td></tr> <tr><td>&nbsp;</td><td><input type="submit" value="Upload"></td></tr> </table> </div> </form> </body> </html> file-up.php: <?php $time = new DateTime(); $time->format('YmdHis'); $upload_dir = "uploads/";// . $time; if (isset($_FILES["myfile"])) { if ($_FILES["myfile"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_dir . $_FILES["myfile"]["name"]); echo "Uploaded File: " . $_FILES["myfile"]["name"]; } } ?> A: Try this Working Code <?php $time = new DateTime(); $time->format('YmdHis'); //$upload_dir = "uploads/";// . $time; $folder_name=date('mds'); $new_folder=mkdir($folder_name, 0777, true); if(file_exists($new_folder)){ echo "Folder already exist"; } $upload_dir = $folder_name.'/'; if (isset($_FILES["myfile"])) { if ($_FILES["myfile"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { if(move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_dir. $_FILES["myfile"]["name"])){ echo "Uploaded File: " . $_FILES["myfile"]["name"]; } else { echo $new_folder .'/'. $_FILES["myfile"]["name"]; echo "Folder created file not uploaded"; } } } ?>
    { "pile_set_name": "StackExchange" }
    Q: How to implement like-HtmlHelper HtmlHelpers are really useful, also i was using AjaxHelpers untill i wanted to do something they can't... so now i'm prefering jquery+javascript, but i don't like to write in javascript (mayby because i never know it as good as i wanted) and to make life easier i wanted to implement something like JQueryHelper, but right now i don't know how I wanted to use inside of "Helper" resolved URL's, because most methods would just pass data to controllers etc... and update some parts of UI, so i'd like to create something like AjaxHelper, but based on JQuery, not MSScripts. What should I include in such class? how can i get context, url's and generate proper javascript code which can by dynamicly injected into ex. <div onclick=JQuery.Action("<ActionName>", "<Controller>", new { param1, param2}, <Id to Update>)> My Div</div> How is it implemented in HtmlHelper or AjaxHelper? Edit: I've tried few simple implementation, but i think I'm lack of knowledge and don't know how to implement class with extensions exacly. I've ClassA(class) and ClassAExt(extensions): I've something like that: static public class ClassAExt{ public static MvcHtmlString Method(this ClassA classA) { } } But in View(), when I'm using ClassAExt.Method() i have to pass also instance of ClassA (in helpers Ajax and Html this argument is grey (optional? not needed?), how to get such effect). A: I am not sure if I understand your question correctly. The HtmlHelper also get instantiated (i.e. new HtmlHelper()) during the course of page rendering and user control rendering. Ajax and URL helpers also get instantiated and this is what give one access to the various variables such HttpContext etc. So in order for you to use your helper class related to ClassA you too will need to instantiate it. I think then the question leads to how do I do this? You will probably need to extend the ViewPage, ViewUserControl and ViewMasterPage classes.
    { "pile_set_name": "StackExchange" }
    Q: Puppet does not honor 'require' modules I have created a module to add a user as follows: user { 'test': ensure => 'present', comment => 'Test User', home => '/home/test', shell => '/bin/bash', managehome => 'true', gid => 'postgres', groups => 'users', password => '$1$PIp.c9J6$gdAyd76OhBk7n9asda80wm0', require => [ Package['rubygem-ruby-shadow'], Class['postgres'] ], } It requires the class postgres as I need its primary group to be assigned to postgres, and the rubygem-ruby-shadow dependency is for the password setup. My problem is puppet does not honor these requirements. Puppet will always execute the useradd module first before rubygem-ruby-shadow, and this causes the password setup to fail. I have also tried to include rubygem-ruby-shadow in the same class as useradd but to no avail. The output upon running puppet agent -t: linux-z14x:~ # puppet agent -t info: Caching catalog for linux-z14x.playground.local info: /User[test]: Provider useradd does not support features manages_passwords; not managing attribute password info: Applying configuration version '1425978163' notice: /Stage[main]/Users/Package[rubygem-ruby-shadow]/ensure: created notice: /User[test]/ensure: created notice: Finished catalog run in 78.19 seconds Running it the second time: linux-z14x:~ # puppet agent -t info: Caching catalog for linux-z14x.playground.local info: Applying configuration version '1425978163' notice: /Stage[main]/Users/User[test]/password: changed password notice: Finished catalog run in 74.79 seconds My rubygem-ruby-shadow class: package { 'rubygem-ruby-shadow': ensure => 'installed', require => Class['myrepo'], provider => 'zypper', } How do I get rubygem-ruby-shadow module to run first before the useradd? Puppet master version is 3.7.4-1 (on CentOS) and puppet client is 2.6.12-0.10.1 (on SLES 11 SP2). Thanks. A: This is unfortunate. The provider detects the absence of ruby-shadow during agent initialization, and does not update its capabilities during the transaction. This may be limitation of Puppet that might be fixed in a more recent version (what are you using?) I do try and make sure to provide ruby-shadow along with Puppet itself everywhere, to avoid this very issue.
    { "pile_set_name": "StackExchange" }
    Q: PHP variable changes itself although not passed by reference In the following code, I am having trouble understanding why the variable $service_category_tree changes by itself. Somehow, the subscription_tree alter's the parameter variable although it is not passed by reference. $service_category_tree = $this->service_category_model->with_request_forms(); foreach ($this->view_data['users'] as &$user) { echo md5(serialize($service_category_tree))."<br>"; // To check if the variable is changed. $user->service_categories = $this->merchant_model->subscription_tree($user->id, $service_category_tree); } The output of the MD5 statement, as you can see shows that the variable is changed: 10066a31bb6e191fbb94b8dc61fd6e55 10066a31bb6e191fbb94b8dc61fd6e55 fd1e22aa74c048e88751c85528d23254 752e0cef4357d7a33e47b90ef207d396 8b5b6ea856080bf32b9bfecc4e43a3f6 8b5b6ea856080bf32b9bfecc4e43a3f6 8b5b6ea856080bf32b9bfecc4e43a3f6 3f3e7619e59e3776c395065e4278c3f8 3f3e7619e59e3776c395065e4278c3f8 dbfebae62d65bd04ce4ce74f2046f90e 34498709256b34ce4d843c1f735c4c6a The method subscription_tree does not have an ampersand on the second parameter as seen in the following code. function subscription_tree($merchant_id, $tree_array = NULL){ if($tree_array === NULL){ $this->load->model('service_category_model'); $tree_array = $this->service_category_model->with_request_forms(); } if(is_array($tree_array) && count($tree_array)){ $my_request_forms = $this->request_forms($merchant_id)->result(); $my_service_categories = $this->service_categories($merchant_id)->result(); foreach ($tree_array as &$sc) { // Indicate subscribed service categories $sc->subscribed = FALSE; if(is_array($my_service_categories) && count($my_service_categories)) { foreach ($my_service_categories as $my_sc_key => $my_sc) { if($my_sc->id == $sc->id){ $sc->subscribed = TRUE; unset($my_service_categories[$my_sc_key]); } } } // Indicate subscribed request forms if(is_array($sc->request_forms) && count($sc->request_forms)) { foreach ($sc->request_forms as &$rf) { $rf->subscribed = FALSE; if(count($my_request_forms)) { foreach($my_request_forms as $mrf_key => $my_request_form){ if ( $my_request_form->id == $rf->id ) { $rf->subscribed = TRUE; unset($my_request_forms[$mrf_key]); break; } } } } } } } return $tree_array; } A: In PHP objects are always passed by reference: Thus lines foreach ($tree_array as &$sc) { // Indicate subscribed service categories $sc->subscribed = FALSE; could change the $tree_array object, which is a reference to $service_category_tree You could also make a deep-copy of your array: $new_tree = array(); foreach ($service_category_tree as $k => $v) { $new_tree[$k] = clone $v; } and pass it to the function. Or make a deep-copy in the function... More info at http://php.net/manual/en/language.oop5.references.php
    { "pile_set_name": "StackExchange" }
    Q: Comparing two fields using LINQ I'm facing a weird problem. As shown in the image actually I selected record number 37 but lightswitch is highlighting as record number 1. 1) The FristName,LastName & HospitalName are unique indexes in the table Doctors since each doctor can have multiple addresses. 2) I'm validating this drop down field as below to avoid user from selecting doctors who are not part of the hospital patient belongs to. partial void DoctorsMasterItem_Validate(EntityValidationResultsBuilder results) { if (this.DoctorsMasterItem != null) { if (this.HospitalName != this.DoctorsMasterItem.HospitalName) { results.AddPropertyError("Make Sure the Hospital Patient belongs to and Doctor is also part of that hospital else your letters address would be wrong"); } } } The data model is A: A better approach would be to filter the dropdown box, so the user isn't presented with invalid choices. Have a look at these two articles. This is what I believe you should be doing, nested (or cascading) comboboxes: Nested AutoCompleteBox For Data Entry Nested AutoCompleteBox for data entry Part 2
    { "pile_set_name": "StackExchange" }
    Q: The filter does not return anything even after match in Javascript so I am trying use this Filter in one of my functions but the filter return empty array even though there are few matches . code filteredCardList: function () { if (this.monthFilter.length > 0) { return this.cardList.filter((card) => { this.monthFilter.forEach(function (val) { if (val.toString() == card.months) { console.log('Matched') return true; } else { console.log('NoMatch') return false; } }); }) } else { return this.cardList } } Any ideas , most welcome thanks A: Ok, assuming monthFilter is an array and you want to filter cardList by the values inside using an any sort of match, try using Array.prototype.some filteredCardList: function () { if (this.monthFilter.length > 0) { return this.cardList.filter(card => { return this.monthFilter.some(val => { return val.toString() == card.months }) }) } else { return this.cardList } } Your problem was that your return true / return false was simply returning from the forEach callback and nothing was returned in the filter callback.
    { "pile_set_name": "StackExchange" }
    Q: ActionMailer observers not working with delayed_job I have an ActionMailer observer that's working just fine during normal sends, but when I send the delivery to delayed_job, it doesn't get called at all. Is this a function of delayed_job itself, or something specific with my observer? Controller: BulkMailer.delay.blast(recipients, email, template) Initializer: ActionMailer::Base.register_observer(MailObserver) Observer class MailObserver def self.delivered_email(message) Rails.logger.debug 'Message: finished' end end A: The code itself was fine, Delayed Job and ActionMailer observers are compatible. My problem was solved by restarting the workers.
    { "pile_set_name": "StackExchange" }
    Q: What kind of indexing are used in MyISAM and InnobDB engines? I read that InnobDB uses B+ Tree and Clustered indexing on Primary Key and Hash(H) Tree and Non Clustered indexing on multiple keys (unique key). But I did not get any explanation for MyISAM.. And what I read for InnobDB is correct ? A: Yes you are correct regarding the InnoDB. For MyISAM see below B-tree indexes Yes T-tree indexes No Hash indexes No Read Here more
    { "pile_set_name": "StackExchange" }
    Q: Avoid DD anomalies I have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece. The case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don't like several returns on a method. public String getBingLocation(Coordinate... data) { String response = "Not Retrieved"; final Coordinate location = data[0]; JSONObject locationData; try { locationData = NetworkManager.getJSONResult(ApiFormatter .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude)); if (null != locationData) { final String address = this.getAddressFromJSONObject(locationData); response = address; } } catch (final ClientProtocolException e) { LoggerFactory.consoleLogger().printStackTrace(e); return response; } catch (final JSONException e) { LoggerFactory.consoleLogger().printStackTrace(e); return response; } catch (final IOException e) { LoggerFactory.consoleLogger().printStackTrace(e); return response; } finally { location.Street = response; } return response; } Other example: public static Object loadObject(final String fileName, final Context context) { Object object = null; try { ObjectInputStream objectInputStream = null; try { final FileInputStream fileStream = context.openFileInput(fileName); objectInputStream = new ObjectInputStream(fileStream); object = objectInputStream.readObject(); } catch (final ClassNotFoundException catchException) { LoggerFactory.consoleLogger().printStackTrace(catchException); } catch (final ClassCastException catchException) { LoggerFactory.consoleLogger().printStackTrace(catchException); } catch (final Exception catchException) { LoggerFactory.consoleLogger().printStackTrace(catchException); } finally { if (objectInputStream != null) { objectInputStream.close(); } } } catch (final IOException catchException) { LoggerFactory.consoleLogger().printStackTrace(catchException); } return object; } A: Part of the problem is your functions have more than one responsibility. They are both getting a result and handling errors. You're also getting unnecessarily hung up trying to avoid multiple return points, which is a vestigial practice from C programming where it can cause memory leaks. You should use multiple returns if it clarifies your code, especially in short functions. I'm also guessing that your logging code is getting repeated all over the place. If you separate those concerns and try to avoid repeating yourself, you get something like this: public JSONObject getLoggedJSONResult(String api) { try { return NetworkManager.getJSONResult(api); } catch (final ClientProtocolException e) { LoggerFactory.consoleLogger().printStackTrace(e); } catch (final JSONException e) { LoggerFactory.consoleLogger().printStackTrace(e); } catch (final IOException e) { LoggerFactory.consoleLogger().printStackTrace(e); } return null; } public String getBingLocation(Coordinate... data) { final Coordinate location = data[0]; JSONObject locationData = getLoggedJSONResult( ApiFormatter.generateBingMapsReverseGeocodingURL( location.Latitude, location.Longitude)); if (null == locationData) { return "Not Retrieved"; } else { return this.getAddressFromJSONObject(locationData); } } As a general principle, most DD anomalies can be fixed by splitting the function. It's mostly a matter of figuring out where to split it. Your second example is trickier. That sort of situation is why try-with-resources statements were invented. You can use an early return to eliminate the DD anomaly on object, but you're not going to be able to do much about objectInputStream without a try-with-resources.
    { "pile_set_name": "StackExchange" }
    Q: Webview app code security I have an app which runs mostly in webview and opens an html file from my server and most of the logic happens in its javascript files. If you open the html file on your browser you will have all the code with a simple inspect element. I wanted to ask how can I secure my application and prevent my code from being seen and copied. Thanks A: By default WebView doesn't allow debugging of its contents (unlike Chrome), unless it runs on a debug build of Android. Thus if you don't reveal the URL anywhere, users will simply not know what to open in a browser. You can also minify/obfuscate your JavaScript code to make it barely readable, even if anyone somehow opens it. This also has a benefit of reducing download size. A radical approach would be to generate all the results on the server and send them to clients. This way, your clients will not have any code at all on them. But this will greatly complicate any attempts to make the results interactive.
    { "pile_set_name": "StackExchange" }
    Q: LWJGL 3 Shaders version 150 and above rendering nothing I'm using LWJGL 3 on OSX. The shaders work fine when using a version <150 but porting the code to 330 nothing renders. My shaders are as simple as possible: vertex shader: #version 330 core in vec3 position; void main(void) { gl_Position = vec4(position, 1.0); } fragment shader: #version 330 core out vec4 outColour; void main(void) { outColour = vec4(1.0, 0.0, 0.0, 1.0); } I create a simple triangle like this (Scala): val vertices = Array( 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f ) val vertexBuffer = BufferUtils.createFloatBuffer(vertices.length) vertexBuffer.put(vertices) vertexBuffer.flip() val buffer = GL15.glGenBuffers() GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer) GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBuffer, GL15.GL_STATIC_DRAW) and I draw it like this: GL20.glUseProgram(shader) GL20.glEnableVertexAttribArray(0) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer) GL20.glBindAttribLocation(shader, 0, "position") GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0) GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 9) GL20.glDisableVertexAttribArray(0) GL20.glUseProgram(0) The shaders compile fine and the program runs but I just get a blank screen! Is there anything obviously wrong with my code? A: Vertex Array Objects (VAOs) are required for rendering in a Core context. In Compatibility contexts they're optional. However, you can just generate one at startup and leave it bound if you're feeling lazy :)
    { "pile_set_name": "StackExchange" }
    Q: Significance of Proton Tunneling It has been repeatedly emphasized that proton transfers "involving" three or four membered ring transition states are not favorable and should not be drawn as the primary mechanism for any reaction. However, with regard to a recent discussion involving $\ce{H3CSH}$ it was noted that the rate of proton tunneling in the anionic form $\ce{H3CS-}$ was likely extremely high. Carbon-Sulfur Bond Lengths; Resonance Effects (Or Lack Thereof) So: a) Is this a valid rule of thumb: avoid intramolecular proton transfers unless the transition state has 5 or 6 members in its ring? b) What's more significant with regard to proton transfer - proton tunneling or physical proton transfer? Or is the answer an "it depends"? A: a) Is this a valid rule of thumb: avoid intramolecular proton transfers unless the transition state has 5 or 6 members in its ring? Yes b) What's more significant with regard to proton transfer - proton tunneling or physical proton transfer? Or is the answer an "it depends"? It depends, at temperatures around absolute zero, tunneling can become significant. At ambient temperatures or above, physical proton transfer is much more common. As to the methyl mercaptan anionic example you cite, to the extent that the various carbon-sulfur double bond resonance structures contribute, I would expect a lowering of the barrier around carbon anion planarization - and consequently a lowering of the barrier to inversion at the carbon atom in the anion. Therefore, it is not clear to me that tunneling of the sulfur bound proton would be preferred to carbon inversion in order to bring about the syn-anti interconversion, especially since any presumed experiments to generate the anion would not be performed near absolute zero.
    { "pile_set_name": "StackExchange" }
    Q: Uniformization of Kodaira fibered surfaces Consider a Kodaira fibration. i.e. a smooth non-isotrivial fibration $X\rightarrow C$ with $X$ a smooth complex surface and $C$ a smooth complex curve, such that both the genus of $C$ and genus of the fibers (which are complex curves) are at least $2$. By abuse of notation I call $X$ a Kodaira fibered surface. What is known about the structure of the universal cover of $X$? In particular, when is it a bounded symmetric domain? I know that $X$ is a minimal algebraic surface of general type and that the universal cover of $X$ can never be a ball in $\mathbb{C}^{2}$. A: Here are the arguments to exclude polydisk and the ball (there are no other complex 2-dimensional bounded symmetric domains: In fact, one can do without this and argue that any domain other than the ball would have rank $\ge 2$ and, hence, Margulis superrigidity theorem would apply). Kefeng Liu ("Geometric height inequalities", Math. Research Letters, 3 (1996), 693–702) proved that a compact complex-hyperbolic surface cannot admit a holomorphic submersion to a Riemann surface. This excludes the complex ball. Consider the 2-dimensional polydisk $D^2$ and a group $\Gamma$ acting discretely, holomorphically and cocompactly on $D^2$. Then $\Gamma$ is a lattice in $Isom(D^2)$ and by Margulis' superrigidity theorem either $\Gamma$ is reducible or it is superrigid, and , ehnce, does not admit an epimorphism to a surface group. The second is impossible in the case of fibrations over Riemann surfaces, the first contradicts non-isotriviality assumption in the question. On the other hand, the universal cover of your complex manifold $X$ is a certain bounded domain in ${\mathbb C}^2$: This result could be found in P.A. Griffiths, Complex-analytic properties of certain Zariski open sets on algebraic varieties. Ann. of Math. (2) 94 (1971), 21–51. who proves it using Bers' simultaneous uniformization. A: If an algebraic surface has the bidisk as universal cover, then, by Hirzebruch's proportionality theorem, its topological index is 0 (the index is 1/3 (c_1^2 - 2 c_2)). But Kodaira proved that for Kodaira fibrations the index is strictly positive. To exclude the case that the universal covering is the ball, where c_1^2 = 3 c_2, again by Hirzebruch's theorem, is harder and was done by Kefeng Liu. You may look in my article with Rollenske for more results on Kodaira fibrations. Regards, Fabrizio Catanese.
    { "pile_set_name": "StackExchange" }
    Q: Having an issue with callback function So I have some code like this const getAPIData = (symbol, callback) => { var options = { url: "https://api.binance.com/api/v3/ticker/price", method: "GET", qs: { symbol }, }; request(options, (err, res, body) => { body = JSON.parse(body); callback(body); }); }; var isValid = 0; getAPIData(symbol, (body) => { console.log(body); if (body.symbol) { console.log("yes"); isValid = 1; } else { console.log("no"); } }); After this callback is executed the "isValid" variable still remains 0 no matter what the outcome is. Although the console gets logged with yes and no both. The isValid variable still remains 0 when I debug the program. How can the console.log function work and not set the isValid to 1? it's like it's just skipping that line or I'm not sure. Please help me out! A: This is the way asynchronous calls work. var isValid = 0; getAPIData(symbol, (body) => { console.log(body); if (body.symbol) { console.log("yes"); isValid = 1; console.log(isValid); // 1 } else { console.log("no"); } }); console.log(isValid); // 0 // when the JS engine gets here, isValid will still be 0 // since getAPIData is asynchronous and it's still in progress at this point // also, you cannot use any results of getAPIData here
    { "pile_set_name": "StackExchange" }
    Q: XmlAttribute value and innertext I have a piece of code that fills a hashtable with strings, per example: ("name", Oscar). I want to use them to fill (just by memory usage) values and innertexts of XMLAtributes. But there is one problem. XmlElement Co = newDoc.CreateElement("Co1"); XmlAttribute series = Co.Attributes.Append(newDoc.CreateAttribute("series")); series.InnerText = (string)vector["series"]; series.Value = (string)vector["series"]; MessageBox.Show((string)vector["series"]); MessageBox.Show(Co.Attributes["series"].InnerText.ToString()); MessageBox.Show(Co.Attributes["series"].Value.ToString()); When ever I want the system to show me the value or the innertext (within the xml create method this piece of code is in) it has it returns nothing. Then It passes to the next atribute and returns a "Object reference not set to an instance of an object.". The next piece of code is this one: XmlAttribute folio = Co.Attributes.Append(newDoc.CreateAttribute("folio")); folio.InnerText = vector["folio"].ToString(); The error hits in the last line. In any other place of the class I can see and retrieve the values of the hastable by the .ToString() method and the cast. It seems that Im not properly getting the value out of my hashtable or there is something I am missing with the XMLAtributes... ¿What is the proper way to do so? A: You are doing this the hard way: var folio = Convert.ToString(vector["folio"]); Co.SetAttribute("folio", folio); There is no need to worry about things like InnerText.
    { "pile_set_name": "StackExchange" }
    Q: Integrating Factor - Not getting the answer given? $y' - 4y = t$ My integrating factor is $e^{-4t}$ $\int e^{-4t}y'$ - $\int 4e^{-4t}y$ = $\int te^{-4t}$ $\int (e^{-4t}y)'$ = $\int te^{-4t}$ $e^{-4t}y$ = $-4te^{-4t}$ - $e^{-4t}$ I end up with $y' = -4t -1 + ce^{4t}$ Where did I go wrong? A: You integrated $\int te^{-4t}\mathrm dt$ incorrectly. It should be $$\int te^{-4t}\mathrm dt=-\dfrac{t}{4}e^{-4t}-\dfrac{1}{16}e^{-4t}+c$$ Then multiplying both sides by $e^{4t}$ gives you $$y=-\dfrac{t}{4}-\dfrac{1}{16}+ce^{4t}$$ A: Let $u=t$, $du=dt$, $dv=e^{-4t}$, and $v=-\cfrac{1}{4}e^{-4t}$, then using integration by parts, $\displaystyle\int te^{-4t}\, dt$ should be \begin{align} \int te^{-4t}\, dt&=-\cfrac{t}{4}e^{-4t}+\cfrac{1}{4}\int e^{-4t}\,dt\\ &=-\cfrac{t}{4}e^{-4t}+\cfrac{1}{4}\left(-\cfrac{1}{4}e^{-4t}\right)+C\\ &=-\cfrac{t}{4}e^{-4t}-\cfrac{1}{16}e^{-4t}+C\\ \end{align}
    { "pile_set_name": "StackExchange" }
    Q: Volumetric rendering fundamental concepts and terminology Literature on rendering volumetric materials and effects tends to use a lot of mathematical physics terminology. Let's say that I have a decent handle on the concepts involved in surface rendering. What concepts do I need to understand for volumetric rendering? (Both real-time and offline rendering.) What exactly is meant by light scattering in the context of volumetric rendering? (And why is it split into in-scattering and out-scattering?) What is the relationship between transmission, attenuation, and absorption? What is a phase function and how does it play into volumetric rendering? (In particular, the Henyey-Greenstein phase function.) What is the Beer-Lambert law and how is it related to light scattering? Basically, how do I make sense out of diagrams like this? A: When I was first reading about all of this I stumbled upon this link which helped me better understand this large subject. Also this goes into some more detail on things mentioned here. Light scattering is a natural phenomenon which arises when light interacts with particles distributed in a media as it travels through it. From Wikipedia: Light scattering can be thought of as the deflection of a ray from a straight path, for example by irregularities in the propagation medium, particles, or in the interface between two media In computer graphics there are models that have been developed to simulate the effect of light traversing volume objects from an entry point (Point A) to an exit point (Point B). As the light travels from A to B it is changed due to interactions with particles and these interactions are often referred to as Absorption, Out Scattering and In Scattering. Often you will see these split into two groups; Transmittance (Absorption and Out Scattering) which I like to think of as 'light lost' and In-Scattering ('light gained'). Absorption is basically incident light energy that is transformed into some other form of energy and therefore 'lost'. Transmittance Transmittance describes how light reflected behind a volume will be attenuated due to Absorption as it travels through a medium from A to B. This is usually calculated with the Beer-Lambert law which relates the attenuation of light to the properties of the material through which it is travelling. As the light travels through the medium there is a chance that the photons can be scattered away from their incident direction and therefore not make it to the eye of the observer and this is referred to as Out-Scattering. In most models the Transmittance equation is changed slightly to introduce the concept of Out-Scattering. In Scattering Above we have seen how light can be lost due to photons been scattered away from the viewing direction. At the same time light can be scattered back into the viewing direction as it is travelling from A to B and this is called In-Scattering. Particle In-Scattering itself is a pretty complex topic but basically you can split it into Isotropic and Anisotropic scattering. Modelling Anisotropic scattering would take a considerable amount of time so usually in computer graphics this is simplified by using a Phase Function which describes the amount of light from the incident light direction that is scattered into the viewing direction as it travels from A to B. One commonly used non-isotropic Phase Function is called the Henyey-Greenstein phase function which can model Backward and Forward scattering. It usually has a single parameter, g ∈ [−1,1], that determines the relative strength of forward and backward scattering.
    { "pile_set_name": "StackExchange" }
    Q: ConcurrentDictionary Introduction I'm building an API wrapper for the SE API 2.0 Currently, I'm implementing a cache feature, this wasn't an issue until now. Now I'm taking concurrency into account. This would be my test method: Code public static void TestConcurrency() { Stopwatch sw = new Stopwatch(); sw.Start(); IList<Task> tasks = new List<Task>(); for (int i = 0; i < 1000; i++) { tasks.Add(Task.Factory.StartNew(p => client.GetAnswers(), null)); } Task.WaitAll(tasks.ToArray()); sw.Stop(); Console.WriteLine("elapsed: {0}", sw.Elapsed.ToString()); Console.ReadKey(); } Description Internally, the client has a RequestHandler class, which attempts to fetch a value from the cache, and if it fails to do so, it performs the actual request. Code /// <summary> /// Checks the cache and then performs the actual request, if required. /// </summary> /// <typeparam name="T">The strong type of the expected API result against which to deserialize JSON.</typeparam> /// <param name="endpoint">The API endpoint to query.</param> /// <returns>The API response object.</returns> private IApiResponse<T> InternalProcessing<T>(string endpoint) where T : class { IApiResponse<T> result = FetchFromCache<T>(endpoint); return result ?? PerformRequest<T>(endpoint); } Description The code that actually performs the request is irrelevant to this issue. The code that attempts to access the cache does the following: Code /// <summary> /// Attempts to fetch the response object from the cache instead of directly from the API. /// </summary> /// <typeparam name="T">The strong type of the expected API result against which to deserialize JSON.</typeparam> /// <param name="endpoint">The API endpoint to query.</param> /// <returns>The API response object.</returns> private IApiResponse<T> FetchFromCache<T>(string endpoint) where T : class { IApiResponseCacheItem<T> cacheItem = Store.Get<T>(endpoint); if (cacheItem != null) { IApiResponse<T> result = cacheItem.Response; result.Source = ResultSourceEnum.Cache; return result; } return null; } Description The actual implementation of the cache store works on a ConcurrentDictionary, when the Get<T>() method is invoked, I: Check whether the dictionary has an entry for endpoint. If it does, I verify whether or not it holds a response object. If it doesn't already have a response object, the cache item's state will be Processing, and the thread will be put to sleep for a small amount of time, waiting on the actual request being completed. Once or if the response is "commited" to the cache store (this happens once the request is completed), the cache item is returned. If the cache item was too old or the request processing timed out, the entry is removed from the store. If the cache didn't have an entry for endpoint, null is pushed into the cache as the response for endpoint, signaling a request on that endpoint is being processed and there is no need to issue more requests on the same endpoint. Then null is returned, signaling an actual request should be made. Code /// <summary> /// Attempts to access the internal cache and retrieve a response cache item without querying the API. /// <para>If the endpoint is not present in the cache yet, null is returned, but the endpoint is added to the cache.</para> /// <para>If the endpoint is present, it means the request is being processed. In this case we will wait on the processing to end before returning a result.</para> /// </summary> /// <typeparam name="T">The strong type of the expected API result.</typeparam> /// <param name="endpoint">The API endpoint</param> /// <returns>Returns an API response cache item if successful, null otherwise.</returns> public IApiResponseCacheItem<T> Get<T>(string endpoint) where T : class { IApiResponseCacheItem cacheItem; if (Cache.TryGetValue(endpoint, out cacheItem)) { while (cacheItem.IsFresh && cacheItem.State == CacheItemStateEnum.Processing) { Thread.Sleep(10); } if (cacheItem.IsFresh && cacheItem.State == CacheItemStateEnum.Cached) { return (IApiResponseCacheItem<T>)cacheItem; } IApiResponseCacheItem value; Cache.TryRemove(endpoint, out value); } Push<T>(endpoint, null); return null; } The issue is indeterminately, sometimes two requests make it through, instead of just one like it is designed to happen. I'm thinking somewhere along the way something that's not thread safe is being accessed. But I can't identify what that might be. What could it be, or how should I debug this properly? Update The issue was I wasn't always being thread safe on the ConcurrentDictionary This method wasn't retuning a boolean indicating whether the cache was successfully updated, therefore if this method failed, null would have been returned twice by Get<T>(). Code /// <summary> /// Attempts to push API responses into the cache store. /// </summary> /// <typeparam name="T">The strong type of the expected API result.</typeparam> /// <param name="endpoint">The queried API endpoint.</param> /// <param name="response">The API response.</param> /// <returns>True if the operation was successful, false otherwise.</returns> public bool Push<T>(string endpoint, IApiResponse<T> response) where T : class { if (endpoint.NullOrEmpty()) { return false; } IApiResponseCacheItem item; if (Cache.TryGetValue(endpoint, out item)) { ((IApiResponseCacheItem<T>)item).UpdateResponse(response); return true; } else { item = new ApiResponseCacheItem<T>(response); return Cache.TryAdd(endpoint, item); } } Description The solution was to implement the return value, and changing Get<T>() adding this: Code if (Push<T>(endpoint, null) || retries > 1) // max retries for sanity. { return null; } else { return Get<T>(endpoint, ++retries); // retry push. } A: IApiResponseCacheItem<T> cacheItem = Store.Get<T>(endpoint); if (cacheItem != null) { // etc.. } A ConcurrentDirectionary is thread-safe but that doesn't automatically make your code thread safe. The above snippet is the core of the problem. Two threads could call the Get() method at the same time and get a null. They'll both continue on and call PerformRequest() concurrently. You'll need to merge the InternalProcessing() and FetchFromCache() and ensure that only one thread can call PerformRequest by using a lock. That might produce poor concurrency, perhaps you could just drop a duplicate response. In all likelihood, the requests get serialized by the SE server anyway so it probably doesn't matter.
    { "pile_set_name": "StackExchange" }
    Q: Can I untangle this nesting of 'when' promise invocations? I'm new to the when.js javascript library, but I'm familiar with async programming in C#. That's why I find this code to be unwieldy: filters.doFilter('filter1name', reqAndPosts).then(function(filter1) { filters.doFilter('filter2name', filter1).then(function(filter2) { filters.doFilter('filter3name', filter2).then(function (posts) { renderView(posts); }); }); return filter1; }); I basically want three methods to be called in sequence, with the output of each being piped to the next method. Is there anyway I can refactor this code to be more "sequence-like" - i.e. get rid of the nesting? I feel like there's something I'm missing with the when-framework here. I'm not doing it right, right? A: Since doFilter returns a promise, we can do filters.doFilter('filter1name', reqAndPosts) .then(function(filter1) { return filters.doFilter('filter2name', filter1); }) .then(function(filter2) { return filters.doFilter('filter3name', filter2); }) .then(renderView); A: There is another option to have both advantages of cleaner indentation and previous results available: using withThis. filters.doFilter('filter1name', reqAndPosts).withThis({}).then(function(filter1) { this.filter1 = filter1; // since we used withThis, you use `this` to store values return filters.doFilter('filter2name', filter1); }).then(function(filter2) { // use "this.filter1" if you want return filters.doFilter('filter3name', filter2); }).then(renderView);
    { "pile_set_name": "StackExchange" }
    Q: Deadlock occurs in broker database while publishing I am getting deadlock in my broker database(Oracle based) while publishing lot of components/pages in my production environment. The deadlocks occurs in the following statement: update TAXFACETS set FACET_ISABSTRACT=:1 , FACET_DEPTH=:2 , FACET_HASCHILDREN=:3 , FACET_ID=:4 , FACET_ITEMTYPE=:5 , FACET_KEY=:6 , FACET_LEFT=:7 , FACET_ISNAVIGABLE=:8 , FACET_PARENT=:9 , PUBLICATION_ID=:10 , FACET_RIGHT=:11 , TAXONOMY_ID=:12 , TOTAL_RELATEDITEMS=:13 , FACET_DESCRIPTION=:14 , FACET_NAME=:15 , FACET_ISUSEDFORIDENTIFICATION=:16 where NODE_ID=:17 I can see below message in my deployer cd_core log: 2015-05-21 11:21:33,491 DEBUG SearchIndexerDeployModule - Processing F:\tridion\deployer\incoming_staging\Zip\tcm_0-125870-66560.Content\components.xml file 2015-05-21 11:21:33,491 DEBUG JPAComponentPresentationDAO - Removing component presentation from storage. 2015-05-21 11:21:33,491 DEBUG PreCommitPhase - Executing worker: com.tridion.storage.deploy.workers.ComponentPresentationWorker@1262fa8 on transaction: tcm:0-125868-66560 took: 0 2015-05-21 11:21:33,491 DEBUG PreCommitPhase - Executing worker com.tridion.storage.deploy.workers.ComponentPresentationMetaWorker@7362351f on transaction: tcm:0-125868-66560 this is worker 20 of: 22 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / ItemMeta / null 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / ComponentPresentationMeta / null 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Loading a cached DAO for publicationId/typeMapping/itemExtension: 34 / DynamicLinkInfo / null 2015-05-21 11:21:33,491 INFO StorageManagerFactory - While loading caching DAO, no configuration found, returning uncached. 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Storing non cached DAO into caching map as there is no configuration present for the cached version of the DAO 2015-05-21 11:21:33,491 DEBUG StorageManagerFactory - Wrapping DAO's, currently 0 wrappers installed 2015-05-21 11:21:33,491 DEBUG JPADynamicLinkDAO - Removing dynamic links with source TCMURI tcm:34-36190-48 2015-05-21 11:21:33,491 DEBUG CacheChannel - Received event from another VM [CacheEvent eventType=Invalidate regionPath=/com.tridion.storage.ReferenceEntry key=34:tcd:pub[34]/componentmeta[36156]:tcd:pub[34]/pagemeta[36157]] 2015-05-21 11:21:33,491 ERROR DeployPipelineExecutor - Unable to start processing deployment package with transactionId: tcm:0-125866-66560 com.tridion.deployer.ProcessingException: Phase: Deployment Commit Phase failed. Commit failed for transaction: tcm:0-125866-66560 at com.tridion.deployer.phases.DeployPipelineExecutor.runMainExecutePhase(DeployPipelineExecutor.java:209) [cd_deployer-2013SP1.jar:na] at com.tridion.deployer.phases.DeployPipelineExecutor.doExecute(DeployPipelineExecutor.java:100) [cd_deployer-2013SP1.jar:na] at com.tridion.deployer.phases.DeployPipelineExecutor.execute(DeployPipelineExecutor.java:64) [cd_deployer-2013SP1.jar:na] at com.tridion.deployer.TransactionManager.handleDeployPackage(TransactionManager.java:82) [cd_deployer-2013SP1.jar:na] at com.tridion.deployer.queue.QueueLocationHandler$1.run(QueueLocationHandler.java:180) [cd_deployer-2013SP1.jar:na] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_55] at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_55] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_55] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_55] at java.lang.Thread.run(Thread.java:745) [na:1.7.0_55] Caused by: com.tridion.deployer.ProcessingException: Unable to commit transactions at com.tridion.deployer.phases.AbstractStorageStep.commitTransaction(AbstractStorageStep.java:34) ~[cd_deployer-2013SP1.jar:na] at com.tridion.deployer.phases.CommitPhase.execute(CommitPhase.java:77) ~[cd_deployer-2013SP1.jar:na] at com.tridion.deployer.phases.DeployPipelineExecutor.runMainExecutePhase(DeployPipelineExecutor.java:198) [cd_deployer-2013SP1.jar:na] ... 9 common frames omitted Caused by: com.tridion.broker.StorageException: Commit failed for transaction tcm:0-125866-66560 because of Unexpected error ocurred while committing at com.tridion.storage.StorageManagerFactory.commitTransaction(StorageManagerFactory.java:358) ~[cd_datalayer-2013SP1.jar:na] at com.tridion.deployer.phases.AbstractStorageStep.commitTransaction(AbstractStorageStep.java:32) ~[cd_deployer-2013SP1.jar:na] ... 11 common frames omitted Caused by: com.tridion.broker.StorageException: Unexpected error ocurred while committing at com.tridion.storage.persistence.JPADAOFactory.commitTransaction(JPADAOFactory.java:209) ~[cd_datalayer-2013SP1.jar:na] at com.tridion.storage.StorageManagerFactory.commitTransaction(StorageManagerFactory.java:354) ~[cd_datalayer-2013SP1.jar:na] ... 12 common frames omitted Caused by: javax.persistence.RollbackException: Error while committing the transaction at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final] at com.tridion.storage.persistence.JPADAOFactory.commitTransaction(JPADAOFactory.java:206) ~[cd_datalayer-2013SP1.jar:na] ... 13 common frames omitted Caused by: javax.persistence.PersistenceException: org.hibernate.exception.LockAcquisitionException: could not execute statement at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final] ... 14 common frames omitted Caused by: org.hibernate.exception.LockAcquisitionException: could not execute statement at org.hibernate.dialect.Oracle8iDialect$2.convert(Oracle8iDialect.java:450) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:189) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3236) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3138) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3468) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:393) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:385) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:302) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:349) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1159) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75) ~[hibernate-entitymanager-4.2.10.Final.jar:4.2.10.Final] ... 14 common frames omitted Caused by: java.sql.SQLException: ORA-00060: deadlock detected while waiting for resource at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1044) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1329) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3594) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3675) ~[ojdbc6.jar:11.2.0.3.0] at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354) ~[ojdbc6.jar:11.2.0.3.0] at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:174) ~[weblogic.server.merged.jar:12.1.2.0.0] at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) ~[hibernate-core-4.2.10.Final.jar:4.2.10.Final] ... 29 common frames omitted 2015-05-21 11:21:33,491 DEBUG CacheChannel - Received event from another VM [CacheEvent eventType=Invalidate regionPath=/com.tridion.storage.ReferenceEntry key=34:tcd:pub[34]/componentmeta[36154]:tcd:pub[34]/pagemeta[36157]] 2015-05-21 11:21:33,491 DEBUG JPAComponentPresentationMetaDAO - ComponentPresentationMeta was found for removal As this issue occurs in my production environment, I can't do anything to bottleneck the root cause. This issue is redundant(Even with same data) and I am not able to reproduce the same every time on my development environment with similar data. By looking in the above log I can assume that error occurs because of use of many taxonomies in the metadata schema. If anyone faced similar issue, please share the root cause and respective work around. Thanks in advance.. A: If you are using Tridion 2013 SP1 HR1, there is a hotfix for a problem that looks very similar to this issue. Have you tried this hotfix ? CD_2013.1.1.88660 Deadlock and javax.persistence.OptimisticLockException apparently on metadata leading to a failed transaction The description of the hotfix states: Hotfix Description (SRQ-3065) Deadlock and javax.persistence.OptimisticLockException apparently on metadata leading to a failed transaction" Deadlock and javax.persistence.OptimisticLockException apparently on metadata leading to a failed transaction. There will be a deadlock as such: 2015-03-02 15:02:14,840 DEBUG SqlExceptionHelper - ORA-00060: deadlock detected while waiting for resource [n/a] java.sql.SQLException: ORA-00060: deadlock detected while waiting for resource You can find the hotfix on the sdl tridion world website https://www.sdltridionworld.com/downloads/hotfixes/SDL_Tridion_2013_SP1_HR1/index.aspx
    { "pile_set_name": "StackExchange" }
    Q: Задание по русскому языку Сегодня мне задали вопрос. Выражение A B C D употребляется после слова «самый» и усиливает его. Ещё в русском языке есть неопределённое местоимение A E F B G и составные союзы B... B..., F...F... и A B... F... . Напишите слово E. Честно говоря, я вообще не понял суть задания, что за такие выражения, и что надо вписать вместо точек. Может, кто-нибудь разберется? A: A B C D — что ни на есть (ср.: самый что ни на есть). A E F B G — что бы то ни было; B... B — ни... ни, F... F — то... то, A B... F... — что ни... то (например: что ни встреча, то пьянка). Таким образом, искомое E = бы. Суть задания, очевидно, в простой догадке. Точки остаются на месте, вписываются только буквы. P. S. Вообще, трудно представить, как выполнить остальные задания (их 19; большая часть из них не менее, а иногда более трудна и сложна) за 1 час...
    { "pile_set_name": "StackExchange" }
    Q: Batting averages of the Large Hadron Collider As I understand it, the Large Hadron Collider's function is to throw particles into each other while avoiding hitting the nucleus? If quantum mechanics dictate the position of a particle can only ever be an educated guess how accurate or reliable is the collider's standard results for a successful observation? Does it miss more than it hits? What happens if the nuclei collide, would their impact result in a nasty reaction that would destroy the collider at the least? I can go on, has it ever done so and what was the effect? A: Most of the time, the LHC is focusing opposite traveling bunches of protons, in a vacuum so as to avoid undesired collisions with nuclei, together at the various detector locations. No nucleus is involved unless the LHC is colliding heavy ions in which case, the ion nuclei collide and produce amazing images but no damage to the collider. According to one LHC FAQ: When the bunches cross, there will be only about 20 collisions among 200 billion particles. However, bunches will cross about 30 million times per second, so the LHC will generate up to 600 million collisions per second. A: As I understand it, the Large Hadron Collider's function is to throw particles into each other while avoiding hitting the nucleus? No. In the nuclei are the quarks and trust me, we want to beat the crap out of them (the quarks) with as many direct hits as possible. If quantum mechanics dictate the position of a particle can only ever be an educated guess how accurate or reliable is the collider's standard results for a successful observation? Does it miss more than it hits? As far as the uncertainty principal goes, its doesn't forbid you from creating states that still have very small uncertainty in space and momentum. In the case of the LHC the wavefunction of the protons is still fairly localized to a small peak that they send around the collider, outside of which there is a negligibly small chance of detecting the proton. So just because the proton is quantum mechanical doesn't mean there is an equal chance of detecting it anywhere in Geneva. Furthermore, what little uncertainty in the proton wave-packets there is, it isn't much of an issue as far as I can tell. Most of the time something is making contact when the beams cross. The real question is, how often does something interesting happen? It turns out not often - they don't bother recording something like >%99 of the data simply because nothing interesting happened. That is, an automated quick check of the data is performed to see if something triggered an interesting channel, if it doesn't they dump that data, and if something (possibly) interesting happens they store the data and look at in detail later all together. What happens if the nuclei collide, would their impact result in a nasty reaction that would destroy the collider at the least? The nuclei collide all the time and the collider is still here. More importantly there is much higher energy processes happening all the time in the universe for a long time and we are still here.
    { "pile_set_name": "StackExchange" }
    Q: Unable to decrypt data - openssl_private_decrypt(): key parameter is not a valid private key <?php ini_set('display_errors', 1); $config = array( "config" => "C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf", "private_key_bits" => 2048, "private_key_type" => OPENSSL_KEYTYPE_RSA, ); // Create the private and public key $res = openssl_pkey_new($config); if ($res === false) die('Failed to generate key pair.'."\n"); if (!openssl_pkey_export($res, $privKey, "phrase", $config)) die('Failed to retrieve private key.'."\n"); // Extract the private key from $res to $privKey openssl_pkey_export($res, $privKey, "phrase", $config); echo "<br/>"; echo "Private Key = ".$privKey; echo "<br/>"; // Extract the public key from $res to $pubKey $pubKey = openssl_pkey_get_details($res); $pubKey = $pubKey["key"]; echo "<br/>"; echo "Public Key = ".$pubKey; echo "<br/>"; $data = 'plaintext data goes here'; // Encrypt the data to $encrypted using the public key openssl_public_encrypt($data, $encrypted, $pubKey); echo "<br/>"; echo "Encrypted Data = ".$encrypted; echo "<br/>"; // Decrypt the data using the private key and store the results in $decrypted openssl_private_decrypt($encrypted, $decrypted, $privKey); echo "<br/>"; echo "Decrypted Data = ".$decrypted; echo "<br/>"; ?> LOGS Private Key = -----BEGIN ENCRYPTED PRIVATE KEY----- MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIr2acPfh8YYQCAggA MBQGCCqGSIb3DQMHBAiCvohdiWAZ4QSCBMjKJUXF5ShKfW3TazpKYTxEV8JmGYLf AJWXzxdi0GrDuddz4aW1FeGwvUm2t/41CTxFsWtgoQJrzCgAQETn54majdrDeF4u zCmvFMKSoVP4xsZKke15e1K1LPmFNNuKKyCqMwL+tpQJ7zquvDTKHapUnNzfNXpZ D2K1r2qZWeDN1d36DA9wkN5GbpZYAjuHqHUNzorhxIbHGp2WOg8YKdemoTuKIqYC DUKncWtxRUOx6IIZuey+uTBzH7Bn9K9a71QTjUdeWgQZFzy9yVpetB+XrJA92IWt vMeKXCXNhOgkOvkUPNXSuMOVrECNcbKDAKxmK3EQWqb+8zlYFqjmaL/sCep8ihio 1ZWpRaOd5HxnG5rpmz/BYzcF354mM8B4wAIk7MmFq/pHSKLjpr+2Ef1BpMmXfRpG Pj1jYDClSIQF6ovKOqhevFwfYrtl2jEOISyAggm/sbD750VBkwhbVAyQcarckAiI GlNcQPOC+JYZOV7o/9o+Tg24zwtAQ8y3hNvYyHjqYI5naVS9yuXEqB6zYoGivs/k bIblqTFebLEFtihjsa9wpXkyNzKD2NvdSa2oNC7IkCNi8TRNjy7MLylSmCIdhWAV YgL1hxShMgbnfiGjFQyYnKzZto9RqRlQBIoBOCfwP1EFnZjCJm02CCeGR+GHKXf7 rJ0n6lIUEvVnENirAPtOuiE2ccbzmyjWQ9f2vwBSUea5nPTMG4uTVHrQjrgNYIyU +vLV6tL+MDKF4JGQGgzBUeqTMobmrOK+V20QIasYaAWHJrL8itBwZ++C8lo7kySa SImMXakI4rjgEmj+HmUJygT1EZWz5yQqOiwAYLhQZg+m6+32Pvt6mIrAXbznrdHP JxHb/9HV88mQdRKPBTkSTl71Ics+3oybYPbhSQByXOdtsw6VLYNo4ikgj3tXCz01 DwVQqeQ5tLD4LY8/QaAHkOUq9K24yfkcN+aQh7cvR/HX53Ls6LsdUwkwSOWVj2na Wl4xn+j3ZaPhpgdzcMgknU7BAI2kZP83MxyKnNcnneyX4hTaM5PRZJXKd+onvhff nQ3zHDSYmRDKmTXBjCob3Vjg91LcMjg9dEH7aIFWit5dHK4ll/v1IiOFx8d4d/mV Oll0c0ujJuPjtyqesM2Bz3Ah5YkIT2Z7kxvRy7rTyytQG7hLNENAki9wW79fcEo7 ln/OvEpjdWZngkL/UrMOX8DBrs0PLEH9jyDoCQx/LSqxMAXOwVXILfsfsUFu0M0o 21YbeC33jOlocJ4Q6pwfRVz8lCQOuIVs1jEpvSmvHgvmHmXUI4Y6nZD4Roi0jIjS VvI73eULzc3j0jIptWxzrHWM6iHx1zRxkLMJSZOx0A27ngtSo7g6+aJnMO5FDfdR 90vnr+bX4ki+X/N4wVF7eppyapLe/tQ54vAxsyIBrCXPjwBMehiFjOMhzSLW7xQj Qg2KcilfW6oKFzDQQ5nKPEXvQYMhQ1MeWKyNv6BMoc4EEpIGhtziUXWhgT4sN1ES 5sxVcGVoIe1viO/kk3Zq55hETlZbNWs3V511BcEZCiQNrntnbYv6pwKpoB21ZV2E slVhYcslEGliIQKQsWSl5cfc+pqjLteiPrwk14WKJGXl9zX3YH6H7KKB/7SIRZk7 wq8= -----END ENCRYPTED PRIVATE KEY----- Public Key = -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAriS8qflAjYSYhH2qgC5T yf98X1qoLMXIW9mMkhV8LcApBKOfNjUMc9xjD3a8CR/LYwa4MYhevoKcVfPG8XoE sDGyHh+h/vtYP0rORB1T3RULVUzDLjX558e2KqPrSN+rV+Jl1NB0SO5Of3JA+AKa 0Q3botcjOM3WuFa/s+RzsiCrMMhzOZSTBj+GTP/VcDipF5PM7+/Lxr+edjRXccT2 WQjsq0sUrtsmpzBE8Niph361RjfIisxKoksQGs7hC/Iv4yhBzZZIpRaZuvDj4ImP +4sUQgbdVVCso122kg34UtY5qchuSCcJfsGbD2zMw+8ZftIsJ7dfX1FxujgggDyn 0wIDAQAB -----END PUBLIC KEY----- Encrypted Data = Uš6/ùÅËæÝmL4²G¾'gr¨Ñ­Ä‰ï‚zêbÀ)[îR0s‹yÝ`t™õ°Þe­Ïd>×o¯rß9ÌÔÅAü!-†D·¨ÎVZ¼?¶éžäýöaØT~=‚Fan¢ºq{M”ƒ¹Cû5N3¹.Ð(·#*ÏRƹñß÷õƒ_ò9c-Ÿ% ×óè2Ꙃõ“ÂÐgNÈ-ˆd«…ºt§¼Ô}yŠ"7èPš(¶R¤ßJÚ_h¶ðÞK(Cj“7‘Y ÀŠþrôZƒ4)JU•˜„üˆ k0â§Êë^ÚºGÚªúVKø†ë8ÏLÚó „Ÿ¦¿¤ ( ! ) Warning: openssl_private_decrypt(): key parameter is not a valid private key in C:\wamp\www\android\pki_example.php on line 41 Call Stack # Time Memory Function Location 1 0.0020 252696 {main}( ) ..\pki_example.php:0 2 0.2043 258032 openssl_private_decrypt ( ) ..\pki_example.php:41 Decrypted Data = A: // Decrypt the data using the private key and store the results in $decrypted openssl_private_decrypt($encrypted, $decrypted, openssl_pkey_get_private($privKey, "phrase")); echo "<br/>"; echo "Decrypted Data = ".$decrypted; echo "<br/>"; openssl_private_decrypt function is capable to use PEM formatted private key but your key is encrypted and this function does not have an argument for password. You have to use openssl_pkey_get_private instead.
    { "pile_set_name": "StackExchange" }
    Q: How can I extend the category products Rest API? /V1/categories/(cat ID)/products This API provides very less detail of all the products. { "sku": "Nike 3 color half sleeve tshirt", "position": 1, "category_id": "3" }, { "sku": "Louis Phillipe Blue Jean Size 32", "position": 1, "category_id": "3" }, { "sku": "Louis Phillipe Shirt Size M", "position": 1, "category_id": "3" }, { "sku": "UCB shirt Size ", "position": 1, "category_id": "3" }, I can use the sku in a search filter to get all the produts with these sku's. But is there a better way around ? A: It is possible to use filter by category_id during request to Product Repository: GET <base_url>/rest/V1/products If it is necessary to filter by store_id or website_id at the same time, see workaround here.
    { "pile_set_name": "StackExchange" }
    Q: How to re-initialise (state) array variable in react-native? I'm making an API call. And I'm getting response as : var data = [ {a: 'a', b: 'b'} ] And I want to set value of variable in state as data. But it's not working . Giving error as => Objects are not valid as a React child Ex: - state = { stateVariable: [] } apiCall.then((data) => { this.setState({ stateVariable: data }) }) A: Objects are not valid as a React child In react, you cannot render an object directly. I feel you are trying to do something like this <Text>{this.state.stateVariable}</Text> It will not work because the value in there is an array. To fix this, you can map it: {this.state.stateVariable.map(data => <Text>{data.a} {data.b}</Text>)} Secondly, You may already be mapping it or looping it but you're still getting the error. This is because if you render just data as in my map above, it is an object {a:'a', b:'b'} and this is not allowed in react. So you have to make it {data.a} or {data.b}
    { "pile_set_name": "StackExchange" }
    Q: Object History Related List in Lightning Experience I found that Object History related list isn't supported in Lightning Experience : https://success.salesforce.com/ideaView?id=08730000000LgQWAA0 . I need to show it in Lightning; is there any way to show the Related History on Contact (in lightning) without creating a new object. Thanks! A: I tried to track few standard and custom field on Contact using Field History Tracking. In lightning, it doesn't seem to show the "Contact History" related list and its history records at all even if you add it to the page layout. The only way I could do is to switch to "Classic View" and see the field changes in Contact History related list for the contact record. If you need to see this working in Lightning, We will have to wait till the following idea (https://success.salesforce.com/ideaView?id=08730000000LgQWAA0) gets incorporated by Salesforce. Update: This has been delivered in Summer 17, for those who are still looking.
    { "pile_set_name": "StackExchange" }
    Q: How do i get facebook album id from url? Im trying to publish to an album on a facebook page (I can post to the wall no problem - i have all the permissions). The Facebook graph API says the album id is the value of aid. But the url looks like: https://www.facebook.com/media/set/?set=a.531274833612778.1073741825.193687907371474&type=3 So what is the album id? A: For the sake of this question having an answer (I missed out @CBroe comment the first time I landed here). The album ID is the first number right between a. and the next following . (dot). In this case: 531274833612778
    { "pile_set_name": "StackExchange" }
    Q: tidyr quasiquotation with lexical scoping I realize that tidy evaluation does not use lexical scoping, but I want the quasiquotation in rlang to look for symbols in the environment I decide. Current behavior: envir <- new.env(parent = globalenv()) eval(parse(text = "little_b <- 'b'"), envir = envir) eval(rlang::expr(!!little_b), envir = envir) ## Error in (function (x) : object 'little_b' not found Instead, I want the last line to return "b". Bonus points if you find a version of eval() that does the job here AND works like evaluate::try_capture_stack(). FYI: I am trying to solve this issue. A: We can use with to pass the expression within an environment with(envir, expr(!!little_b)) #[1] "b" Or another option is local local(rlang::expr(!!little_b), envir = envir) #[1] "b" Or pass via quote in eval (as @lionel mentioned) eval(quote(expr = rlang::expr(!! little_b)), envir = envir) #[1] "b"
    { "pile_set_name": "StackExchange" }
    Q: How to set y axis limits when using map2(~ggplot...? How can I set different y axis limits in each plot when using purrr::map2? I would like to set the y-axis lower limit to half the maximum y-axis value, something like: max(y-axis value/2). data(mtcars) library(tidyverse) mtcars_split <- mtcars %>% split(mtcars$cyl) plots <- map2( mtcars_split, names(mtcars_split), ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + geom_jitter() + ggtitle(.y)+ scale_y_continuous(limits=c(max(.y)/2,NA)) ) plots Error in max(.y)/2 : non-numeric argument to binary operator A: .y is the name of the dataframe, which is why max(.y)/2 is giving you that error. This should give you what you want: plots <- imap( mtcars_split, ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + geom_jitter() + ggtitle(.y) + scale_y_continuous(limits=c(max(.x$mpg)/2,NA)) ) Note that imap(x, ...) is just shorthand for map2(x, names(x), ...). A: This doesn't work based on the y-axis value, but it gets the job done if you don't mind specifying your y-column twice: plots <- map2( mtcars_split, names(mtcars_split), ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + geom_jitter() + ggtitle(.y)+ scale_y_continuous(limits=c(max(.x$mpg)/2,NA)) ) Or maybe a safer option: plots <- map2( mtcars_split, names(mtcars_split), ~{ ploty <- 'mpg' plotx <- 'wt' ggplot(data = .x, mapping = aes_string(y = ploty, x = plotx)) + geom_jitter() + ggtitle(.y)+ scale_y_continuous(limits=c(max(.x[[ploty]])/2,NA)) } )
    { "pile_set_name": "StackExchange" }
    Q: Node.js Ubuntu Installation I am following instructions from as someone suggested on stackoverflow: http://www.giantflyingsaucer.com/blog/?p=2284 After following all the steps when I command git clone https://github.com/joyent/node.git && cd node it shows cloning..... error: RPC failed; result=56, HTTP code = 100 fatal: The remote end hung up unexpectedly I am using Ubuntu, terminals, etc. for the very first time. Can you please suggest what to do? Is there any problem with the configuration? Thanks in advance for bearing such a question... A: If you are new to using node, I would suggest instead of bothering with git just download the source straight from nodejs.org. Choose the 0.4.11 branch, its more stable. From there, follow these directions: sudo apt-get install libssl-dev (may not be needed, but good idea anyways) cd *your download dir* tar xvf node-v0.4.11.tar.gz cd node-v0.4.11 ./configure make sudo make install If that still seems to cause problems, this site allows you to quickly create an install script for node, your mileage may vary with it. A: As others stated above, what's included in the standard repo is quite old. The following is a decent solution on Ubuntu 11 or higher: sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs A: You're on Ubuntu. Is there a reason not to install the package? sudo apt-get install nodejs
    { "pile_set_name": "StackExchange" }
    Q: Creating a formula which references a Variable in WEBI Business Objects I am using a formula to successfully convert a number of minutes into "HH:mm" format- =ToDate(If((IsNull([Totalmins])) Or([Totalmins] = 0 )) Then ("00:00") Else FormatNumber(Floor([Totalmins] /60) ;"00") + ":" + FormatNumber(Floor(Mod([Totalmins] ;60)/1) ;"00");"HH:mm") This works fine where Totalmins is an absolute number. However I also want to convert the SUM of the Totalmins column into HH:mm format, but I can't get it to work. I have tried creating a variable called TotalMinSum which is "=Sum([Totalmins])", and referenced it from the same formula- =ToDate(If((IsNull([TotalMinSum])) Or([TotalMinSum] = 0 )) Then ("00:00") Else FormatNumber(Floor([TotalMinSum] /60) ;"00") + ":" + FormatNumber(Floor(Mod([TotalMinSum] ;60)/1) ;"00");"HH:mm") ...but this does not work. It just gives me an #ERROR. Does anybody know how I can do this? A: Figured it out myself. Went into Designer and added a variable into the universe with the value of sum(@Select(ProjectTotals\Totalmins)). I am now able to use this in the report as if it is an absolute value.
    { "pile_set_name": "StackExchange" }
    Q: For linear quadratic approximation of RBC model, why does matrix $P$ of value function $V = F^TPF$ has to be negative semi-definite matrix? In http://www.compmacro.com/makoto/note/note_rbc_lq.pdf page 5, it is said that for value function $V = F^TPF$ (Bellman equation) $P$ has to be negative semi-definite matrix. Why does it have to be negative semi-definite? A: P being negative semi-definite would imply that V is a concave function. The reason you would restrict P so that V would be a concave function is because of some of the assumptions you've made about about the model previously tell you that V must be concave. In general, some of the typical assumptions that imply that the value function must be concave are something like the following: the graph of the constraint correspondence is convex, the period return function is concave, other assumptions about the stochastic transition function having the Feller property and being monotone, etc... Sorry I'm not giving the full details, but you can read more about them in chapters 4 and 9 of "Recursive Methods in Economic Dynamics" by Stokey, Lucas, and Prescott. The point that I'm making is that the assumptions of these kinds of models usually imply that the value function is concave. Therefore, if you check the assumptions and they indeed do so restrict the value function, then you can restrict your search to look only for matrices P that are negative semi-definite.
    { "pile_set_name": "StackExchange" }
    Q: Uncaught (in promise) TypeError: Cannot call a class as a function I recently upgraded my babel versions to latest. After update the normal class is not recognized by babel in my react application and I am getting below error. Uncaught (in promise) TypeError: Cannot call a class as a function .babelrc { "presets": [ "env", "react" ], "plugins": [ "transform-class-properties", "transform-object-rest-spread" ] } babel related libs in my app: "babel-core": "^6.26.3", "babel-eslint": "^8.2.6", "babel-jest": "^22.4.3", "babel-loader": "^7.1.5", "babel-plugin-transform-class-properties": "^6.24.1", "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-polyfill": "^6.26.0", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1" babel doesn't understand this class CRUDTree.js const resourceBoxWidth = 225; const resourceBoxHeight = 85; const halfBoxWidth = resourceBoxWidth / 2; const halfBoxHeight = resourceBoxHeight / 2; const urlLeftMargin = 10; const urlFontSize = 12; const fullPathFontSize = 10; export default class{ static resourceBoxWidth() { return resourceBoxWidth; } static resourceBoxHeight() { return resourceBoxHeight; } static halfBoxHeight() { return halfBoxHeight; } static halfBoxWidth() { return halfBoxWidth; } } APITree.js import React, { Component } from 'react'; import CRUDTree from './CRUDTree'; class extends Component{ render(){ return( <CRUDTree data={ [ this.state.treedata, this.onClick, { x: this.state.offsetX, y: this.state.offsetY } ]} width={400} height={500} options={{ border: "2px solid black", margin: { top: 0, bottom: 0, left: 50, right: 0 } } } /> ) } } A: If your CRUDTree is a React component (it seems as it is to me) then you are defining it wrong. You are missing the extends part. export default class extends React.Component { .... }
    { "pile_set_name": "StackExchange" }
    Q: UILabel Subclass appears as UILabel in Objective-C I'm a experienced C++ programmer trying to create my first Objective-C subclass of UILabel with an added read-only property // UINumericlabel.h @interface UINumericLabel : UILabel // Returns true if the numeric display contains a decimal point @property (readonly,nonatomic) BOOL hasDecimalPoint; @end // UINumericLabel.m #import "UINumericLabel.h" @implementation UINumericLabel // Returns true if the numeric display contains a decimal point - (BOOL) hasDecimalPoint; { return [self.text rangeOfString:(@".")].location != NSNotFound; } @end When I try to reference the hasDecimalPoint property for an instantiated UINumericLabel I get an abort with error 2012-02-20 18:25:56.289 Calculator[10380:207] -[UILabel hasDecimalPoint]: unrecognized selector sent to instance 0x684c5c0 In the debugger it shows my declaration of a UINumericLabel property as being a UILabel * Do I need to override the (id)init for UILabel in my UINumericLabel subclass? How do I do that? #import "UINumericLabel.h" @interface CalculatorViewController : UIViewController <ADBannerViewDelegate> @property (weak, nonatomic) IBOutlet UINumericLabel *display0; @end When I hover over display0P in the debugger it says it is a UILabel * not a UINumericLabel * UINumericLabel * display0P = self.display0; A: In the Interface Builder select the label and then open the Identity Inspector. In the text field "Class" it probably says UILabel. Change that to be your new subclass, UINumericLabel.
    { "pile_set_name": "StackExchange" }
    Q: Discrepancy in using adjective or adverb with “taste” One asks “how does x taste,” implying that they’d like an adverb describing the way it tastes. But one answers with an adjective, “it tastes good” instead of “it tastes well,” which would imply that x is tasting something else. What’s the reason for this discrepancy? A: Is it good? Or do you feel sick? It’s pretty easy to think of other verbs like this, so there’s no discrepancy. These are linking verbs and the adjective is the subject compliment. A subject complement is the adjective, noun, or pronoun that follows a linking verb. The following verbs are true linking verbs: any form of the verb be [am, is, are, was, were, has been, are being, might have been, etc.], become, and seem. These true linking verbs are always linking verbs. Then you have a list of verbs that can be linking or action: appear, feel, grow, look, prove, remain, smell, sound, taste, and turn. If you can substitute any of the verbs on this second list with an equal sign [=] and the sentence still makes sense, the verb is almost always linking. Grammar Bytes — The Subject Complement: Recognize a subject complement when you see one.
    { "pile_set_name": "StackExchange" }
    Q: Issue with Java threads, using Runnable or Thread I'm trying to implement multi-threading using merge sort. I have it making new threads at the point where it cuts an array in half. The array is sorted depending on the: [size of the array] vs [how many times I create new threads] For instance: the array will be sorted if I let it create merely two threads on an array of size 70, but if I let it create 6, it will come back unsorted. One thing I thought it might be is that the threads weren't sync'd, but I used threadName.join() here is some code: merge.java import java.util.Random; public class merge implements Runnable { int[] list; int length; int countdown; public merge(int size, int[] newList, int numberOfThreadReps, int firstMerge) { length = size; countdown = numberOfThreadReps; list = newList; if (firstMerge == 1) threadMerge(0, length - 1); } public void run() { threadMerge(0, length - 1); } public void printList(int[] list, int size) { for (int i = 0; i < size; i++) { System.out.println(list[i]); } } public void regMerge(int low, int high) { if (low < high) { int middle = (low + high) / 2; regMerge(low, middle); regMerge(middle + 1, high); mergeJoin(low, middle, high); } } public void mergeJoin(int low, int middle, int high) { int[] helper = new int[length]; for (int i = low; i <= high; i++) { helper[i] = list[i]; } int i = low; int j = middle + 1; int k = low; while (i <= middle && j <= high) { if (helper[i] <= helper[j]) { list[k] = helper[i]; i++; } else { list[k] = helper[j]; j++; } k++; } while (i <= middle) { list[k] = helper[i]; k++; i++; } helper = null; } public void threadMerge(int low, int high) { if (countdown > 0) { if (low < high) { countdown--; int middle = (low + high) / 2; int[] first = new int[length / 2]; int[] last = new int[length / 2 + ((length % 2 == 1) ? 1 : 0)]; for (int i = 0; i < length / 2; i++) first[i] = list[i]; for (int i = 0; i < length / 2 + ((length % 2 == 1) ? 1 : 0); i++) last[i] = list[i + length / 2]; merge thread1 = new merge(length / 2, first, countdown, 0);// 0 // is // so // that // it // doesn't // call // threadMerge // twice merge thread2 = new merge(length / 2 + ((length % 2 == 1) ? 1 : 0), last, countdown, 0); Thread merge1 = new Thread(thread1); Thread merge2 = new Thread(thread2); merge1.start(); merge2.start(); try { merge1.join(); merge2.join(); } catch (InterruptedException ex) { System.out.println("ERROR"); } for (int i = 0; i < length / 2; i++) list[i] = thread1.list[i]; for (int i = 0; i < length / 2 + ((length % 2 == 1) ? 1 : 0); i++) list[i + length / 2] = thread2.list[i]; mergeJoin(low, middle, high); } else { System.out.println("elsd)"); } } else { regMerge(low, high); } } } proj4.java import java.util.Random; public class proj4 { public static void main(String[] args) { int size = 70000; int threadRepeat = 6; int[] list = new int[size]; list = fillList(list, size); list = perm(list, size); merge mergy = new merge(size, list, threadRepeat, 1); // mergy.printList(mergy.list,mergy.length); for (int i = 0; i < mergy.length; i++) { if (mergy.list[i] != i) { System.out.println("error)"); } } } public static int[] fillList(int[] list, int size) { for (int i = 0; i < size; i++) list[i] = i; return list; } public static int[] perm(int[] list, int size) { Random generator = new Random(); int rand = generator.nextInt(size); int temp; for (int i = 0; i < size; i++) { rand = generator.nextInt(size); temp = list[i]; list[i] = list[rand]; list[rand] = temp; } return list; } } so TL;DR my array isn't getting sorted by a multithreaded merge sort based on the size of the array and the number of times I split the array by using threads...why is that? A: Wow. This was an interesting exercise in masochism. I'm sure you've moved on but I thought for posterity... The bug in the code is in mergeJoin with the middle argument. This is fine for regMerge but in threadMerge the middle passed in is (low + high) / 2 instead of (length / 2) - 1. Since in threadMerge low is always 0 and high is length - 1 and the first array has (length / 2) size. This means that for lists with an odd number of entries, it will often fail depending on randomization. There are also a number of style issues which makes this program significantly more complicated and error prone: The code passes around a size of the arrays when Java has a convenient list.length call which would be more straightforward and safer. The code duplicates calculations (see length/2) in a number of places. The code should be able to sort inside the array without creating sub-arrays. Classes should start with an uppercase letter (Merge instead of merge) firstMerge should be a boolean The code names the Thread variable merge1 and the merge variable thread1. Gulp. The merge constructor calling threadMerge(0,length -1) is strange. I would just put that call after the new call back in proj4. Then firstMerge can be removed. I would consider switching to having high be one past the maximum value instead of the maximum. We tend to think like for (int i = 0; i < 10; i++) more than i <= 9. Then the code can have j go from low to < middle and k from middle to < high. Better symmetry. Best of luck.
    { "pile_set_name": "StackExchange" }
    Q: Any news on the graduation from beta? Given the performance of the beta site. How do we know if and when a graduation is in order? A: I've been monitoring this beta's site activity on Area51 Stack Exchange dashboard and Stack Exchange sites overview very closely. From what I can tell, the main statistics I've been looking at is the questions per day indicator and if you only look at this rate (currently around 14 questions asked per day), Ethereum Stack Exchange is the most active beta site in the network (followed by Adruino (13), Mechanics (11) and Gardening (10)). However, site activity might be the main indicator for graduation, but there are also some other soft factors that also play an important role. User base: This site wont graduate until it has a solid (and maintains an active) user base. The stats on Area51 might be misleading as they are probably placing the mininmung requirements too low (compare mechanics user base to our's on Area51 for instance, they are also waiting for graduation). I think we wont recieve a graduation notice unless we have at least 5 users above 10k reputation (a.k.a. access to moderator tools privilege) and a dozen users above 3k reputation (a.k.a. cast open and close votes privilege). Meta activity: This site is very active on the main topic, but the activity on meta is currently very low. We need to get more involved with defining what this site actually is, e.g., what is on topic, what is off topic, what is our topic, what should our documentation contain, etc. pp.? See also our current challenge. To get an interesting insight into beta progress updates by the community, you can follow this August 2015 and that January 2016 report on the Adruino beta site. So, if you want to speed up graduation process, you can do multiple things for now. Ask 1 good question a day, this wont keep graduation away. Vote good content up, vote low quality content down. This will separate the wheat from the chaff, and also will generate reputation for users and maintain a solid userbase. Get involved in meta. You are invited to discuss, debate and propose changes to the way the Ethereum Stack Exchange community itself behaves (discussions), as well as how the software itself works (bugs, features, support). Thanks for coming to meta and helping out to mature this site.
    { "pile_set_name": "StackExchange" }
    Q: CSS selector issues I am very bad with selectors, I am trying to figure out how to make a transition happen on my form when I hover over the "create one" link. Can anyone help me? http://jsfiddle.net/LyZxG/ body:hover .form{} the fiddle above shows all of my code, I currently have it transitioning from "body:hover" so you can see the transition. Thanks in advance! ps. I have ready every form about selectors and cant figure it out, I know its simple I'm just not getting it, thank you again. A: OK with just css all you need to do is remove the body:hover .form{} add and in .create-link:hover .form{ opacity:1.0; width:260px; } After you do that you will need to update your create link html to this <li class="create-link"> <a href="#"> <h1 class="account-links">Create One</h1></a> <form class="form" action="demo_form.asp" method="get"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> Password: <input type="text" name="pass"> <input type="submit" value="Submit"> </form> </li>
    { "pile_set_name": "StackExchange" }
    Q: existence of de Rham complexes I have a very basic question about the exterior derivative of differential forms and de Rham complexes. It is very basic, I know that the exterior derivative satisfies $d^2=0$. Knowing that, how is a de Rham complex even possible ? My definition of a de Rham complex is the following : Let $M$ be a manifold of dimension $n$, the de Rham complex is the following chain : $$ 0 \xrightarrow[]{d} \Omega ^{0}(M) \xrightarrow[]{d} \Omega ^{1}(M) \xrightarrow[]{d} ... \xrightarrow[]{d} \Omega ^{m}(M) \xrightarrow[]{d} 0 $$ My question : since $d^2 =0$, shouldn't we always have that $\Omega ^2 (M) = 0$ ? Thank you very much for your help A: $\Omega^2(M)$ is the space of all the differential $2$-forms on $M$. You have $d(\Omega^1(M))\subseteq\Omega^2(M)$ and $d^2(\Omega^0(M))\subseteq d(\Omega^1(M))\subseteq\Omega^2(M)$. As you said, $d^2(\Omega^0(M))=\{0\}$, but there's no reason why $d^2(\Omega^0(M))$ would be equal to $\Omega^2(M)$.
    { "pile_set_name": "StackExchange" }
    Q: Solving a pair of ODEs I'm trying to solve a pair of ODEs for which I've obtained a solution. However, my problem is that my answer is slightly different from mathematica's answer. $$ \frac{dA}{dt} = \theta - (\mu + \gamma)A, \ \ A(0) = G$$ $$ \frac{dT}{dt} = 2 \mu A - (\mu + \gamma)T, \ \ T(0) = B$$ Using an integrating factor of $e^{(\mu + \gamma)t}$, I got the following solution to the first ODE: $$ A(t) = \frac{\theta}{\mu + \gamma} + \left(G -\frac{\theta}{\mu + \gamma}\right)e^{-(\mu + \gamma)t}$$ For simplicity, let $\mu + \gamma = \alpha$ such that: $$ A(t) = \frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}$$ For the second ODE (again using an integrating factor of $e^{(\mu + \gamma)t}= e^{\alpha t}$ ): $$ e^{\alpha t}\frac{dT}{dt} + e^{\alpha t}\alpha T = 2 \mu A e^{\alpha t} $$ $$ T(t)e^{\alpha t} = \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}\right)dt $$ $$ T(t) = \frac{2 \mu \theta}{\alpha^2} + \left(B - \frac{2 \mu \theta}{\alpha^2}\right)e^{-\alpha t} $$ However, when I computed these two ODEs in mathematica, it gave back the following solution: $$ T(t) = Be^{-\alpha t} + 2G \mu te^{-\alpha t}+ \frac{2 \mu \theta}{\alpha^2} - \frac{2 \mu \theta e^{-\alpha t}}{\alpha^2} - \frac{2 \mu \theta t e^{-\alpha t}}{\alpha} $$ I've tried solving my equation over and over again but I can't seem to understand why my solution is different from mathematica's. The only I thought about was possibly in the substitution of arbitrary constant. Am I missing something obvious here? A: You forgot the integration constant. Following on from your integral for $T(t)$, we find \begin{align} T(t)e^{\alpha t} &= \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}\right)dt \\ &= \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right) dt \\ &= 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t + C \\ \implies T(t) &= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t e^{-\alpha t} + Ce^{-\alpha t} \\ T(0) &= B \\ &= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + C \\ \implies C &= B - 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) \\ \implies T(t) &= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t e^{-\alpha t} + \bigg(B - 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) \bigg)e^{-\alpha t} \\ &= \frac{2 \mu \theta}{\alpha^{2}} + 2 \mu G t e^{-\alpha t} - \frac{2 \mu G \theta}{\alpha}t e^{-\alpha t} + B e^{-\alpha t} - \frac{2 \mu \theta}{\alpha^{2}} e^{-\alpha t} \\ &= B e^{-\alpha t} + 2 \mu G t e^{-\alpha t} + \frac{2 \mu \theta}{\alpha^{2}} - \frac{2 \mu G \theta}{\alpha}t e^{-\alpha t} - \frac{2 \mu \theta}{\alpha^{2}} e^{-\alpha t} \end{align}
    { "pile_set_name": "StackExchange" }
    Q: What is the default 'backup' user for? I am setting up multiple-machine backup plan and I was hoping to use a user called 'backup' on each machine as the backup destination. My problem is, there is already a user called 'backup' on my machine. What is it for, and can I hijack it for my own purposes? root@frodo:~# useradd backup useradd: user 'backup' already exists A: I can confirm it's in a default installation, see the /usr/share/base-passwd/passwd.master file provided by the base-passwd package. According to the documentation from that package, it is used for backup accounts without requiring full root permissions (which is available at /usr/share/doc/base-passwd/users-and-groups.txt.gz, /usr/share/doc/base-passwd/users-and-groups.html and online): backup Presumably so backup/restore responsibilities can be locally delegated to someone without full root permissions? HELP: Is that right? Amanda reportedly uses this, details? Note the keyword locally, for remote backups you have to enable a login shell first. You are free to use it for your own purposes, but note the above guide lines. Do not grant sudo policies for example that would allow the backup user to escalate its privileges to root.
    { "pile_set_name": "StackExchange" }
    Q: TestNG class with Factory and Dataprovider never works I have a jar calculator library. I made a simple class to test 'sum' function with Factory and DataProvider like in many examples. But when i run it i see: no test's executed. If i delete Factory and write DataProvider to a Test annotation - everything works fine. public class SumTest { Calculator calc = new Calculator(); private final double a; private final double b; @Factory(dataProvider = "getValues") public SumTest(double aValue, double bValue) { this.a = aValue; this.b = bValue; this.calc = new Calculator(); } @Test public void testSum() { Assert.assertEquals(a + b, calc.sum(a, b)); } @DataProvider public Object[][] getValues() { return new Object[][]{ {10, 5}, {-10, 5}, {11.55, -10.55}, {-5, -6}, {99999.8d, 1l}, {9223372036854775807L, 9223372036854775807L} }; } } A: DataProvider needs to be Static to make Factory Work.
    { "pile_set_name": "StackExchange" }
    Q: glBindAttribLocation whats next? I'm struggling to find OpenGL/GLSL examples that don't require glew or glut or what have you. I'm trying to work with only using glfw3 (if possible I would like to use no other libraries) and I'm struggling to understand what to do once I use glBindAttribLocation? I've written code to pass an image as a texture into shaders, but I can't figure how to pass vertices. I have a vertex shader and fragment shader I want to make a triangle and then color it red, I can create the shader programs and object program and link everything, but how do I pass things to the shaders. // vert in vec3 vPosition; void main() { gl_Position = vec4(vPosition,1.0); } // Frag out vec4 color; void main() { color = vec4(1.0,0.0,0.0,1.0); } I don't understand what I need to do after I call glBindAttribLocation glBindAttribLocation(p,0,"vPosition"); glUseProgram(p); now how do I pass the vertices of a triangle into the shader? more code, I'm calling my own library to read in the files so the textread won't work if anyone tries to run it #include <GLFW/glfw3.h> #include <stdlib.h> #include <stdio.h> #include "src/textfile.h" GLuint v,f,p; void printLog(GLuint obj) { int infologLength = 0; int maxLength; if(glIsShader(obj)) glGetShaderiv(obj,GL_INFO_LOG_LENGTH,&maxLength); else glGetProgramiv(obj,GL_INFO_LOG_LENGTH,&maxLength); char infoLog[maxLength]; if (glIsShader(obj)) glGetShaderInfoLog(obj, maxLength, &infologLength, infoLog); else glGetProgramInfoLog(obj, maxLength, &infologLength, infoLog); if (infologLength > 0) printf("%s\n",infoLog); } static void error_callback(int error, const char* description) { fputs(description, stderr); } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } void setShaders() { char *vs = NULL,*fs = NULL; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); vs = textFileRead("toon.vert"); fs = textFileRead("toon.frag"); const char * ff = fs; const char * vv = vs; glShaderSource(v, 1, &vv,NULL); glShaderSource(f, 1, &ff,NULL); free(vs);free(fs); glCompileShader(v); glCompileShader(f); p = glCreateProgram(); glAttachShader(p,f); glAttachShader(p,v); glLinkProgram(p); //glUseProgram(p); } int main(void) { GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); while (!glfwWindowShouldClose(window)) { int height, width; float ratio; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); setShaders(); glBindAttribLocation(p,0,"vPosition"); glUseProgram(p); /* Now What */ glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } A: you "pass vertices into the shaders" by making a draw call, most typically glDrawArrays(). when glDrawArrays() hits, the currently bound vertex array gets sent off to GPU-land. the vertices will be processed by the currently bound program (which you seem to have figured out) and each vertex attribute will flow into the vertex shader variables based on whether or not the shader variable's attribute index matches the vertex attribute's glVertexAttribPointer() "index" parameter (which you seem on the way to figuring out). so, look into glVertexAttribPointer() to describe your array of vertices, glEnableAttributeArray() to enable your array of vertices to be sent on the next draw call, and then glDrawArrays() to kick off the party.
    { "pile_set_name": "StackExchange" }
    Q: Proving that the derivative of an odd function is even. For an assignment I had, I had to prove that the derivative of an odd function is even. In the assignment we also had to prove that $F(x)=\int_0^x f(t)dt$ is odd given that $f$ is even, which I did do. Using that fact I stated the following: Let us define $F(x)=\int_0^xf(t)dt$ such that $F(x)$ is odd. \begin{equation} F'(x)=\frac{d}{dx}\int_0^xf(t)dt=f(x) \nonumber \end{equation} Using 1.1 (the section where I proved that $F(x)=\int_0^x f(t)dt$ is odd given that $f$ is even) we know that $f(x)$ is even. However, the teacher felt that the answer was not rigorous enough and that I was simply going backwards. Am I indeed simply moving backwards and not proving anything in which case: could someone point out places where I could make it more succinct and rigorous or alternatively supply better proof altogether. A: The proof is quite simple from the definition of the derivative: if $f$ is odd then $$ f'(-x) = \lim\limits_{h\to 0}\frac{f(-x+h)-f(-x)}{h} = -\lim\limits_{h\to 0}\frac{f(x-h)-f(x)}{h} = -f'(x). $$ W.r.t. your proof. You have showed that if $f$ is even, then $F = \int f$ is odd. You proved it - but you didn't prove that any odd function is an anti-derivative of the even function. That would be a reverse statement, as Alex has already told you. Generally, you have $A\Rightarrow B$ where $A = \{f\text{ is even}\}$ and $B = \{F\text{ is odd}\}$ but to prove that the derivative of the odd function is even you need $B\Rightarrow A$ which you don't know at the moment.
    { "pile_set_name": "StackExchange" }
    Q: Flask WTForms validate_on_submit not working I am new in Web Development and I am using Flask to create a property price prediction website. I have a function validate_on_submit that is not working. It does not show any error, the form is submitted, it just does not validate. When the submit form is clicked, it needs to go to the next page. Here is the code: @app.route('/route1', methods=['POST', 'GET']) def predict(): form = Form_1() # These errors, submitted and validated just for some context, not in the actual code print(form.errors) # Returns {} if form.submit(): print("submitted") # Returns "submitted" if form.validate(): print("validated") # Page shows error 'NoneType' object is not iterable # more code if form.validate_on_submit(): print("validated on submit") # This is not working # more code return redirect(url_for('page_x')) return render_template('page_x.html', title='Page X', form=form) Here is the HTML: <div class="content" align="center"> <div class="content-section"> <form method = "POST" action=""> {{ form.hidden_tag() }} <table style="width:15%"> <tr> <td>{{ form.select_field.label() }}</td> <td>:</td> <td>{{ form.select_field() }}</td> </tr> <tr> <td></td> <td></td> <td>{{ form.submit() }}</td> </tr> </table> </form> </div> </div> It is weird because I have another code similar to this that worked: @app.route('/route2', methods=['POST', 'GET']) def add_data(): form = Form_2() if form.validate_on_submit(): # more code return redirect(url_for('page_y') return render_template('page_y.html', title='Page Y', form=form) HTML: <div class="content" align="center"> <h1>Help Us Improve by Uploading a New Dataset</h1> <div class="content-section"> <form method="POST" action="" enctype="multipart/form-data"> {{ form.hidden_tag() }} {{ form.add_file() }} {{ form.submit() }} </form> </div> </div> I am not sure what went wrong. Any help would be appreciated. Thank you. A: I found the problem. It is with the SelectField form that I use. I place a coerce arguments and it works. Article that helped me: Not a Valid Choice for Dynamic Select Field WTFORMS
    { "pile_set_name": "StackExchange" }
    Q: jQuery - Event by scroll The goal of my script is that when user scrolls down, my page should scroll to the next div. For this, the script distinguishes if the user scrolls up and down. After, when he scrolls, it should remove the class active of my first div and add to the next. Then it's scrolling to the new div with the class active. The problem is that it's working for the first scroll only, not the next. My code: $(window).load(function() { var tempScrollTop, currentScrollTop = 0; var $current = $("#container > .active"); var next = $('.active').next(); var prev = $('.active').prev(); $(window).scroll(function() { currentScrollTop = $(window).scrollTop(); if (tempScrollTop < currentScrollTop) { //scrolling down $current.removeClass('active').next().addClass('active'); $.scrollTo(next, 1000); } else if (tempScrollTop > currentScrollTop ) { //scrolling up $current.removeClass('active').prev().addClass('active'); $.scrollTo(prev, 1000); } tempScrollTop = currentScrollTop; }); }); Can anybody help me? A: I found the answer var lastScrollTop = 0; var isDoingStuff = false; $(document).scroll(function(event) { //abandon if(isDoingStuff) { return; } if ($(this).scrollTop() > lastScrollTop) { //console.log('down'); $('.active').removeClass('active').next('div').addClass('active'); isDoingStuff = true; $('html,body').animate( {scrollTop: $('.active').offset().top }, 1000, function() { setTimeout(function() {isDoingStuff = false;}, 100); console.log('off'); }); } else { //console.log('up'); } lastScrollTop = $(this).scrollTop(); })​
    { "pile_set_name": "StackExchange" }
    Q: How to implement a Web UI feature to insert default sentences in an textarea We are talking about implementing a system that easily generates sales reports for our sales employees. We want to create a web application with one or maybe more text area's to gather the input data from the employee. There are a few sentences that will return time and time again. Something like: "customer xyz decided to buy the products advised by consultant abc" What options do I have to implement a feature like that. What I already thought of: Click RMB in text area to pop the sentences or categories of sentences which can be selected. Feels a bit outdated to me. Shortcuts, like an IDE. When I type psvm[tab] I get "public static void main...". Probably to technical for most users. Present a box with sentences next to the text area from which you can drag and drop the sentences. This will take up a lot of real estate. When the system recognizes the start of a sentence that is in the default sentences it pops the sentence and can be clicked (something like the tag functionality here on SE). This will give a lot of false true's which might be annoying for the user. I understand that there is not a single right answer to this question. Please post answers preferably with an example (of some other site) A: When the system recognizes the start of a sentence that is in the default sentences it pops the sentence and can be clicked (something like the tag functionality here on SE). This will give a lot of false true's which might be annoying for the user. I would go with this one. It's done in Microsoft Excel (which is fairly ubiquitous). The only time this might get annoying is if the user had to take extraordinary measures to change it. (If they kept typing something else, the default would disappear) If you are unsure about it, test it with a few people who will be using the system. It's the only way to be sure.
    { "pile_set_name": "StackExchange" }
    Q: Best PHP Webserver for Development I'm starting to work with PHP more these days and I've been wondering what the best PHP webserver might be for a dev environment. Ideally, it would be easy to build, live only in the project deps directory and be easy to configure. Also, decent performance would be a plus. In python land, werkzeug would be an equivalent of the type of server I'm thinking of. A: In my opinion, the best webserver for the dev environment is as close as you can come to exactly the webserver in production. PHP is a lot less 'stand-alone' in some cases then Python, and it prevents nasty errors and surprises when pushing code to the production server. All kinds of havoc can ensue when a $_SERVER array is just that essential bit different, or something runs as (fast)cgi instead of as a module.
    { "pile_set_name": "StackExchange" }
    Q: Reportlab: Is it possible to have internal links in Platypus? I know that I can internally link with canvas, but my whole doc's set up with Platypus. Does Platypus support internal linking? How hard is migrating to canvas if it doesn't? Thanks in advance! A: You can use intra-paragraph markup to create anchors (<a> tag) and links (<link> tag), as explained in the section 6.3 Intra-paragraph markup (chapter 6, page 72) of the ReportLab 2.6 User Manual PDF, which also contains the following example: This <a href="#MYANCHOR" color="blue">is a link to</a> an anchor tag ie <a name="MYANCHOR"/><font color="green">here</font>. This <link href="#MYANCHOR" color="blue" fontName="Helvetica">is another link to</link> the same anchor tag.
    { "pile_set_name": "StackExchange" }
    Q: What's the relationship between an SVM and hinge loss? My colleague and I are trying to wrap our heads around the difference between logistic regression and an SVM. Clearly they are optimizing different objective functions. Is an SVM as simple as saying it's a discriminative classifier that simply optimizes the hinge loss? Or is it more complex than that? How do the support vectors come into play? What about the slack variables? Why can't you have deep SVM's the way you can't you have a deep neural network with sigmoid activation functions? A: I will answer one thing at at time Is an SVM as simple as saying it's a discriminative classifier that simply optimizes the hinge loss? SVM is simply a linear classifier, optimizing hinge loss with L2 regularization. Or is it more complex than that? No, it is "just" that, however there are different ways of looking at this model leading to complex, interesting conclusions. In particular, this specific choice of loss function leads to extremely efficient kernelization, which is not true for log loss (logistic regression) nor mse (linear regression). Furthermore you can show very important theoretical properties, such as those related to Vapnik-Chervonenkis dimension reduction leading to smaller chance of overfitting. Intuitively look at these three common losses: hinge: max(0, 1-py) log: y log p mse: (p-y)^2 Only the first one has the property that once something is classified correctly - it has 0 penalty. All the remaining ones still penalize your linear model even if it classifies samples correctly. Why? Because they are more related to regression than classification they want a perfect prediction, not just correct. How do the support vectors come into play? Support vectors are simply samples placed near the decision boundary (losely speaking). For linear case it does not change much, but as most of the power of SVM lies in its kernelization - there SVs are extremely important. Once you introduce kernel, due to hinge loss, SVM solution can be obtained efficiently, and support vectors are the only samples remembered from the training set, thus building a non-linear decision boundary with the subset of the training data. What about the slack variables? This is just another definition of the hinge loss, more usefull when you want to kernelize the solution and show the convexivity. Why can't you have deep SVM's the way you can't you have a deep neural network with sigmoid activation functions? You can, however as SVM is not a probabilistic model, its training might be a bit tricky. Furthermore whole strength of SVM comes from efficiency and global solution, both would be lost once you create a deep network. However there are such models, in particular SVM (with squared hinge loss) is nowadays often choice for the topmost layer of deep networks - thus the whole optimization is actually a deep SVM. Adding more layers in between has nothing to do with SVM or other cost - they are defined completely by their activations, and you can for example use RBF activation function, simply it has been shown numerous times that it leads to weak models (to local features are detected). To sum up: there are deep SVMs, simply this is a typical deep neural network with SVM layer on top. there is no such thing as putting SVM layer "in the middle", as the training criterion is actually only applied to the output of the network. using of "typical" SVM kernels as activation functions is not popular in deep networks due to their locality (as opposed to very global relu or sigmoid)
    { "pile_set_name": "StackExchange" }
    Q: How to compare two objects in a dictionary I just wonder that how to compare two objects in a dictionary: a = {} while z: if a[z] == a[s]: print("Correct!") else: print("You don't know that country.") z = input("Enter a country: ") s = input("What is the capital of " + z + " ? ") I want to print Correct when z = s; when z not in a, print You don't know that country. A: Assuming that a is a dictionary with the country as the key, and the capital as the value, you should make two separate checks: First you want to make sure that the entered country exists as a key in the dictionary. For that you should use the in operator. Second, you want to check whether the entered capital matches the capital in the dictionary. For that you perform an index access using the country on the dictionary and check whether the value equals the entered capital: capitals = { 'Austria': 'Vienna', 'Belgium': 'Brussels', 'Denmark': 'Copenhagen', 'France': 'Paris', 'Germany': 'Berlin', 'Netherlands': 'Amsterdam', 'Norway': 'Oslo', 'Sweden': 'Stockholm', 'Switzerland': 'Bern', 'United Kingdom': 'London' } while True: country = input("Enter a country: ") # abort the loop if the user didn’t enter anything if not country: break # check whether we know that country if country in capitals: capital = input("What is the capital of {}? ".format(country)) if capital == capitals[country]: print('That was correct!') else: print('You made a mistake there.') else: print('I do not know that country, sorry.')
    { "pile_set_name": "StackExchange" }
    Q: Brute-force algorithm to find the set of all empty triangles Given a set P of points in the plane, specify a naive brute-force algorithm to find the set of all empty triangles with vertexes in P. (A triangle with vertexes a, b, c belong to P is empty if it contains no other point d which belongs to P.) How shall I start solving this type of problem? Are there any existing algorithm which I should look up or you think I would have to sketch it out with a few points? A: Given a set P of points in the plane, specify a naive brute-force algorithm to find the set of all empty triangles with vertexes in P. (A triangle with vertexes a, b, c belong to P is empty if it contains no other point d which belongs to P.) How shall I start solving this type of problem? Well bottom up: For a single triangle and a single point, write a function contains, which tests, whether the point is in the triangle. For a single triangle and a group of points, look whether whether there is no point contained in the triangle. Call this isEmpty. For a group of triangles, test each. Keywords are: iteration, predicate, filter. You should write tests on each stage, points in the triangle, outside, bordercases. Test as early as possible. Write testmethods, to make testing easy. Then Triangle.isEmpty or how this would look in your language. Top down would work too. Then you might need mock-functions for testing. But I don't see advantages vs. bottom up. Pseudocode: Triangle.contains (p: Point) : Boolean () Triangle.isEmpty (ps: Pointset) : Boolean = ps.forAll (p => ! t.contains (p)) triangleset.filter (t => t.isEmpty (pointset))
    { "pile_set_name": "StackExchange" }
    Q: Apply bootstraps tr hover effect to a div I am using Bootstrap for my css themes. The themes are compiled and saved into the database for use later on. This means that the pages only have access to the compiled css and not the less files. Given that, how can I apply Bootstrap’s tr:hover effect to various divs? I need the color to be the same as what is defined for tr:hover and I can’t use less variables. Bootstrap's style: .table tbody tr:hover td, .table tbody tr:hover th { background-color: #f5f5f5; } Is it possible to define a css element based on another one that is assigned to a tr? Is there a way to grab the style using jQuery? Any suggestions? A: Pure CSS Way: Have a class for the div as .hoverDiv and the CSS for this: .hoverDiv {background: #fff;} .hoverDiv:hover {background: #f5f5f5;} Fiddle: http://jsfiddle.net/bD5kS/ jQuery Way: $(document).ready(function(){ $(".hoverDiv").hover(function(){ $(this).css("background", "#f5f5f5"); }, function(){ $(this).css("background", "#fff"); }); }); Fiddle: http://jsfiddle.net/KQzwc/ To get the colour dynamically, use $(".table tbody tr:hover").css("background-color"): $(document).ready(function(){ $(".hoverDiv").hover(function(){ $(this).css("background", $(".table tbody tr:hover").css("background-color")); }, function(){ $(this).css("background", $(".table tbody tr").css("background-color")); }); });
    { "pile_set_name": "StackExchange" }
    Q: My PC doesn't want to make a final rebooting to end up the installation of Ubuntu 16.04 smarty people, I'm a total noob on OS subject, so I'll be very thankful if you excuse me for the elementary lvl of my question. I've tried to install the last update desktop version of Ubuntu 17.10, but it refuses to make the last installation (after the settings and all of the questions) to finish the process. I didn't find any similar questions on the Internet, so I've decided that maybe the problem is very unpopular or perhaps I've done something wrong (which is kindda funny, considering how easy should it be). Anyway, I've downloaded the older version since 16.04.2017, but that didn't fixed the situation. I click on the button "restart" and the desktop freezes with no possibility to click again. The only option available is to shut-down the PC and the whole operation repeat itself all over again. I've used USB Flash Drive for the booting and I want to make Ubuntu pioneer OS on my PC. So, where exactly the root of the problem should be? (is in the ground, someone could say, but I've dig the whole place yet) A: SysRq R E I S U B - graceful reboot Sometimes, at the very end of the installation, the system justs hangs, does not reboot, does not shut down. This can be caused by a 'race condition', that things cannot be done in the correct sequence. When this happens it might help with the SysRq R E I S U B method. This causes the computer to reboot gracefully (if it can listen to the request). See more details in the following link and links from it, Restart Ubuntu via keyboard SysRq is often on the PrintScreen key: Press Alt + PrintScreen continuously, sometimes the Fn key is involved too (in laptops), and then slowly (one key after another) the keys R E I S U B to reboot. When you press the 'letter keys' you need not specify caps lock or shift.
    { "pile_set_name": "StackExchange" }
    Q: Has the Url Shortener in Google Apps Script changed? I've been using this simple function to create shortened links in Google Apps Script. It's been working for the past few months but stopped working few days ago. Has there been a change? function getShortenedUrl(url){ var longUrl = UrlShortener.newUrl() .setLongUrl(url); var shortUrl = UrlShortener.Url.insert(longUrl); return shortUrl.getId(); } A: Yes. It has. I figured it out the hard way. Just make a small change for it to work function getShortenedUrl(url){ var longUrl = UrlShortener.newUrl(); longUrl.setLongUrl(url); var shortUrl = UrlShortener.Url.insert(longUrl); return shortUrl.getId(); }
    { "pile_set_name": "StackExchange" }
    Q: How to get manufacturer name for each product I have to get some attributes for each product I've gotten most of them but I don't know how to get manufacturer name and the upc or ean barcode value in adminhtml. I've tried with this code $name = 'Manufacturer'; $attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem(); $attributeId = $attributeInfo->getAttributeId(81); $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId); $attributeOptions = $attribute ->getSource()->getAllOptions(false); var_dump($attribute); But I can Just print (like in the image) $attribute level and then the $attributeOptions goes empty. A: $productId='your_product_id'; $product=Mage::getModel('catalog/product')->load($productId); $manufaturer=$product->getAttributeText('manufacturer');
    { "pile_set_name": "StackExchange" }
    Q: Pass file from file() to Perl program PHP I have a PHP code that stores contents of a url by file() method like $contents=file("http://www.rcsb.org/pdb/files/2AID.pdb"); I need to pass these $contents to a perl program by shell_exec() method , something like following $result=shell_exec("perl_prog.pl $contents"); My question is how to pass this $contents to Perl program. I tried like following @file=<@ARGV>; but its not working. Please help me. A: That shell_exec() code is utterly vulnerable to shell injection - you're trusting that the remote service won't include something like: ; rm -rf / As well, file() returns the file contents as an array - you can't pass arrays over the command line directly. Only strings. A moderately safer version is: $contents = file_get_contents('http://etc....'); $safe_contents = escapeshellarg($contents); $result = shell_exec('perl_prog.pl $safe_contents'); On the Perl side, you'd use my ($contents) = @ARGV;
    { "pile_set_name": "StackExchange" }
    Q: Rails - Alphanumeric field validation In rails 4, I need to validate the alphanumeric field which can accept only dot(.), hyphen(-), slash(/) and space in between the characters. Eg: AB123-GH345 or AB45.NH744 or KHJ3/SD34 or HJS23 JKA34 I have tried with /^[0-9]+#$/ and /^\d+([.,]\d+)?$/ and /^[0-9]+#$/ but it is not working as per the requirement. Value should be accept as per the examples. Please help me to validate this field. A: I think this might help you: /^[A-Za-z0-9-\/\.\s]+$/ This worked for all the examples you have provided AB123-GH345 or AB45.NH744 or KHJ3/SD34 or HJS23 JKA34 and rejected when I inserted a character like ? in the middle(HJS23?JKA34). Update If you don't want multiline anchors then you can use it like this: /\A[A-Za-z0-9-\/\.\s]+\z/ You can use this Rubular site to validate your Regex codes.
    { "pile_set_name": "StackExchange" }
    Q: Sorting Color in C# on the basis of brightness or YIQ scale I am looking for sorting some colors in our project on the basis of the brightness, so probably I need YIQ representation of the color on basis of which I can sort. So I am pricesely looking for the YIQ representaion of some given RGB format color in C# I found this formula on wiki and some other sites for conversion from RGB to YIQ scale: Here is the RGB -> YIQ conversion: [ Y ] [ 0.299 0.587 0.114 ] [ R ] [ I ] = [ 0.596 -0.275 -0.321 ] [ G ] [ Q ] [ 0.212 -0.523 0.311 ] [ B ] But now how to get the Color value in C# from this Y, I and Q values which we would get from this formula. So if I have this color: #FF832727 which is in RGB format, how to get its corresponding color in YIQ scale. A: Possible implementation, if I´ve understood your right List<Color> colors = new List<Color> { Color.Wheat, Color.Black, Color.Red, Color.FromArgb(unchecked ((int)0xFF832727U)) }; // You don't need convert colors into YIQ (i.e. matrix multiplication) // just compare brightness (Y component) colors.Sort((Comparison<Color>) ( (Color left, Color right) => (left.R * 299 + left.G * 587 + left.B * 114).CompareTo( right.R * 299 + right.G * 587 + right.B * 114) ));
    { "pile_set_name": "StackExchange" }
    Q: How to determine where biggest files/directories on my system are stored? I was wondering how do you know where the largest files in my system are stored. For example--- Disk Space Used: 1GB Java: 500MB Java Percentage: 50% maybe represented in a pie chart. Maybe? I know this maybe a feature overkill. I sometimes forget having stored things and wonder why my disk is so full. So basically a command that will allow me to run on the file system and provide me with information on disk space used. Please and thank you. A: The Disk Usage Analyzer is available under Ubuntu > Accessories > Disk Usage Analyzer. It provides you with a snazzy pie graph showing what files and folders take up the most space: The documentation on it is a little sparse, but you can find more information on the Ubuntu wiki, and the project page. If you're interested in using the command line, there's du which is described here. A: Unless it changed recently, baobab only shows directories; check out kdirstat for an alternative that actually shows files, coloured by type. A commandline alternative is du -a | sort -nr | head A: The solution that @UncleZeiv proposed is not working when there is really no more space left, since sort is using the /tmp folder when there are multiple lines to sort. du -a | sort -nr | head sort: write failed: /tmp/sortuCYq8E: No space left on device An alternative is a combination of the answer from @UncleZeiv and @Yoav Weiss, plus adding another path for the temporary location: sudo du -a | sort -nr -T /media/usb-key Finally, my preferred solution will be a human-readable one that doesn't depend on temp folder and list root directory (/): sudo du -ah --max-depth=1 / | sort -hr
    { "pile_set_name": "StackExchange" }