{ // 获取包含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\n\nA: \n\n

JavaScript Email Validation

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

\n\n\n\n\nA: You should use below regex which have tested all possible email combination\n function validate(email) {\n var reg = \"^[a-zA-Z0-9]+(\\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,15})$\";\n //var address = document.getElementById[email].value;\n if (reg.test(email) == false) \n {\n alert('Invalid Email Address');\n return (false);\n } \n }\n\nBonus tip\nif you're using this in Input tag than you can directly add the regex in that tag \nexample \n\n\nAbove you can see two attribute required & pattern\nin \nrequired make sure it input block have data @time of submit\n&\npattern make sure it input tag validate based in pattern(regex) @time of submit\nFor more info you can go throw doc\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635533\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"37\"\n}"}}},{"rowIdx":1967604,"cells":{"text":{"kind":"string","value":"Q: How to change the default enums serialization in Boost.Serialization By default in Boost.Serialization, enum types are serialized as a 32-bit integer. But I need to serialize some enum types as different width integer. I've tried to specialize the boost::serialization::serialize method, but it seems it doesn't work for enums.\nHere is my attempt:\n#include \n#include \n#include \n\nenum MyEnum_t\n{\n HELLO, BYE\n};\n\nnamespace boost \n{ \nnamespace serialization\n{\n\ntemplate< class Archive >\nvoid save(Archive & ar, const MyEnum_t & t, unsigned int version)\n{\n unsigned char c = (unsigned char) t;\n ar & c;\n}\n\ntemplate< class Archive >\nvoid load(Archive & ar, MyEnum_t & t, unsigned int version)\n{\n unsigned char c;\n ar & c;\n t = (MyEnum_t) c;\n}\n\n} // namespace serialization\n} // namespace boost\n\nBOOST_SERIALIZATION_SPLIT_FREE(MyEnum_t)\n\nint main(int argc, const char *argv[])\n{\n boost::asio::streambuf buf;\n boost::archive::binary_oarchive pboa(buf); \n\n buf.consume(buf.size()); // Ignore headers\n\n MyEnum_t me = HELLO;\n pboa << me;\n\n std::cout << buf.size() << std::endl; // buf.size() = 4, but I want 1\n\n return 0;\n} \n\n\nA: This probably doesn't work because enums aren't a real type, I don't think you can in general overload a function for a specific enum.\nYou could accomplish what you want by doing the conversion to char in the serialization of whatever object contains your MyEnum_t. You could also do what Dan suggested and encapsulate the enum in a first-class type for which you can overload the serialization. Something like:\nclass MyEnum_clone {\n unsigned char v_;\n MyEnum_clone(MyEnum_t v) : v_(v) {};\n operator MyEnum_t() const {return MyEnum_t(v_); };\n\n // serialization...\n};\n\nThat still likely won't be completetely transparent, though.\nHowever, I don't see why you care about how the type is serialized. Isn't the point of serializing that you don't have to care about the internal representation of the serialization, as long as you can restore the object correctly. The internal representation seems like a property of the archive.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635534\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967605,"cells":{"text":{"kind":"string","value":"Q: How to stop every 10 questions? Let's say I have a list of 100 questions in my database.\nI also have an array of shuffled questions with a index size of 0-99 which I use to reference to the database. It's so I don't shuffled the database.\nMy question is that the game starts at question 0 (10 for 2nd round, 20 for 3rd etc). I tried using a x mod 10 but I have it ordered so I check whether or not the question I'm up to has exceeded the limit for the round. (This stops the 11th question displaying on the screen) But since the game starts at question 0, the mod result is 0 and that would mean the end of the round. I need it to run question 0-9 stop at 10. next round 10-19 stop at 20.. etc\nI don't want to have to hardcode it like:\nrun question except if question number is 0, 10, 20... 80, 90 100.\nin one big if statement.\nAny help would be great.\n\nA: What about (x + 1) mod 10? If you offset by one you don't get 0 as a valid case.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635536\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967606,"cells":{"text":{"kind":"string","value":"Q: MYSQL performance issue concat in select or in where I used to develop databases under ms-sql, and now I've moved to mysql. Great progress. The problem is that I don't have any tool to see graphically the query execution plan... \nEXPLAIN doesn't really help. \nThus I require your advice on this one: \nI'll have a table with approximatively 50000 entries: \nThe two following queries are giving me the same result but I need to know which one will be the more efficient/quick on a huge database. \nIn the first one the concat is in the where, whereas in the second one it is in the select with a having clause. \nSELECT idPatient, lastName, firstName, idCardNumber \nFROM optical.patient \nWHERE CONCAT(lastName,' ',firstName) LIKE \"x%\"; \n\n\nSELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber \nFROM optical.patient \nHAVING formattedName LIKE \"x%\"; \n\nThanks in advance for your answers.\n\nA: In both versions, the query cannot use index to resolve WHERE and will perform full-table scan. However, they are equialent to:\nSELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber \nFROM optical.patient \nWHERE lastName LIKE \"x%\"; \n\nAnd it can use index on lastName\nIf you need to search by any of the 2 fields, use union\nSELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber \nFROM optical.patient \nWHERE firstName LIKE \"x%\"; \nUNION \nSELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber \nFROM optical.patient \nWHERE lastName LIKE \"x%\"; \n\n\nA: I don't believe you'll see any difference between these two queries since the CONCAT needs to be executed for all rows in both cases. I would consider storing formattedName in the database as well, since you can then add an index on it. This is probably the best you can do to optimize the query.\nAs an aside, you may find pt-visual-explain to help with visualizing EXPLAIN output.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635539\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967607,"cells":{"text":{"kind":"string","value":"Q: Authorize.Net SIM Method With Response using C# I have been trying to implement the Authorize.NEt SIM Method using the information given on their website and tutorials.But i have been only able to redirect to their payment gateway using the ddl provided by them.I need a way to get a response from SIM Method to know about the transaction status. \n\nA: Either use relay response or silent post (I am the author of that blog post).\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635546\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967608,"cells":{"text":{"kind":"string","value":"Q: Tooltip creation in android I am using ListView in my application. For each listitem I have to keep four images to its right side. When I click on each image it has to move to that particular page. Though the image specifies what it is meant for to know clearly I want to put a tooltip for each image. How can I create tooltip in android? Any help will be thankful to you. \nThank you\n\nA: Normally tool tips are used when you hover over something using mouse..Tooltips are not a normal practice in touch screen devices..\nIf you want to do it, you can use a longClickListener and show a toast message with your tip string in it..\nToast viewToast = Toast.makeText(this, \"Your tool tip\", Toast.LENGTH_SHORT);\nyourView.setOnLongClickListener(new OnLongClickListener() {\n @Override\n public void onLongClick(View v) {\n viewToast.show();\n }\n});\n\nwell this is one way to do..Hope it helps..\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635551\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967609,"cells":{"text":{"kind":"string","value":"Q: Trying to use EditorFor with an ICollection in an ASP.NET MVC3 View? I'm trying to display a class object in a Create view, where a property is an ICollection.\nFor example...\nnamespace StackOverflow.Entities\n{\n public class Question\n {\n public int Id { get; set; }\n ....\n public ICollection Tags { get; set; }\n }\n}\n\nand if the view was like a StackOverflow 'ask a question' page, where the Tags html element is a single input box .. I'm not sure how I could do that in an ASP.NET MVC3 view?\nAny ideas?\nI tried using EditorFor but nothing was displayed in the browser, because it's not sure how to render a collection of strings.\n\nA: Start by decorating your view model with the [UIHint] attribute:\npublic class Question\n{\n public int Id { get; set; }\n\n [UIHint(\"tags\")]\n public ICollection Tags { get; set; }\n}\n\nand then in the main view:\n@model StackOverflow.Entities.Question\n@Html.EditorFor(x => x.Tags)\n\nand then you could write a custom editor template (~/Views/Shared/EditorTemplates/tags.cshtml):\n@model ICollection\n@Html.TextBox(\"\", string.Join(\",\", Model))\n\nor if you don't like decorating, you could also specify the editor template to be used for the given property directly in the view:\n@model StackOverflow.Entities.Question\n@Html.EditorFor(x => x.Tags, \"tags\")\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635555\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":1967610,"cells":{"text":{"kind":"string","value":"Q: How can i implement CustumBinding configuration for this nettcpbinding configuration I have a nettcpbinding wcf service.It called 100000+ times in one second so there are more issue about performance. I must optimize this.\nMy first issue is: A newly accepted connection did not receive initialization data from the sender within the configured ChannelInitializationTimeout (00:00:05). As a result, the connection will be aborted. If you are on a highly congested network, or your sending machine is heavily loaded, consider increasing this value or load-balancing your server.\nI should set ChannelInitializationTimeout using CustomBinding. I read some sample but not implemented configuration.\nHow can implement below configuration to custombinding configuration?\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n\n \n \n \n\n \n \n \n \n \n \n \n \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\nA: I resolved this problem using customTcpBinding and Protocol Buffer for .Net but I understand to need high capacity network for using nettcpbinding fastly and efficient (10GBit Ethernet and Cat6 cable)\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \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 \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635556\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967611,"cells":{"text":{"kind":"string","value":"Q: How to encode accented char I am using php and getting some utf8 string from Javascript.\nI try to remove accent... by using a lot of difference function but still have troubles...\nWith iconv() I have wrong accent removing, with some encode() I have nothing...\nWhen I use serialize(mystring), my wrong char look like followings:\nxE3xA0 with A0 depending of the char.\nIt there any exhaustive map I can use ?\nIs there another method ?\n(I am under php 5.2 and no real control on the server so I cannot use intl/Normalize)\n\nEdit :\ncode like this doesnt works (otherwise it would be ugly but efficient for short term)\n $string = mb_ereg_replace('(À|Á|Â|Ã|Ä|Å|à|á|â|ã|ä|å)','a',$string);\n\n\nA: This should do it:\niconv(\"UTF-8\", \"ASCII//TRANSLIT\", $text)\n\nIf this does not work for you, see \"How do I remove accents from characters in a PHP string?\"\n\nA: For simple cases, like words or small sentences, I always use Sjoerd answer and it does work. For more complex cases such as long and complex paragraphs, possibly including some html, I use HTMLPurifier library with this set of options\nrequire_once dirname(__FILE__) . '/htmlpurifier/HTMLPurifier.auto.php';\n$config = HTMLPurifier_Config::createDefault();\n$config->set('Core.Encoding', 'utf-8');\n$config->set('Core.EscapeNonASCIICharacters', true);\n$config->set('Cache.SerializerPath', sys_get_temp_dir());\n$config->set('HTML.Allowed', 'a[href],strong,b,i,p');\n$config->set('HTML.TidyLevel', 'heavy');\n$purifier = new HTMLPurifier($config);\necho $purifier->purify('òàòààòòààè');\n\nIt will replace any non ASCII char to its corresponding HTML entity, in this way you get rid of all encoding problems for such strings. For instance òàòààòòààè will become &#224;&#242;&#224;&#242;&#232;&#224;&#242;&#232;&#224;&#242;&#232; which is encode friendly because it doesn't contain any non-ASCII char.\nP.S. in any case don't use preg_replace for this kind of tasks, it's unsafe because you can't list all the possible non ASCII chars in a regex (or better, you could but it's pretty error prone task).\nP.P.S. here is a good document on utf-8 encoding and conversion in php taken from HTMLPurifier website.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635557\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967612,"cells":{"text":{"kind":"string","value":"Q: How to pass a boolean field from one activity to a class? How to pass, at any time!, a boolean field from one activity to a class?\n\nA: Pass to Activity:\nIntent i = new Intent(getBaseContext(), NameOfActivity.class);\ni.putExtra(\"my_boolean_key\", myBooleanVariable);\nstartActivity(i)\n\nRetrieve in Second Activity:\nBundle bundle = getIntent().getExtras();\nboolean myBooleanVariable = bundle.getBoolean(\"my_boolean_key\");\n\n\nA: You can create your own singleton class that both your Activity and other class can access at any time. You have to be careful with it because it does add a layer of global variables (which people tend to not like), but it works.\npublic class MyBoolean{\n\n private static final MyBoolean instance = new MyBoolean();\n\n private boolean boolValue = false;\n\n private MyBoolean(){}\n\n public static MyBoolean getInstance(){\n return instance;\n }\n\n public boolean getValue(){\n return boolValue;\n }\n\n public void setValue(boolean newValue){\n boolValue = newValue;\n }\n}\n\nCall MyBoolean.getInstance() and you can use the methods inside which will be in sync with your whole program.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635559\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967613,"cells":{"text":{"kind":"string","value":"Q: Speed optimize - which is better? Let's say that we build a game and we have a player character. That character in the game will do many actions, like walking, jumping,attacking, searching target etc : \npublic class Player extends MovieClip\n{\n public function Player(){}\n private function walk(){}\n private function attack(){}\n private function jumping(){}\n ...\n ..\n .\n private function update(){}\n}\n\nNow, for every state or action we want to execute a different code. Now, how to do this? I can think of 3 ways.\n1.With events - as I understand, event system is costly to use, so I'll skip this one.\n2. With simple checks in the update() - something like if(currentStateAction) {doSomethingHere} or with switch statement. But what if the actions are not mutually exclusive, e.g. it can jump and attack in the same time? Than we have to use if() for every action, e.g. to do checks for every frame.\n3. I came up with this solution on my own and I need to know is this better than option number 2:\n//declare Dictionary. Here we will add all the things that needs to be done\npublic var thingsToDo:Dictionary = new Dictionary(true);\n\n//in the update function we check every element of the dictionary\nprivate funciton update():void\n{\n for each(item:Function in thingsToDo)\n {\n item.call();\n }\n}\n\nNow, every time we need to do something, we add a element, like thingsToDo[attack]=attack; \nOr if we don't want to do something anymore: delete thingsToDo[attack];\nIn this ... system ... you don't need to check every frame what the object should do, but instead, you only check when is needed. It's like a event driving system. Say for example, the object don't need to check for attack until new enemy is spawn. So. when spawing a new enemy, you will add thingsToDo[attack] = attack; and etc.\nSo the question: Is this faster than option number 3? Any idea how to do this checking differently?\nThanks. \n\nA: You should probably focus on making it work the way you want (flexible, easy to maintain and modify), instead of making it as fast as possible. This is very unlikely to ever be a real bottleneck.\nPremature optimization is the root of all evil, and all that.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635562\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967614,"cells":{"text":{"kind":"string","value":"Q: Embed MS Excel in SWF / Silverlight For a project requirement, I want to make available editing of an excel file through browser.\nThe only possible ways that I could think of was by embedding the excel file either in Flash or Silverlight. I am building my project on asp.net mvc3 c#.\nI wanted to know that is there a way by which this could be achieved? \nI shall be happy to start an open source project is need be so that people who are interested can collaborate together.\nAny pointer would be great.\nMuch thanks.\n\nA: Well on Windows Live Skydrive there is an Silverlight Excel app, but that requires windows live accounts... There are other controls out there I'm sure, just most will cost something.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635566\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967615,"cells":{"text":{"kind":"string","value":"Q: Most appropriate way to develop a server on limited resources I am facing a problem which seems to have few, and especially simple solutions.\nTo get to the point; I have written a client application on Windows using C++.\nThis client application takes input from the user, and is supposed to send this\ninformation to a server, which find users who's inputs match each other - like matchmaking.\nHow can I (an indie developer) with most ease solve this problem, IF and only if I\ncannot host the server application myself, and do not want to spend money on renting\na whole virtual private server?\nMost preferred, I want to write this server using sockets in PHP and just rent a\nweb-server with unlimited bandwidth, but it seems to have far too many restrictions,\nrelated to timeouts (PHP's set_time_limit, Apache's timeout value and the internal OS\ntimeout value).\nSo to sum up the question, and in a generic form; How can I as an indie developer create\na server application which do not require using my own bandwidth and without expensive purchases for items such as a virtual private server.\n\nA: You can just code your server application in PHP as a webservice.\nIn your client application, instead of connecting through sockets and a using a home-made protocol, you just have to use the HTTP REST webservice you created. It seems to me even easier than coding a whole server.\nMaybe you absolutely want to use socket on your server, but you didn't specify that in your question.\n\nA: You can try a cloud hosting provider, such as Rackspace.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635567\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967616,"cells":{"text":{"kind":"string","value":"Q: Can ReSharper be used when editing SSIS script tasks? I have ReSharper 6 installed and integrated with Visual Studio 2008 and Visual Studio 2010. I'm editing SSIS packages in VS2008 and some of them contain script tasks. When editing the script task, a Microsoft Visual Studio Tools for Applications (VSTA) application is launched which is lacking ReSharper integration. Does anyone know if ReSharper can be installed and used in this context?\n\nA: Resharper works with Business Intelligence Development Studio for SQL Server 2012, primarily because SQL Server 2012 now uses the integrated Visual Studio shell for editing script files.\nAnything before SQL Server 2012 does not use the integrated shell. VSTA and the isolated shell do not load additional plugins like Resharper, which is why it won't show up in BIDS for SQL Server 2008 R2 or earlier.\n(In fact, the SSIS editor will create an entire temporary Visual Studio project and load it into the separate IDE as a complete, buildable solution.)\n\nA: to expand on SpikeX's answer, the Visual Studio 2008 used for SSIS is a Shell Version of Visual Studio 2008. It won't support anything beyond Business Intelligence Studio projects. (Akin to the Express version of VS2008) Since it's not a full version of VS, it can't support Resharper.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635570\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967617,"cells":{"text":{"kind":"string","value":"Q: How to set transparency color of the WPF Window? Is there any way to set one specific color to be transparent for the whole WPF window?\n\nA: You don't need to. Transparency in WPF doesn't work using mask colors like in Winforms- just set the background to Transparent, and AllowsTransparency to true. If you want different shaped windows, you can use the technique described here: http://devintelligence.com/2007/10/shaped-windows-in-wpf/\n\nA: We can make a transparent WPF window by using a XAML like follows.\n\n......\n\n\n\nA: No. WPF supports alpha-channel transparency, not bitmap mask transparency. \nThere are people who have attempted to work around this, but only on a per-image basis.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635573\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967618,"cells":{"text":{"kind":"string","value":"Q: DB Migrate not reflected on heroku I recently created a db migration which works fine locally. I pushed to heroku and ran \nheroku rake db:migrate\n\nWhilst the command doesn't seem to throw an error, I can see the database hasn't been updated with the column I've tried to add to a table. I've tried running heroku rake db:setup but to no avail. Additionally, I've also tried restarting heroku after both commands but it still doesn't work.\nAnybody have this problem before?\n\nA: First try to be specific with heroku rake db:migrate:up VERSION=xxx\nI had similar problems and what I did was to reset the database, if that doesn't work, I would migrate down all migrations (one by one) and add them up again, of course only if you can afford to loose all your data, alternatively download the database and investigate. The problems I had with recreating the db were related to the fact that I was changing the migrations and that in heroku I had a shared database.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635577\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967619,"cells":{"text":{"kind":"string","value":"Q: Dubugging GAC DLL with IIS 5 I'm trying to debug a DLL in the GAC with VS 2008 / XP / IIS 5 configuration. Tried to copy the DLL in the C:\\\\assembly\\GAC_MSIL but the symbols still doesnt get loeded :-( Also this interesting post about debugging GAC without having to copy the PDB file into the GAC : http://www.elumenotion.com/Blog/Lists/Posts/Post.aspx?ID=23 \nBut since I run IIS 5, there's no trace of the w3wp.exe (which seems to be only in IIS 6 and newer). Do you know a trick so I can attach to my web page and trace a referenced DLL ? \n\nA: Finally, turns out that the solution without copying the .pdb file is working. Only thing is to attach to the \"aspnet_wp\" process instead of the \"w3wp.exe\" mentionned in the post.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635579\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967620,"cells":{"text":{"kind":"string","value":"Q: Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)? am learning vectors and made a bit of code that selects random numbers i can use for buying lottery tickets here in Netherlands. But although it runs, the compiler is warning me about 'conversion from 'time_t' to 'unsigned int, possible loss of data'.\nCan anyone spot what is causing this? I haven't even defined any unsigned int in this code; int i by default is a signed int as i understand. Thanks for insight. \n#include \n#include \n#include \n#include \nusing namespace std;\n\nvoid print_numbers();\nstring print_color();\n\nint main() {\nsrand(time(NULL));\nprint_numbers();\nstring color = print_color();\ncout << color << endl;\n\nsystem(\"PAUSE\");\nreturn 0;\n}\n\n//Fill vector with 6 random integers. \n//\nvoid print_numbers() {\nvector lucky_num;\n\nfor (int i = 0; i < 6; i++) {\n lucky_num.push_back(1 + rand() % 45);\n cout << lucky_num.at(i) << endl;\n}\n}\n\n//Select random color from array.\n//\nstring print_color() {\nstring colors[6] = {\"red\", \"orange\", \"yellow\", \"blue\", \"green\", \"purple\"};\nint i = rand()%6;\nreturn colors[i];\n}\n\nExact compiler message: warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data. Line 11.\n\nA: Because time_t happens to be larger in size than unsigned int on your particular platform, you get such a warning. Casting from a \"larger\" to a \"smaller\" type involves truncating and loss of data, but in your particular case it doesn't matter so much because you are just seeding the random number generator and overflowing an unsigned int should occur for a date in the very far future.\nCasting it to unsigned int explicitly should suppress the warning:\nsrand((unsigned int) time(NULL));\n\n\nA: time_t is a 64 bit value on many platforms to prevent the epoch time eventually wrapping while unsigned int is 32 bits.\nIn your case, you don't care cause you're just seeding the random number generator. But in other code, if your software ever deals in dates past 2038, you could have your time_t truncated to a 32-bit pre 2038 date when you cast to a 32-bit value.\n\nA: time returns a time_t object.\nsrand is expecting an unsigned int.\n\nA: srand(time(NULL));\n\nThis line can overflow if the return value from time exceeds the representation range of an unsigned int, which is certainly possible.\n\nA: void srand ( unsigned int seed );\ntime_t time ( time_t * timer );\ntypedef long int __time_t;\n\nlong int is not the same as a unsigned int. Hence the warning.\n(from stackoverflow\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635580\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"5\"\n}"}}},{"rowIdx":1967621,"cells":{"text":{"kind":"string","value":"Q: unknown property while using a list of class in Vf page i have a class\npublic with sharing class CAccountRep {\nstring sageAccountNo {get;set;}\nstring clientName {get;set;}\nstring name {get;set;}\ninteger noofdays {get;set;}\nstring billableUnits {get;set;}\ndecimal dailyChargeRate {get;set;}\nstring nominalCode {get;set;}\nstring practice {get;set;}\nstring taxFlag {get;set;}\nstring ProjectId {get;set;}\nstring PONumber {get;set;}\n\npublic CAccountRep(String CrSageAc,String CrClientN,string CrName,integer Crnoofdays,string crbillableunits,decimal CrDecimalChargeRate,string crNominalCode,string CrPractice, String CrTaxFlag,String CrProjectId, String CrPONumber)\n{\n sageAccountNo=CrSageAc;\n clientName=CrClientN;\n name=CrName;\n noofdays=Crnoofdays;\n billableUnits=crbillableunits;\n dailyChargeRate=CrDecimalChargeRate;\n nominalCode=crNominalCode;\n practice=CrPractice;\n taxFlag=CrTaxFlag;\n ProjectId=CrProjectId;\n PONumber=CrPONumber;\n\n}\n\n }\n\nIam creating a object of this class and passing out the parameters into this class\n public List AR { get;set; }\n\n public list getAR()\n { \n if(AR!= null)\n return AR ;\n else return null;\n }\n\n Using the follwing code to create the object of the class\n\n CAccountRep CRep=new CAccountRep(projectList[0].Sage_Account_Number__c,projectList[0].Client_Name__c, Cname,enoOfBillableDays,projectList[0].BillableUnits__c,AssConlist[0].Daily_Charge_Rate_of_Consultant__c,AssConlist[0].Nominal_Code__c,projectList[0].C85_Practice__c,projectList[0].Tax_Flag__c,projectList[0].Project_ID__c,projectList[0].PO_Number__c);\n\n AR.add(CRep);\n\nIn my VF page i am trying to display the contents of the list AR.\nBut i get an error Unknown Propery CAccountRep.ProjectId while saving the VF page.\n\n \n \n\n \n \n \n
{!TCrep.ProjectId}
\n\nI can get the output like this if i just give {!TCrep}\nCAccountRep:[PONumber=null, ProjectId=C85_JPMC1 _A-0083, billableUnits=null, clientName=001A000000YJFhdIAH, dailyChargeRate=null, name=Change Order 10002011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=Administration, sageAccountNo=null, taxFlag=null]\nCAccountRep:[PONumber=null, ProjectId=C85_BBCWW _A-0084, billableUnits=null, clientName=001A000000cwgIlIAI, dailyChargeRate=null, name=Secure Desktop v012011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=null, sageAccountNo=null, taxFlag=null]\nCAccountRep:[PONumber=null, ProjectId=C85_JPMC1 _A-0083, billableUnits=null, clientName=001A000000YJFhdIAH, dailyChargeRate=null, name=Change Order 10002011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=Administration, sageAccountNo=null, taxFlag=null]\n\nAny ideas on how to get it display correctly?\n\nA: I think the compiler is getting confused because you have 2 public getters in it's opinion i.e. both of these lines:\npublic List AR { get;} // just removed set; for now\n\npublic list getAR()\n\nWould be called from a Visualforce page when you use the following syntax in the page:\n{!AR}\n\nTry doing this instead:\npublic List AR { get{\n return AR ; // if AR is null it returns null so the if statement was redundant\n\n}set; }\n\nAnd remove the getAR() method. You should also mark the class member variables that you'd like to be visible as public e.g.\npublic string ProjectId {get;set;}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635588\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967622,"cells":{"text":{"kind":"string","value":"Q: Detect if css position overflow is working? As iOS5 beta has fixed css property overflow: scroll and overflow: auto, I’d like to target the older iOS versions with Javascript.\nIs there a way to check with JS if the property is actually working or not? Trying to get the style property does alert the correct value in both Mobile Safaris, but in the current version it requires a two-finger scrolling to work.\n\nA: I don't know of a way to check if the scroll property is working but you could check the user-agent to determine which version of iOS they're running (3.2 in the following example):\nMozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635589\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967623,"cells":{"text":{"kind":"string","value":"Q: store a Byte[] in an sqlite db in small chunks? I would like to store a large Byte[] in my SQLite database.\nAndroid has a limit to how much RAM each app can use, so I figured the best way to skirt around this limitation is to write the file in smaller chunks.\nIs it possible to use a stream to access my file, and append to my database Byte[] in small pieces? (without loading the Byte[] into memory to append)\n\nA: Store the data in files in your app/sdcard and keep a reference in SQLite - you cannot append to BLOBs in SQLite (at least without pre-allocating the size with zeroblob() and using the NDK) - besides - how would you read it back? The only API made available in the SDK will attempt to read the entire BLOB back as a byte[].\nTypically you want to implement ContentProvider#openFile(..) properly.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635592\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967624,"cells":{"text":{"kind":"string","value":"Q: How to do a second transform on the output of an XSLT template I have only basic XSLT skills so apologies if this is either basic or impossible.\nI have a paginator template which is used everywhere on the site I'm looking at. There's a bug where one particular search needs to have a categoryId parameter appended to the href of the page links. I can't alter the paginator stylesheet or else i would just add a param to it. What I'd like to do is apply the template as is then do a second transform based on its output. Is this possible? How do others normally go about extending library templates?\nSo far I've thought about doing a recursive copy of the output and applying a template to the hrefs as they are processed. The syntax for that escapes me somewhat, particularly as I'm not even sure it's possible. \n\nEdit - Between Dabbler's answer and Michael Kay's comment we got there. Here is my complete test.\n \n \n\n \n \n \n \n\n \n \n foo\n \n\n \n \n \n \n \n\n \n \n \n \n \n \n\n\n\n\nA: Here is a complete example how multi-pass processing can be done with XSLT 1.0:\n\n \n \n\n \n \n \n \n \n\n \n \n \n \n \n\n \n \n \n \n\n \n \n\n \n \n \n\n \n \n \n \n \n \n\n \n \n \n\n\nwhen this transformation is applied on the following XML document:\n\n 01\n 02\n 03\n 04\n 05\n 06\n 07\n 08\n 09\n 10\n\n\nthe wanted result (each num is multiplied by 2 and in the next pass 3 is added to each num) is produced:\n\n 5\n 7\n 9\n 11\n 13\n 15\n 17\n 19\n 21\n 23\n\n\n\nA: It's possible in XSLT 2; you can store data in a variable and call apply-templates on that.\nBasic example:\n\n \n\n\n\nAnd somewhere in your stylesheet have a template that matches Elem. You can also use a separate mode to keep a clear distinction between the two phases (building the variable and processing it), especially when both phases use templates that match the same nodes.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635593\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"17\"\n}"}}},{"rowIdx":1967625,"cells":{"text":{"kind":"string","value":"Q: ColdFusion not \"seeing\" my components I have a directory structure similar to\n\nC:...\\wwwroot\\project\\testPage.cfm \n\n\n\nTest Page\n\n\n\n\n\n \n\n Pick as many as you like: \n \n \n \n \n \n \n
\n
\n\n
\n\n\n\n\n\nC:...\\wwwroot\\project\\TestCFC.cfc\n\n\n \n remote function One(whatever){\n return whatever; \n }\n \n\n\nand for some reason the ColdFusion server won't \"see\" my component. I get this error.\n\nI wasn't using mappings as my component was located in the same directory as my page. This worked at one point, and it seems as though the CF server has just dropped a setting or something. Anyone have some idea as to why this is happening?\n\nA: Well, since your CFC is located in C:...\\wwwroot\\project\\TestCFC.cfc wouldn't the path (FQN) be project.TestCFC?\nDid you try this:\n
\n\n\nA: This is not an answer, per-se; but a suggestion for investigation.\nWhat's the URL that is actually being requested by the browser under the hood? And what's the HTTP error you get?\nAlso: I doubt CF mappings are relevant here because JS is mapping a client-side HTTP request, and CF mappings are just so CF can access resources on its local system (ie: server side). If you need to map anything to the location of the URL, it needs to be a web server virtual directory, not a CF mapping.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635599\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967626,"cells":{"text":{"kind":"string","value":"Q: Detail property of SoapException set in .NET Web service ends up as null in Java web service client So I wrote simple asmx .NET web service in C#. All exceptions are caught and re-thrown as SoapException with Detail property set up to XmlNode that contains three sub-nodes with additional information about exception that has occurred. On Java side server exceptions surface as SoapFaultException. But when I try to print ex.getFault().getDetail() it's appears to be null. So my question is why is this happening or what am I doing wrong?\nFinally managed to get raw SOAP response:\nHTTP/1.1 500 Internal Server Error\nCache-Control: private\nContent-Type: text/xml; charset=utf-8\nServer: Microsoft-IIS/7.0\nX-AspNet-Version: 2.0.50727\nX-Powered-By: ASP.NET\nDate: Tue, 04 Oct 2011 20:13:21 GMT\nContent-Length: 2143\n\n\n\n\n\nsoap:Server\nSystem.Web.Services.Protocols.SoapException: ...\nCustomSoapException\n\n BackendException\n Internal application error occured. Please contact application developer for quick resolution.\n Exception details: ....\n \n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635600\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967627,"cells":{"text":{"kind":"string","value":"Q: Variable not defined error in Classic ASP (VBScript) Microsoft VBScript runtime error '800a01f4'\nVariable is undefined: 'product_id'\n/Vital/form/products.asp, line 64 \nI am using option explicit and I have defined the variable as\nDim product_id\n\nproduct_id=Request.Form(\"product_id\")\n\nIs this a problem with IIS or sql server 2003? Actually its working fine when i access my sql server 2008 database from localhost. But the problem comes when my client uploads the asp file to web server and try to access mysql 2003 database.\n\nA: Without seeing more code, I have to guess and I guess you define the variable inside a function, for example:\nFunction Foo\n Dim product_id\n\n '......\nEnd Function\n\nThen having the line product_id=Request.Form(\"product_id\") outside the function will indeed result in error, as it's only local to that function.\nIt got nothing to do with IIS or database - pure VBScript issue.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635604\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967628,"cells":{"text":{"kind":"string","value":"Q: error while pressuing multiple times physical back button of device in android I am facing this error while I am pressing back multiple times on the physical button of device.\nThis is my log:\n10-03 18:47:50.403: ERROR/ActivityManager(98): Reason: keyDispatchingTimedOut\n10-03 18:47:50.403: ERROR/ActivityManager(98): Load: 4.16 / 3.77 / 2.21\n10-03 18:47:50.403: ERROR/ActivityManager(98): CPU usage from 141136ms to 62ms ago:\n10-03 18:47:50.403: ERROR/ActivityManager(98): system_server: 8% = 6% user + 2% kernel / faults: 3797 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): dhd_dpc: 2% = 0% user + 2% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): om.htc.launcher: 1% = 1% user + 0% kernel / faults: 1095 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): mediaserver: 1% = 0% user + 0% kernel / faults: 1610 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): d.process.acore: 0% = 0% user + 0% kernel / faults: 4617 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): e.pluginmanager: 0% = 0% user + 0% kernel / faults: 389 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): akmd: 0% = 0% user + 0% kernel / faults: 69 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): adbd: 0% = 0% user + 0% kernel / faults: 331 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): logcat: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): id.defcontainer: 0% = 0% user + 0% kernel / faults: 153 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): tc.RosieUtility: 0% = 0% user + 0% kernel / faults: 81 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): android.vending: 0% = 0% user + 0% kernel / faults: 61 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.bg: 0% = 0% user + 0% kernel / faults: 47 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): e.process.gapps: 0% = 0% user + 0% kernel / faults: 62 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.bgp: 0% = 0% user + 0% kernel / faults: 67 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): s:FriendService: 0% = 0% user + 0% kernel / faults: 47 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): equicksearchbox: 0% = 0% user + 0% kernel / faults: 45 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): wpa_supplicant: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): droid.apps.maps: 0% = 0% user + 0% kernel / faults: 50 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.svox.pico: 0% = 0% user + 0% kernel / faults: 40 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): suspend: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): events/0: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): cabc_work_q: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): panel_on/0: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): m.android.phone: 0% = 0% user + 0% kernel / faults: 18 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): ksoftirqd/0: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): .android.htcime: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): re-initialized>: 0% = 0% user + 0% kernel / faults: 45 minor 1 major\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.android.mms: 0% = 0% user + 0% kernel / faults: 13 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): get.clockwidget: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): atmel_wq: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): ls_wq/0: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): rild: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): zygote: 0% = 0% user + 0% kernel / faults: 31 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): d.process.media: 0% = 0% user + 0% kernel / faults: 10 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.music: 0% = 0% user + 0% kernel / faults: 7 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): ogle.android.gm: 0% = 0% user + 0% kernel / faults: 9 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.fd.httpd: 0% = 0% user + 0% kernel / faults: 8 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): d.apps.uploader: 0% = 0% user + 0% kernel / faults: 8 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): init: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): netd: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): android.updater: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): roid.worldclock: 0% = 0% user + 0% kernel / faults: 7 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): c.android.Stock: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.fm: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): MessageUploader: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): ec.android.jbed: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): roid.footprints: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): android.browser: 0% = 0% user + 0% kernel / faults: 7 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): tc.android.mail: 0% = 0% user + 0% kernel / faults: 6 minor\n10-03 18:47:50.403: ERROR/ActivityManager(98): +flush-179:0: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): +om.amritbani.tv: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): +om.amritbani.tv: 0% = 0% user + 0% kernel\n10-03 18:47:50.403: ERROR/ActivityManager(98): TOTAL: 24% = 14% user + 8% kernel + 0% softirq\n\n\nA: It is looked like that this error occur because of the emulator. This is error of the emulator.\nCreate New Emulator and try your code again.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635607\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967629,"cells":{"text":{"kind":"string","value":"Q: How do I create Windows in D with win32? Hello I'm trying to open a window with win32 in D, and I've got a little problem. The program crashes when I call CreateWindowA.\nHere is my code :\nthis.fenetrePrincipale = CreateWindowA(this.classeFenetre.lpszClassName, toStringz(title), WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, null, null, this.hInstance, null);\n\nwith:\nthis.classeFenetre.lpszClassName = toStringz(\"classeF\");\nthis.hInstance = GetModuleHandleA(null);\n\nand \nstring title = \"test\";\n\nWhen I launch the exe, the program crashes and I've got:\n\nProcess terminated with status -1073740791\n\non code::blocks.\n\nA: The error code -1073740791 (or 0xc0000409) is caused by a stack buffer overrun (not overflow, as in running out of stack, but writing to a place in stack where you are not supposed to write to).\nThe call that you've shown is looks OK. But you didn't show us the class registration code, and more importantly, the WndProc you register. I am not sure how you do it in D, but your WndProc needs to be declared __stdcall, so that it matches the calling convention assumed by Windows. This is a common problem that causes crashes on CreateWindow.\n\nA: Yeah that was the problem : \nI didn't declared the WndProc as __stdcall\nthe way you do that in D is \nextern (Windows) int windowRuntime(HWND window, UINT message, WPARAM wParam, LPARAM lParam)\n\nthanks for your help.\n\nA: I would suggest using gtkD or QTD instead of Win32. The two widget libraries are mature and powerful, yet very simple to use. And you have cross-platform support as well.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635609\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":1967630,"cells":{"text":{"kind":"string","value":"Q: Run JQuery after Specific updatePanel fires I have a script that runs once an update panel fires:\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);\n function EndRequestHandler(sender, args) {\n initDropSearch();\n }\n function initDropSearch() {\n var search = jQuery(\"#searchBar div.productSearchFilter\");\n\n if (search.length > 0) {\n\n var grid = search.find(\"table.gridView\");\n\n if (search.next().val() != \"open\") {\n\n search.animate({\n height: ['toggle', 'easeOutBounce'],\n opacity: 'toggle'\n }, 1000)\n\n .next().val(\"open\");\n\n } else {\n\n search.show();\n\n }\n }\n}\n\nOnce the results of a search have loaded, the container drops down and bounces.\nIt works perfectly - that is until another update panel is triggered on the same page - in which case the search panel opens again.\nWhat I need to do is only run the script when a specific updatePanel fires.\nIs there a way to do this?\n\nA: Do the sender or args contain data about the UpdatePanel that triggered the EndRequestHandler?\nIf so just check which one triggered it and only fire your code based on that.\nfunction EndRequestHandler(sender, args) {\n if (((UpdatePanel)sender).ID == \"UpdatePanel1\") {\n initDropSearch(); \n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635623\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967631,"cells":{"text":{"kind":"string","value":"Q: android - javah doesn't find my class I am having troubles generating the C header file for JNI using javah. \nHere's the script I use while standing in the \\bin directory:\njavah -classpath C:\\PROGRA~2\\Android\\android-sdk\\platforms\\android-8\\android.jar com.test.JniTest\n\nAs return I get:\nERROR: Could not find class file for 'com.test.JniTest'.\n\nEven though the class JniTest certainly is in \\com\\test.\nWhat am I doing wrong?\n\nA: You specify the classpath to contain only android.jar.\nYou also need to include the location where your classes are stored. In your case it is the current directory, so you need to use . (separated by ; on Windows). The invocation should look like this:\njavah -classpath C:\\PROGRA~2\\Android\\android-sdk\\platforms\\android-8\\android.jar;. com.test.JniTest\n\n\nA: If you are on Linux or MAC-OS, use \":\" to separate the directories for classpath rather than \";\" character: Example:\njavah -cp /Users/Android/android-sdk/platforms/android-xy/android.jar:. com.test.JniTest\n\n\nA: You should change the directory to \\bin\\classes; then, run the following command:\njavah -classpath C:\\PROGRA~2\\Android\\android-sdk\\platforms\\android-8\\android.jar;. com.test.JniTest\n\nI'm using the following command file to generate headers:\njHdr.cmd on my desktop:\n@echo on\nSET PLATFORM=android-8\nSET ANDROID_SDK_ROOT=C:\\Android\\android-sdk\nSET PRJ_DIR=D:\\Workspaces\\sqLite\\raSQLite\nSET CLASS_PKG_PREFIX=ra.sqlite\ncd %PRJ_DIR%\\bin\\classes\njavah -classpath %ANDROID_SDK_ROOT%\\platforms\\%PLATFORM%\\android.jar;. %CLASS_PKG_PREFIX%.%~n1\npause\n\n adjust variables to your needs ...\n put this file on your desktop, then drag you .java file from eclise to jHdr.cmd, result is under %PRJ_DIR%\\bin\\classes directory\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635624\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"13\"\n}"}}},{"rowIdx":1967632,"cells":{"text":{"kind":"string","value":"Q: EF 4.1 Code First : How to load entity references into memory? I just started working with EF 4.1 Code First and noticed that by default, references (navigation properties), are not loaded into memory with a POCO entity you queried with LINQ-to-Entity. I have had no success with making the referenced entities load using DbEntityEntry.Reference. When I call DbReferenceEntry.Load, the following exception is thrown:\n\n\"There is already an open DataReader associated with this Command which must be closed first.\"\n\nClosing a DataReader is not something I really want to have to do when I'm in the middle of several LINQ queries. \nFor example, the following will not work:\nusing (db1 = new NorthindDbContext(new SqlConnection(this.NORTHWIND))) { \norders = db1.Orders.Where(o => !(o.CustomerId == null || o.ShipperId == null || o.EmployeeID == null));\n foreach (var o in orders) {\n Shipper s = o.Shipper;//exception: \"There is already an open DataReader associated with this Command which must be closed first.\"\n DbEntityEntry entry = db1.Entry(o);\n DbReferenceEntry shipper_reference = entry.Reference(\"Shipper\");\n if (!shipper_reference.IsLoaded) {\n shipper_reference.Load(); \n }\n }\n }\n\nHere is the Order class:\npublic partial class Order\n{\n public System.Int32 ID { get; set; } \n public System.Nullable OrderDate { get; set; }\n public System.Nullable RequiredDate { get; set; }\n public System.Nullable ShippedDate { get; set; } \n public System.Nullable Freight { get; set; } \n public Employee Employee { get; set; }\n public Int32 CustomerId { get; set; }\n public Customer Customer { get; set; }\n public Int32 EmployeeID { get; set; }\n /// \n /// marked virtual for lazy loading\n /// \n public virtual Shipper Shipper { get; set; }\n public Int32 ShipperId { get; set; }\n} \n\nI have tried marking the Order.Shipper property as virtual, and I still get the same exception if when I run the code.\nThe ObjectQuery.Include method, does work:\n[TestMethod] \n//configure MARS here?\n//Order.Shipper is not marked virtual now\n//...\n using (db = new NorthindDbContext(new SqlConnection(this.NORTHWIND))) { \n db.Orders.Include(o => o.Shipper)\n.Where(o => !(o.CustomerId == null || o.ShipperId == null || o.EmployeeID == null));\n foreach (var o in orders) {\n Shipper s = o.Shipper;//null\n DbEntityEntry entry = db.Entry(o);\n DbReferenceEntry shipper_reference = entry.Reference(\"Shipper\");\n if (!shipper_reference.IsLoaded) {\n shipper_reference.Load();//\"There is already an open DataReader associated with this Command which must be closed first.\"\n }\n\n\n }\n\nWith EF 4.1 Code First, how do you make a referenced entity load into memory? \n\nA: If you need multiple database reads work in the same time you must allow MARS on your connection string but your real problem is elsewhere.\nEF doesn't load navigation properties by default. You must either use lazy or eager loading. Lazy loading needs all navigation properties in entity to be virtual:\npublic class Order\n{\n ...\n\n public virtual Shipper Shipper { get; set; }\n}\n\nOnce lazy loading and proxy creation is allowed on context (default) your property will be automatically loaded when first time accessed by your code. This access must happen within scope of the same context used to load the order (you can still meet the error with opened DataReader here).\nOther way is to load Shipper directly with Order by using eager loading:\nvar query = context.Orders.Include(o => o.Shipper)...\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635628\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967633,"cells":{"text":{"kind":"string","value":"Q: Loaded JavaScript files and dynamically events Anyone knows a tool that collect all the js files that are loaded with a web page?\nI know that Firebug through the script tab gives me all the js files downloaded with the web page, but I have to copy the URL from the tab and make the download one by one.\nAnother question, if I have one element in the web page, for example:\n \n\nHow can I know all the events associated with this element? Events that were add dynamically for example in the onsubmit event through JavaScript, for example.\ndocument.getElementById(\"test1\").onclick = \"function()....\"\n\n\nA: First Question: Chrome's inspector tool \nSecond Question: refer to this post: Inspect attached event handlers for any DOM element\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635630\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967634,"cells":{"text":{"kind":"string","value":"Q: SQL- Identify nullable values I am relatively new to SQL queries. \nI have a large number of tables in my SQL Database ( over 1500 )\nMy question is as follows:\nI need to identify columns which are nullable from all the tables which have default values?\nHow can I go about it for all the tables?\nAny help or tutorial for the same would be also very helpful.\nThank you\n\nA: You can use information_schema to get this data, the columns \"COLUMN_DEFAULT\" and \"IS_NULLABLE\" will give you what you need.\nSELECT *\nFROM information_schema.columns c with (Nolock)\n\n\nA: Use the self-describing features of SQL Server :-\nSELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS \nWHERE IS_NULLABLE = 'YES'\nOR COLUMN_DEFAULT IS NOT NULL\n\n\nA: SELECT\n OBJECT_NAME(c.object_id), *\nFROM\n sys.columns c\n JOIN\n sys.default_constrainst dc ON c.columnid = dc.parent_column_id AND c.object_id = dc.parent_object_id\nWHERE\n c.is_nullable = 1\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635632\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967635,"cells":{"text":{"kind":"string","value":"Q: How can I check if a generic method parameter is a value type? Is there a way to check if a variable is value type of reference type?\nImagine:\nprivate object GetSomething(params T[] values) \n{\n foreach (var value in values)\n {\n bool is ValueType; // Check if 'value' is a value type or reference type\n }\n}\n\n\nA: bool isValueType = typeof(T).IsValueType;\n\nJob done... it doesn't matter if any of the values is null, and it works even for an empty array.\n\nA: Your condition will look like\nvar cond = false;\nif(value != null) \n cond = value.GetType().IsValueType\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635640\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"9\"\n}"}}},{"rowIdx":1967636,"cells":{"text":{"kind":"string","value":"Q: SQL Query Join 2 tables I'm new to SQL and was reading on joins but i'm a bit confused so wanted help....\nI have a table called student_sport which stores StudentID and SportID\nI have another table which stores details of matches... so basically sportsID,MatchId,....\nWhat i wanna do is.... for a perticular student display the sports in which matches have been played. ie. if a sportID exists in the second table only then display that when i check which sports the student plays.\nThe resultSet should contain only those sports for a student in which matches have been played....\nThanks\n\nA: Okay, as this is homework (thanks for being honest about that) I won't provide a solution.\nGeneric way to design a query is:\n\n\n*\n\n*Think of how to write the FROM block (what is your data source)\n\n*Think of how to write the WHERE block (what filters apply)\n\n*Write the SELECT block (what you want from the filtered data).\n\n\nYou obviously need to join your two tables. The syntax for joins is:\nFROM table1\nJOIN table2 ON boolean_condition\n\nHere your boolean_condition is equality between the columns sportid in your two tables.\nYou also need to filter the records that your join will produce, in order to only retain those that match your particular student, with the WHERE clause.\nAfter that, select what you need (you want all sports ids).\nDoes that help enough?\n\nA: Then you have two tables :\n// One record per student / sport association\nstudent_sport\n StudentID \n SportID\n\n// A match is only for one sport (warning to your plural) no?\nmatches\n SportID\n MacthID\n\nYou want: For one student all sport already played in a match\nSELECT DISTINCT StudentID, student_sport.SportID\nFROM student_sport, matches\n\nWHERE \n -- Select the appropriate player\n student_sport.StudentID = @StudentID \n -- Search all sport played in a match and plays by the student \n -- (common values sportid btw student_sport & matches)\n AND student_sport.SportID = matches.SportID \n\nor use this other syntax (JOIN IN) (it makes complex queries easier to understand, so it's good to learn)\nSELECT DISTINCT StudentID, student_sport.SportID\nFROM student_sport\n-- Search all sport played in a match and plays by the student \n-- (common values sportid btw student_sport & matches)\nINNER JOIN matches on student_sport.SportID = matches.SportID\nWHERE \n -- Select the appropriate player\n student_sport.StudentID = @StudentID \n\nps: Includes Jan Hudec Coments, tx for it\n\nA: Because you only need to return results from the student_sport table, the join type is a semijoin. Standard SQL's operator for semi join is funnily enough MATCH e.g. \nSELECT * \n FROM student_sport \n WHERE SportID MATCH (\n SELECT SportID \n FROM matches\n WHERE student_sport.SportID = matches.SportID\n );\n\nThere are a number of other ways of writing a semi join in SQL e.g. here's three more:\nSELECT * \n FROM student_sport \n WHERE SportID IN (\n SELECT SportID \n FROM matches\n WHERE student_sport.SportID = matches.SportID\n );\n\nSELECT * \n FROM student_sport \n WHERE EXISTS (\n SELECT * \n FROM matches\n WHERE student_sport.SportID = matches.SportID\n );\n\nSELECT student_sport.* \n FROM student_sport \n INNER JOIN matches\n ON student_sport.SportID = matches.SportID;\n\n\nA: Well the query would be something like that:\nselect sm.* \nfrom student_sport ss join student_matches sm on ss.sportid = sm.sportId\nwhere ss.StudentId = @studendId\n\nThis and this should give you some insight of sql joins\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635643\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967637,"cells":{"text":{"kind":"string","value":"Q: How do I get access to the object which the Timer is attached to? I have a programming problem which I think is being caused by my rustiness in using events and delegates...\nI have the code:\npublic void DoStuff()\n {\n List processorsForService1 = processorsForService1 = ProcessFactory.GetProcessors();\n\n foreach (IProcess p in processorsForService1)\n {\n if (p.ProcessTimer != null)\n {\n p.ProcessTimer.Elapsed += new ElapsedEventHandler(IProcess_Timer_Elapsed);\n }\n }\n }\n\nAnd:\n private void IProcess_Timer_Elapsed(object sender, ElapsedEventArgs e)\n {\n IProcess p = (IProcess)sender;\n p.Step_One();\n p.Step_Two();\n }\n\nBut when I get to the event handler im getting null reference exception for p on the first line. \nHow do I pass an argument to the handler in this instance?\n\nA: It looks like you're using a System.Timers.Timer, if you were to use a System.Threading.Timer then you could pass a state object which, in this case, could be the desired instance of a class, i.e. the timer's 'owner'. In this way, you define your method body as with your previous experience of implementation within an event handler, only now the signature is as follows:\nprivate void MyTimerCallbackMethod(object state)\n{\n\n}\n\nThen, upon creating the timer instance, you can do something such as:\nvar timerCallback = new TimerCallback(MyTimerCallback);\nvar timer = new Timer(timerCallback, myStateObject, \n Timeout.Infinite, Timeout.Infinite);\n\nThen, use timer.Change(whenToStart, interval) to kick off the timer.\n\nA: The sender is the timer object, not the object associated with the handling delegate. For a start, events can have multiple handlers.\nWhat you could do is create a delegate which has access to the IProcess using variable capture.\n\nA: if you used a lambda instead of a delegate you could refer to the class from the lambda because it would still be in the referencing environment. I think this is called Closure.\npublic void DoStuff()\n{\n List processorsForService1 = ProcessFactory.GetProcessors();\n foreach (IProcess p in processorsForService1)\n {\n if (p.ProcessTimer != null)\n {\n p.ProcessTimer.Elapsed += (s, e) =>\n {\n p.Step_One();\n p.Step_Two();\n };\n }\n }\n}\n\nBeware of the following scope related rules though (taken from msdn):\n\nThe following rules apply to variable scope in lambda expressions:\n\n*\n\n*A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.\n\n\n*Variables introduced within a lambda expression are not visible in the outer method.\n\n\n*A lambda expression cannot directly capture a ref or out parameter from an enclosing method.\n\n\n*A return statement in a lambda expression does not cause the enclosing method to return.\n\n\n*A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.\n\n\nA: Make the event handler a member of IProcess and set up like this:\np.ProcessTimer.Elapsed += new ElapsedEventHandler(p.IProcess_Timer_Elapsed);\n\nand if you want to handle the event elsewhere, make the handler forward the event:\nclass IProcess\n{\n public delegate void Timer_Elapsed_Handler (IProcess process, ElapsedEventArgs e);\n public event Timer_Elapsed_Handler Timer_Elapsed;\n\n public void IProcess_Timer_Elapsed (object sender, ElapsedEventArgs e)\n {\n if (Timer_Elapsed != null) Timer_Elapsed (this, e);\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635646\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967638,"cells":{"text":{"kind":"string","value":"Q: jQuery Equal Heights of Divs I have two columns that have draggable and droppable divs within them. I used this code:\n//Equal Height Divs\n function equalHeight( group ) {\n var tallest = 0;\n group.each(function() {\n var thisHeight = $(this).height();\n if(thisHeight > tallest) {\n tallest = thisHeight;\n }\n });\n \n group.each(function() {\n $(this).css( \"min-height\", tallest );\n } );\n }\n\nTo make sure that as more divs are added to one column and that columns height gets larger so will the height of the second column.\nHowever I don't seem to know how to reverse this so that if I remove things from one column and the div height of both columns should get smaller. I know that I have over-complicated this so any help to sort out my confusion here would be much appreciated.\n\nA: Simply add $(this).css(\"height\", \"\");, to reset the CSS height attribute, so that the height won't be greater than necessary. Without a set height property, the element will shrink to the minimum height:\n function equalHeight( group ) {\n var tallest = 0;\n group.each(function() {\n $(this).css({height:\"\", \"min-height\":\"\"});\n var thisHeight = $(this).height();\n if(thisHeight > tallest) {\n tallest = thisHeight;\n }\n });\n\n group.each(function() {\n $(this).css( \"min-height\", tallest );\n } );\n }\n\n\nA: I think I understand your question only to an extent. If you are trying to set the height of elements with the height of the highest element, you can use this code. It is assuming that the elements that you are working on has same class.\nvar maxHeight = Math.max.apply(null, $('.common_classname').map(function() {\n return $(this).height();\n }).get());\n\n$('.common_classname').height(maxHeight);\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635653\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967639,"cells":{"text":{"kind":"string","value":"Q: Using a SELECT CASE statement in ActiveRecord, as Rails model default_scope I have a model, User, which can either be an individual or a company, depending on the value of a boolean, is_company. If the user is a company, company_name stores the name; if the user is an individual, first_name and last_name stores their name.\nIn the vast majority of cases, I want the users to be sorted by last_name OR company_name by default, so I'm using a default_scope in my User model.\nHowever, the way I have it - even though it works for SQLLite - is not database agnostic. Can anyone let me know how I can refactor this to accept a parameter of \"true\" in the case statement?\ndefault_scope select('users.*')\ndefault_scope select('CASE WHEN is_company = \"t\" THEN company_name ELSE last_name END AS sort_name')\ndefault_scope order('sort_name ASC')\n\nThanks!\n\nA: You need to rethink your design. A user that can be a company doesn't sound like good design to me. I think you're better off with separate User and Company models.\nYour sorting will be much easier that way too..\n\nA: You might want to do a modest redesign to handle this at the time you write to the database. \n\n\n*\n\n*Create a new column on your User table for display_name\n\n*Create a before_save callback in your User model that sets the display name like:\nbefore_save :set_display_name\n\ndef set_display_name\n self.display_name = self.is_company? ? self.company_name : self.last_name \nend\n\n\n*Change your default_scope to just order by the new column\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635655\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967640,"cells":{"text":{"kind":"string","value":"Q: Why my Emulator get restarted while i am going top run the Application in it? I have made a simple application in which i have use some buttons and some textView.\nOn button click event i am using the selector which will display the appropriate image base on the Button click action.\nBut i dont know what happend, and My Emulator got restarted.\nI have tried many times but still the emulator got restarted.\nWhere is the problem i dont know.\nPlease Help me in that.\nThanks.\nAnd the Error after cleaning the project i got is:\nError:\n[2011-10-03 19:01:11 - TaxCalculator] libpng error: Not a PNG file\n\n[2011-10-03 19:01:11 - TaxCalculator] ERROR: Failure processing PNG image E:\\Android\\Workspace\\TaxCalculator\\res\\drawable-hdpi\\email_icon.png\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:2: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/wawatermark').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:7: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/header_gradient').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:11: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_back_button').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:25: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/contact_us_title').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:42: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/phone_icon').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\contect_us.xml:53: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/email_icon').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\menu_screen.xml:6: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/tax_calculator_logo').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\menu_screen.xml:14: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\menu_screen.xml:21: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\menu_screen.xml:28: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\layout\\menu_screen.xml:35: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\drawable\\selector_back_button.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/back_pressed').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\drawable\\selector_back_button.xml:8: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/back_normal').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\drawable\\selector_menu_button.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/button_blue').\n[2011-10-03 19:01:11 - TaxCalculator] E:\\Android\\Workspace\\TaxCalculator\\res\\drawable\\selector_menu_button.xml:8: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/button_white').\n[2011-10-03 19:01:39 - TaxCalculator] Failed to install TaxCalculator.apk on device 'emulator-5554!\n[2011-10-03 19:01:39 - TaxCalculator] (null)\n[2011-10-03 19:01:39 - TaxCalculator] Launch canceled!\n\nA: Well, here no one give me answer. But i Got the Solution. Please read this carefully.\nProblem:I recently faced an issue where when I added my png file to an Android project it complained that it’s not a PNG file.\nError I faced:\n[2011-07-24 19:54:00 - xxxx] libpng error: Not a PNG file\n[2011-07-24 19:54:00 - xxxx] ERROR: Failure processing PNG image C:\\Users\\pawana\\workspace\\xxxx\\res\\drawable-nodpi\\background.png\n[2011-07-24 19:54:00 - xxxx] C:\\Users\\pawana\\workspace\\xxxx\\res\\layout\\main.xml:7: error: Error: No resource found that matches the given name (at ‘background’ with value ‘@drawable/background’).\nEnvironment: I was using “windows 7″ for development and that file was opening file as a PNG File on Windows 7. I was puzzled what was happening.\nBackground: I tried searching the web if someone else faced this issue and what as the solution. There were no good answers. I had verified my PNG was 24 bit. Android does support 24-bit and 32-bit. After lot of research it occured to me that maybe Android does not like the PNG format of “Adobe Photoshop”, too which I used to create the PNG.\nSolution: Final solution was to open the png file in MS Paint and re save it as png file. Once I did that Eclipse was able to use that file in Android project. I looked at what it changed, it convered the PNG to 32-bit format. Since Android supports both 24-bit and 32-bit PNGs, it makes me think there is something with “Adobe Phtoshop” generated PNGs which Android does not like.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635657\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967641,"cells":{"text":{"kind":"string","value":"Q: Keygen and Checker C#? I am trying to implement a license feature in my software, i want to print the key on the CD and the user have to input the key in the system and the key will be validated then, that means that a key generated in the CD have to produce a value after decryption that will match the hard coded value on the software or something like that. \nCan somebody please tell me how to implement this kind of the thing or anything that work with the same i idea.\nthanks.\n\nA: As an indirect answer, I'd suggest you start by having a read through the answers to this question - it may be that you decide to take another approach to the licensing and protection of your software.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635662\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":1967642,"cells":{"text":{"kind":"string","value":"Q: Why am I getting \"Warning: mysql_connect(): Access denied for user\" when attempting to connect? I can connect to php/myadmin by using the connection string, but if i am trying to connect through my php page, then it's giving the following error.\n\nWarning: mysql_connect(): Access denied for user 'bf_cards_user'@'My Server IP' (using password: NO) in /home/blue204/html/download/test_connection.php\n\nHere is my code:\n$dbCon = mysql_connect('My Server IP', 'bf_cards_user', 'bbeqvfyAwPWECvWs');\nif ($dbCon){\n echo \"connected\";\n} else {\n echo \"not connected\" ;\n} \n\n\nA: Have you allowed access to the MySQL server for the login/server combination you provide?\ngrant all permissions on *.* 'bf_cards_user'@'My Server IP'\n identified by 'bbeqvfyAwPWECvWs';\nflush privileges;\n\n\nA: You have made two mistakes here. The first mistake is you have passed \"My Server IP\" as your IP address. This is usually \"localhost\", but can also be an IP address for your server. Secondly (as pointed out in the comments of your OP), it says there is no password for the database yet you have stated one. You should ensure your database user has a password set.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635663\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967643,"cells":{"text":{"kind":"string","value":"Q: MS Access + NZ() function with empty table I am trying to add values from two different tables, but one of the tables is completely empty. I know the Nz() function is meant to convert Null values to a different value, i.e. 0, but the problem I am having is the table doesn't have any data, so Nz() doesn't work.\nIs there a way I can add the values of two tables together if one table is Null? I know it seems pointless, and eventually the table will have values, but for the sake of this week's reports, I need to do this.\nThanks\n\nA: I suspect this is to do with your query. Try something on the lines of:\nSELECT Nz(t1.[Field1],0) + Nz(t2.[Field1],0) As Added \nFROM t1 LEFT JOIN t2\nON t1.ID = t2.ID\n\nThe important point is LEFT JOIN, which will include all records from t1, even if there is no match in t2.\n\nA: Note that the Nz() function is not available outside of the Access UI. Here's an alternative approach that avoids Nz():\nSELECT t1.Field1 + t2.Field1 AS Added \n FROM t1 INNER JOIN t2 ON t1.ID = t2.ID\nUNION\nSELECT 0 AS Added \n FROM t2\nHAVING COUNT(*) = 0;\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635673\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967644,"cells":{"text":{"kind":"string","value":"Q: Error retrieving json with php I've some problem retrieving json information with a PHP.\nI've created a simple php page that returns a json:\n$data = array(\n 'title' => 'Simple title'\n);\nprint json_encode($data);\n\nAnd in another page I try to get that array as an object:\n$content = file_get_contents($url);\n$json_output = json_decode($content, true); \n\nswitch(json_last_error())\n{\n case JSON_ERROR_DEPTH:\n echo ' - Maximum stack depth exceeded';\n break;\n case JSON_ERROR_CTRL_CHAR:\n echo ' - Unexpected control character found';\n break;\n case JSON_ERROR_SYNTAX:\n echo ' - Syntax error, malformed JSON';\n break;\n case JSON_ERROR_NONE:\n echo ' - No errors';\n break;\n}\n\nThe problem is that there is an error with this approach: I receive a \"JSON_ERROR_SYNTAX\" because after \"file_get_contents\" function I have an unknown character at the beginning of the string.\nIf I copy/paste it on Notepad++ I didn't see:\n{\"title\":\"Simple title\"}\n\nbut I see:\n?{\"title\":\"Simple title\"}\n\nCould someone help me?\n\nA: Make sure both your scripts have same encoding - and if it's UTF make sure they are without Byte Order Mark (BOM) at very begin of file.\n\nA: What about\n$content = trim(file_get_contents($url));\n\n?\nAlso, it sounds as if there was a problem with the encoding within the PHP that echos your JSON. Try setting proper (as in: content-type) headers and make sure that both files are UTF-8 encoded.\n\nAlso: What happens if you open $url in your browser? Do you see an \"?\"\n\nA: I am pretty sure your page that does the json_encode has a stray ?. Look in there for a missing > in terms of ?> and such.\n\nA: Look through your PHP for a stray \"?\".\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635682\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967645,"cells":{"text":{"kind":"string","value":"Q: Template classes c++ friend functions My code has the same structure as the shown below. I have two container classes defined in a single header file and each one of them has a friend function with parameters of type the other class so I get a compiling error which is something like 'Class2' - undeclared identifier.\nTried a few things but didn't work it out. I think that if add one more template parameter V to both of the templates and replace Class2 with it could be a solution but thing get much complicated if I use these containers in my program.I also thought to separate Class1 and Class2 into different headers and then include in Class1 Class2 and vice versa but I actually I doubt that this could work at all. \nI really can't figure out how to solve this problem so please your help is much appreciated!\ntemplate\nclass Class1\n{\n ...\n friend void function1(Class1>&, const Class2&);\n ...\n};\n\ntemplate\nclass Class2\n{\n ...\n friend void function2(Class1);\n ...\n};\n\n\nA: Add a forward declaration for Class2 at the beginning of the file:\ntemplate class Class2;\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635684\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967646,"cells":{"text":{"kind":"string","value":"Q: Accessing android market form java application I want to build an java application, kind of a robot that periodically asks for exist apps based on a parameter (id, name, package...).\nWhat I want to know first is how to access the android market API (if there is any..) from my application. What plug-ins, additional jars in my build path do I need, to start communicating with the android market?\nMore specifically, I saw some answers about how to search, based on given URL's, but my question is even more basic - what are the first steps to access the market? In other words, how do I create a client of the android market in me application.\nBTW, I am using eclipse for JavaEE. I have pretty good pure java programming knowledge, though working with JavaEE, and web application is quite new for me.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635685\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967647,"cells":{"text":{"kind":"string","value":"Q: Ajax.BeginForm response contains previous values even if I pass another model I'm having a simple action:\n [HttpPost]\n public virtual ActionResult New(Feedback feedback)\n {\n feedback.CreatedDate = DateTime.UtcNow;\n\n if (TryValidateModel(feedback))\n {\n FeedbackRepository.Add(feedback);\n var model = new Feedback\n { \n SuccessfullyPosted = true\n };\n\n return PartialView(MVC.Shared.Views._FeedBackForm, model);\n }\n\n return PartialView(MVC.Shared.Views._FeedBackForm, feedback);\n }\n\nSo, idea is if received data is validating fine, return partial view with empty feedback entity. \nThing is, that if i look at firebug response, I see old values coming back, how weird is this?\nForm looks like this:\n\n@using (Ajax.BeginForm(MVC.Feedback.New(), new AjaxOptions\n {\n UpdateTargetId = \"contactsForm\",\n HttpMethod = \"post\"\n }))\n{ \n \n \n \n \n @Html.LabelFor(x => x.FirstName)\n @Html.EditorFor(x => x.FirstName)\n @Html.ValidationMessageFor(x => x.FirstName)\n \n @Html.LabelFor(x => x.LastName)\n @Html.EditorFor(x => x.LastName)\n @Html.ValidationMessageFor(x => x.LastName)\n \n @Html.LabelFor(x => x.Email)\n @Html.EditorFor(x => x.Email)\n @Html.ValidationMessageFor(x => x.Email)\n \n @Html.LabelFor(x => x.Phone)\n @Html.EditorFor(x => x.Phone)\n @Html.ValidationMessageFor(x => x.Phone) \n \n @Html.LabelFor(x => x.Comments)\n @Html.TextAreaFor(x => x.Comments, new { cols = 60, rows = 10 })\n @Html.ValidationMessageFor(x => x.Comments)\n \n if (Model.SuccessfullyPosted)\n {\n \n Feedback sent successfully.\n }\n \n \n}\n\nIs it possible somehow to disable this behavior and how PartialView(MVC.Shared.Views._FeedBackForm, model) manages to get different model?\nupdate: I see stackoverflow ate all html from by view and can't find how to fix that.\n\nA: ModelState is primary supplier of model values. Even if you pass your model to View or PartialView, EdiorFor will first look into ModelState for corresponding property value, and if it does not exist there, only then into model itself. ModelState is populated when posting to controller (old feedback). Even if you create new feedback and pass it as model, ModelState already contains values from previously posted feedback, so you get old values on client. Clearing modelstate before successfull post result will help you.\nFeedbackRepository.Add(feedback);\nvar model = new Feedback\n { \n SuccessfullyPosted = true\n };\nModelState.Clear(); // force to use new model values\nreturn PartialView(MVC.Shared.Views._FeedBackForm, model);\n\n\nSee this and this links for examples of related situations\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635690\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967648,"cells":{"text":{"kind":"string","value":"Q: writeToFile is not writing to the file Well I am experiencing a problem and I've been struggling with it for few days. Here it is: when trying to write to an xml file (placed in the xcode project which I am developing) using writeToFile, writing doesn't work and I can see nothing in the xml file although the bool value which is returned from writeToFile is being evaluated to true !! In addition, the file bytes are zero. So, I would really appreciate if anyone can help me out with that. Below is part of the code which I wrote:\n//writing to a file\n NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@\"sample\" ofType:@\"xml\"];\n NSString *dummyString = @\"Hello World!!\\n\"; \n NSFileManager *filemanager;\n\n filemanager = [NSFileManager defaultManager];\n\n //entering the first condition so I assured that the file do exists\n if ([filemanager fileExistsAtPath:pathOfFile] == YES)\n NSLog (@\"File do exist !!!\");\n else\n NSLog (@\"File not found !!!\");\n\n\nBOOL writingStatus = [dummyString writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:nil];\n\n //Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes\n if(!writingStatus)\n {\n NSLog(@\"Error: Could not write to the file\");\n }\n\nI also tried this alternative, but unfortunately it didn't work too.\nNSString *hello_world = @\"Hello World!!\\n\";\nNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\nNSString *directory = [paths objectAtIndex:0];\nNSString *fileName = @\"sample.xml\";\nNSString *filePath = [directory stringByAppendingPathComponent:fileName];\nNSLog(@\"%@\",filePath);\nBOOL sucess = [hello_world writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil]; \nif(!sucess)\n{\n NSLog(@\"Could not to write to the file\");\n}\n\n\nA: In the first piece of code, we can't see the definition of path. If that's a typo and you meant file_path, the problem is that file_path points to a path inside the app bundle. You can't write inside your app bundle. (There shouldn't be any typos, because you should be pasting the code directly.)\nIn the second case, it's harder to tell what the problem is. filePath should be in the documents directory, which is writeable. However, it'd be a lot easier to diagnose the problem if you were getting an actual error. Instead of passing nil for the error parameter in -writeToFile:atomically:encoding:error:, create a NSError* variable and pass in its address. If there's a problem, then, your pointer will be set to point to an NSError object that describes the problem.\n\nA: The fact that writeToFile: is returning a boolean value of YES simply means that the call is completing.\nYou should be passing an NSError** to writeToFile: and examining that, e.g:\n NSError *error = nil;\n BOOL ok = [hello_world writeToFile:filePath atomically:YES \n encoding:NSASCIIStringEncoding error:&error];\n if (error) {\n NSLog(@\"Fail: %@\", [error localizedDescription]);\n }\n\nThat should give you a good clue about what is going wrong (assuming error is not nil after the call).\n\nA: -(void)test{\n//writing to a file\n NSError *error;\n NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@\"sample\" ofType:@\".xml\"];//was missing '.'\nNSString *dummyString = @\"Hello World!!\\n\";\nNSFileManager *filemanager;\n\nfilemanager = [NSFileManager defaultManager];\n\n//entering the first condition so I assured that the file do exists\n //the file exists in the bundle where you cannot edit it\n\n if ([filemanager fileExistsAtPath:pathOfFile]){\n NSLog (@\"File do exist IN Bundle MUST be copied to editable location!!!\");\n NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\n NSString *docsDir = [[locs objectAtIndex:0]stringByAppendingString:@\"dummyFile\"];\n NSString *file = [docsDir stringByAppendingPathComponent:@\".xml\"];\n\n [filemanager copyItemAtPath:pathOfFile toPath:file error:&error];\n }\n else{\nNSLog (@\"File not found in bundle!!!\");\n\n }\n\n if (error) {\n NSLog(@\"error somewhere\");\n }\n\n\n//if youre only messing with strings you might be better off using .plist file idk\nBOOL success = [dummyString writeToFile:file atomically:YES encoding:NSUnicodeStringEncoding error:nil];\n\n//Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes\nif(!success)\n{\n NSLog(@\"Error: Could not write to the file\");\n}\n\n\n}\n\n\nA: //I typically do something like this\n\n//lazy instantiate a property I want such as array.\n-(NSMutableArray*)array{\n if (!_array) {\n _array = [[NSMutableArray alloc]initWithContentsOfFile:self.savePath];\n }\n return _array;\n}\n\n//I'm using a class to access anything in the array from as a property from any other class\n//without using NSUserDefaults.\n\n//initializing the class\n-(instancetype)init{\n\n self = [super init];\n if (self) {\n //creating an instance of NSError for error handling if need be.\n NSError *error;\n //build an array of locations using the NSSearchPath... \n NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\n //location 0 of array is Documents Directory which is where I want to create the file\n NSString *docsDir = [locs objectAtIndex:0];\n//my path is now just a matter of adding the file name to the docsDir\n NSString *path = [docsDir stringByAppendingPathComponent:@\"fileName.plist\"];\n//if the file is a plist I have in my bundle I need to copy it to the docsDir to edit it\n\n//I'll do that by getting it from the bundle that xCode made for me\n NSString *bunPath = [[NSBundle mainBundle]pathForResource:@\"fileName\" ofType:@\".plist\"];\n\n\n//now I need a NSFileManager to handle the dirty work\n NSFileManager *filemngr = [NSFileManager defaultManager];\n\n\n//if the file isn't in my docsDir I can't edit so I check and if need be copy it. \n if (![filemngr fileExistsAtPath:path]) {\n [filemngr copyItemAtPath:bunPath toPath:path error:&error];\n\n//if an error occurs I might want to do something about it or just log it as in below.\n//I believe you can set error to nil above also if you have no intentions of dealing with it.\n if (error) {\n NSLog(@\"%@\",[error description]);\n error = nil;\n\n }\n//here I'm logging the paths just so you can see in the console what's going on while building or debugging.\n NSLog(@\"copied file from %@ to %@\",bunPath,path);\n }\n\n//in this case I'm assigning the array at the root of my plist for easy access\n _array = [[NSMutableArray alloc]initWithContentsOfFile:path];\n _savePath = path;//this is in my public api as well for easy access.\n\n }\n\n return self;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635696\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"5\"\n}"}}},{"rowIdx":1967649,"cells":{"text":{"kind":"string","value":"Q: MVC3 render scripts in partial view Hopefully someone out there can help me with this.....I'm building an MVC3 project and I can't seem to figure out why my partial view cannot execute any inline javascript functions. Here is made up example, but will hopefully show the principal I am trying to achieve....\nI have a list of items in a view, called Items. \nforeach (var item in Model.SaleItems)\n{ \n
@Html.ActionLink((string)item.ID, \"Item\", new { ID = @item.ID })
\n}\n\nIf the user clicks one of the items, they will be sent to a page with details about the item selected. On this page, there is a menu will 3 choices; details, reviews, images (each is a partial view). If the user selects the details option from the menu, the details partial will render a few charts from a webservice like the Google visualization API.\nHere is my partial view with a script to load a chart :\n
\n

Details

\n
\n
\n\n\n\n\nAnyone have any ideas why this doesn't work? If I move the script from the partial view to the view, and statically declare an item in the main view's ActionResult, it will work, but other than that it doesn't.\nThanks in advance!\n\nA: I finally figured it out. Shuniar was correct, scripts should execute in the partial views, but the problem is with the Google maps and visualization APIs. The partial view would render but the function that was never being called in the script. This make sense because there is no onLoad for partial views.\ngoogle.setOnLoadCallback(drawDetailsTable);\nfunction drawDetailsTable() {\n ....\n });\n\nTo fix it, I simply changed it to explicitly call the function as the partial is being rendered.\n google.setOnLoadCallback(drawDetailsTable);\n drawDetailsTable(); \n function drawDetailsTable() {\n ....\n }); \n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635702\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967650,"cells":{"text":{"kind":"string","value":"Q: JAAS and Security - how to use custom tables with GlassFish Security? Is it possible to use JAAS with GlassFish but using my custom tables ?\nI've got a mapping like this\ntbUser -> user_roles <- tbRoles\nIt's a manytomany with users and roles mapped by an Id into user_roles table, so for this to work with JAAS and GlassFish I would need to change GlassFish custom select to one made by me.\nIs it possible to make glassfish use that setup instead of it's default user_table, role_table without relations ?\nI need to use this setup for db, because of the client reqs.\n\nA: You may want to use JDBCRealm in GlassFish: \nhttp://blogs.oracle.com/swchan/entry/jdbcrealm_in_glassfish .\n\nA: This post may help: http://weblogs.java.net/blog/kumarjayanti/archive/2010/02/01/using-custom-jaas-loginmodules-authentication-glassfish\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635704\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967651,"cells":{"text":{"kind":"string","value":"Q: \"deadlock detected\" errors on Rails 2.3.14 site -- Passenger 3.0.9, Ruby 1.9.2 About every 3rd time my app serves a particular update action (two that I've found so far), it bombs out with a \"deadlock detected\" error.\nI haven't been able to trace it to any of our own application code. It seems that the action completes, but then this crash happens as either Rails or Passenger is wrapping it up. (It doesn't happen from just saving records in script/console.)\nHere is what comes up in the logs when it happens: https://gist.github.com/1259104\nWhat's going on, and what do I do about it? \n(note: have switched to RVM-based Ruby 1.9.2, and issue persists.)\n\nA: The issue appears to be this:\nhttps://rails.lighthouseapp.com/projects/8994/tickets/5736-connections-not-released-in-rails-3\nHowever, above issue only pertains to Rails 3. We are seeing it in Rails 2.3.14 under Ruby 1.9.2.\nThe patch to connection_pool.rb given there works for us. That particular file appears to be identical between 2.3.14 and 3.1.0 beta so the patch is likewise the same. We had to patch the gem itself -- doing it by loading the new file/class as part of the Rails app itself didn't do the trick -- but the behavior is the same for us as is being reported there -- instead of deadlocking/running out of db connections, there's a short delay. In conjunction with bumping up the pool size in the production db config in database.yml, this works pretty acceptably, though I do hope for an even better solution.\n& Thanks to Alex Caudill for finding this for us!\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635705\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967652,"cells":{"text":{"kind":"string","value":"Q: OpenCL built-in function 'select' It's not clear for me what is a purpose of built-in OpenCL function select. Can somebody, please, clarify?\nFrom OpenCL specification:\n\nfunction select(gentype a, gentype b, igentype c)\nreturns: for each component of a vector type, result[i] = if MSB of c[i] is set ? b[i] : a[i].\n\nWhat is a MSB in this case? I know that MSB stands for most significant bit, but I have no idea how it's related to this case.\n\nA: OpenCL select is to select elements from a pair of vectors (a, b), based on the truth value of a condition vector (c), returning a new vector composed of elements from the vectors a and b.\nThe MSB (most significant bit) is mentioned here, because the truth value of a vector element is defined to be -1 and the MSB should therefore be set (as the sign bit):\na = {1 , 2} // Pseudocode for select operands\nb = {3 , 4}\nc = {0 ,-1}\nr = {1 , 4} // The result r contains some of a and b\n\n\nA: This is a very useful operator which does the same job as what a conditional expression does in C. However, conditional expression often compiles to a conditional branch which cause warp/wavefront divergence. The 'select' usually generates a predicated expression - kind of like CMOV on x86 or blend_ps in SSE. \n\nA: I have found 2 basic patterns of using select: scalar case and vector case.\nScalar case is pretty straightforward:\nif (a > 0.0f) b = 0.3f;\nis equivalent to\nb = select(b, 0.3f, isgreater(a, 0.0f));\nIf wanted to deal with vectors, i.e. obtain a vector result from select everything became a bit more complicated:\nif (a > 0.0f) b = (float2)(0.3f, 0.4f);\nis equivalent to\nb = select(b, (float2)(0.3f, 0.4f), (int2)(isgreater(a, 0.0f) << 31));\nThat bit-wise shift needed to make LSB result of comparison operator to be MSB to conform select specification. Casting to int2 ensures that all components will take their positions in result.\nConcluding remark is that using snippets above helps more to understand usage of select rather then thinking of equivalence with C ternary operator ?:.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635706\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":1967653,"cells":{"text":{"kind":"string","value":"Q: Regarding htaccess, PHP and hidden variable passing Alright, I have a problem. Let's say that I want to be able to visit this url\n`forum.mysite.com/offtopic/23894/`\n\nand for it to pass the variables\n`forum.mysite.com/file.php?board=offtopic&thread=23894`\n\nwithout anyone seeing the string. Is there any way I can do this, either with .htaccess or anything else?\n\nA: RewriteEngine on\nRewriteRule /([^/]+)/([0-9]+)/ file.php?board=$1&thread=$2\n\nThat should work if you put it in a .htaccess file.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635709\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967654,"cells":{"text":{"kind":"string","value":"Q: Linking CUDA and C++: Undefined symbols for architecture i386 I have tried really hard but no success. I hope someone can help me get this working.\nI have two source files.\nMain.cpp\n#include \n#include \"Math.h\"\n#include \n#include \n\nint cuda_function(int a, int b);\nint callKnn(void);\n\nint main(void)\n{\n int x = cuda_function(1, 2);\n int f = callKnn();\n std::cout << f << std::endl;\n return 1;\n}\n\nCudaFunctions.cu\n#include \n#include \n#include \"Math.h\"\n#include \n#include \"cuda.h\"\n#include \n#include \"knn_cuda_without_indexes.cu\"\n\n__global__ void kernel(int a, int b)\n{\n //statements\n}\n\nint cuda_function2(int a, int b)\n{\n return 2;\n}\n\nint callKnn(void)\n{ \n // Variables and parameters\n float* ref; // Pointer to reference point array\n float* query; // Pointer to query point array\n float* dist; // Pointer to distance array\n int ref_nb = 4096; // Reference point number, max=65535\n int query_nb = 4096; // Query point number, max=65535\n int dim = 32; // Dimension of points\n int k = 20; // Nearest neighbors to consider\n int iterations = 100;\n int i;\n\n // Memory allocation\n ref = (float *) malloc(ref_nb * dim * sizeof(float));\n query = (float *) malloc(query_nb * dim * sizeof(float));\n dist = (float *) malloc(query_nb * sizeof(float));\n\n // Init \n srand(time(NULL));\n for (i=0 ; i GetServices(Int32 CostCentreNo, Int32 Filter);\n\nThis would give an example URI as:\n http://paul-hp:1337/WCF.IService.svc/rest/Services?CostCentreNo=1&Filter=1\n\nI have a lot of get methods.\nand a few insert methods. Is the URI acceptable. Does it need GET/ in it or something?\nedit:\nOkay, now i undstand it more:\n So If I had a sub service, it would(could) be \n /CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService \n\nand, Insert Room booking (with over 20 parameters) could be \n /CostCentres/{CostCentreNo}/Rooms/{RoomNo}/Booking?param1={param1}....&param20=‌​{param20} \n\n\nA: hmm... one of the reasons folks use REST is to avoid query strings for anything other than actual queries. In your case, a CostCentre probably deserves its own URL, as well as a separate URL for its services. Based on your example, in my opinion only the Filter should be a query string. \nI would structure your URL as follows:\n\n/CostCenters/{CostCentreNo}/Services?Filter={Filter}\n\n\nEdit:\n\nOkay, now i undstand it more: So If I had a sub service, it\n would(could) be\n/CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService and,\n\nInsert Room booking (with over 20 parameters) could be\n/CostCentres/{CostCentreNo}/Rooms/{RoomNo}/Booking?param1={param1}....&param20=‌​{param20}\n\n\nI would recommend granting individual entities that can exist on their own URLs that are closer to the parent hierarchy, if possible. Obviously I don't know your system, but my guess is that you might want to do something along the lines of:\n\n/CostCenters/{CostCenterNo}\n/Services/{ServiceID}\n/Rooms/{RoomNo}\n\n\nOnly use hierarchies like \n\n/CostCenters/{CostCentreNo}/Services/{ServiceID}/\n\n\nwhen a Service cannot exist without a CostCenter. If that is the case, by all means, go with such a hierarchy. If a Service can exist without a CostCenter, go with the former hierarchy above. \nOne last thing. This URL from your example:\n\n/CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService \n\n\nonly makes sense if a Service can have one and only one SubService. I'm betting that your example needs a SubServiceID or something similar. And following my advice above, I would definitely say that a SubService absolutely would need to be extending a Service URL, e.g.:\n\n/Services/{ServiceID}/SubServices/{SubServiceID}\n\n\nIn the above case, I would expect that a SubServiceID references the same entity pool as ServiceID, and that whatever data or view is returned by this URL would include both the Service and SubService. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635715\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967656,"cells":{"text":{"kind":"string","value":"Q: how to prevent keyboard from hiding? Say I have an InputService ( keyboard ) that starts an activity. Since the activity has a transparent background, it is seen, that going on under it. Once the activity starts, the keyboard hides from under it and remains hidden after the activity has ended.\nHow to I prevent it from hiding?\nIntent PopIntent = new Intent(getBaseContext(), popup.class);\nPopIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\ngetApplication().startActivity(PopIntent);\n\n\nA: Just do this:\n//Show soft-keyboard:\ngetWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);\n\n\nA: i'm stranded at the exactly the same problem :-(. did you meanwhile found a solution?\ni tried to open the keyboard programmatically again after i come back to the originally activity and simulate a touchevent on the TextView so that the TextView is bound again to the InputMethodService:\nRunnable r = new Runnable() {\n\n @Override\n public void run() {\n final Instrumentation inst = new Instrumentation();\n int[] location = new int[2];\n tvEdit1.getLocationOnScreen(location);\n long time1 = SystemClock.uptimeMillis();\n long time2 = SystemClock.uptimeMillis();\n MotionEvent mv = MotionEvent.obtain(time1, time2, MotionEvent.ACTION_DOWN,\n location[0], location[1], 0);\n inst.sendPointerSync(mv);\n\n time1 = SystemClock.uptimeMillis();\n time2 = SystemClock.uptimeMillis();\n mv = MotionEvent.obtain(time1, time2, MotionEvent.ACTION_UP,\n location[0], location[1], 0);\n\n inst.sendPointerSync(mv);\n\n }\n }; \n\n Thread t = new Thread(r);\n t.start();\n\nThat works if i know which TextView the user clicked. Is there a way to find in a InputMethodService Class the correlating position of the bound TextView? With position i mean the x und y coordinates for simulating a touchevent on that position.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635716\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967657,"cells":{"text":{"kind":"string","value":"Q: type declarations in 'where' -- what's going on? While reading the QuickCheck Manual, I came across the following example: \nprop_RevRev xs = reverse (reverse xs) == xs\n where types = xs::[Int]\n\nThe manual goes on to say:\n\nProperties must have monomorphic types. `Polymorphic' properties, such as the one above, must be restricted to a particular type to be used for testing. It is convenient to do so by stating the types of one or more arguments in a\nwhere types = (x1 :: t1, x2 :: t2, ...)\nclause. Note that types is not a keyword; this is just a local declaration which provides a convenient place to restrict the types of x1, x2 etc.\n\nI have never seen such a trick in Haskell before. Here's what I'm really having problems with:\n\n\n*\n\n*Why does this syntax for type declarations even exist? What can it do for me that the following couldn't?\nprop_RevRev :: [Int] -> Bool\nprop_RevRev xs = reverse (reverse xs) == xs\n\n\n*Does this use of where constitute 'special' syntax for type declarations? Or is it consistent and logical (and if so, how?)?\n\n*Is this usage standard or conventional Haskell? \n\nA: It is no special syntax, and sometime you just need it, like in the following case:\nfoo :: String -> String\nfoo s = show (read s)\n\nAs it stands, this cannot be typed because the type of the value read s cannot be identified. All that is known is that it must be an instance of Show and of Read. But this type does not appear in the type signature at all, so it is also not possible to leave it at that and infer a constrained type. (There is just no type variable that could be constrained.)\nIt is interesting to note that what read s does depends entirely on the type signature one gives to read s, for example:\nread \"Just True\" :: (Maybe Bool)\n\nwill succeed, while\nread \"Just True\" :: (Maybe Int)\n\nwill not.\n\nA: where is not special syntax for type declarations. For example, this works:\nprop_RevRev :: [Int] -> Bool\nprop_RevRev xs = ys == xs\n where ys = reverse (reverse xs)\n\nand so does this:\nprop_RevRev xs = ys == xs\n where ys = reverse (reverse xs)\n ys :: [Int]\n\nThe advantage of where type = (xs :: [Int]) over prop_RevRev :: [Int] -> Bool is that in the latter case you have to specify the return type, while in the former case the compiler can infer it for you. This would matter if you had a non-Boolean property, for example:\nprop_positiveSum xs = 0 < length xs && all (0 <) xs ==> 0 < sum xs\n where types = (xs :: [Int])\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635720\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"14\"\n}"}}},{"rowIdx":1967658,"cells":{"text":{"kind":"string","value":"Q: Add search box for getting started search box I want to add a search box for getting started example (Hello, World) on chrom extensions http://code.google.com/chrome/extensions/getstarted.html, I was able to add a search box so I can change the word/s are used to get different thumbnails (\"text=hello%20world\").\nThe problem I faced is how to refresh the contents with a new thumbnails, for ex.:\nIf I want to search for word jerusalem and click go button the contents (thumbnails) will be updated with a new thumbnails for jerusalem\nDo I need to use AJAX? Please explain.\nThanx for any help.\n====================\nI included jquery in popup.html \nInside showPhotos() function I did the following:\nfunction showPhotos() {\n//Remove previous thumbs if any\nfor (var i = document.images.length; i-- > 0;) document.body.removeChild(document.images[i]);\n\nvar photos = req.responseXML.getElementsByTagName(\"photo\");\nfor (var i = 0, photo; photo = photos[i]; i++) {\n var img = document.createElement(\"image\");\n var span = document.createElement(\"span\");\n var span1 = document.createElement(\"span\");\n\n $(span1).attr('id', 'innerSpan');\n $(span1).attr('style', 'text-align:center;color:#ffffff;');\n $(span1).addClass('tooltip black bottom center w100 slide-up');\n $(span1).html('' + photo.getAttribute(\"title\") + '');\n\n $(span).addClass('savytip');\n $(span).attr('id', 'outerSpan');\n\n $(img).attr('src', constructImageURL(photo));\n\n $(span1).appendTo(span);\n $(img).appendTo(span);\n\n $(span).appendTo('body');\n}}\n\nThe extension just work for the first time and the go button stop responding, where is the wrong in my code?\n\nA: This example is already using AJAX, aka XHR(XMLHttpRequest).\nAll you need to do is put the request inside a function to be able to call it again later.\nAlso You'll need to remove the previous thumbs before appending the new ones(see the first line of 'showPhotos' function).\nHere's a working example:\npopup.html\n\n\n \n \n\n\n \n\n\n\npopup.js\nfunction search() {\n request(document.getElementById('query').value);\n return false;\n}\n\nfunction request(query) {\n window.req = new XMLHttpRequest();\n req.open(\n \"GET\",\n \"http://api.flickr.com/services/rest/?\" +\n \"method=flickr.photos.search&\" +\n \"api_key=90485e931f687a9b9c2a66bf58a3861a&\" +\n \"text=\"+encodeURI(query)+\"&\" +\n \"safe_search=1&\" + // 1 is \"safe\"\n \"content_type=1&\" + // 1 is \"photos only\"\n \"sort=relevance&\" + // another good one is \"interestingness-desc\"\n \"per_page=20\",\n true);\n req.onload = showPhotos;\n req.send(null);\n}\n\nfunction showPhotos() {\n //Remove previous thumbs if any\n for(var i=document.images.length;i-->0;) document.body.removeChild(document.images[i]);\n\n var photos = req.responseXML.getElementsByTagName(\"photo\");\n for (var i = 0, photo; photo = photos[i]; i++) {\n var img = document.createElement(\"image\");\n img.src = constructImageURL(photo);\n document.body.appendChild(img);\n }\n}\n\n// See: http://www.flickr.com/services/api/misc.urls.html\nfunction constructImageURL(photo) {\n return \"http://farm\" + photo.getAttribute(\"farm\") +\n \".static.flickr.com/\" + photo.getAttribute(\"server\") +\n \"/\" + photo.getAttribute(\"id\") +\n \"_\" + photo.getAttribute(\"secret\") +\n \"_s.jpg\";\n}\n\npopup.css\nbody {\n min-width:357px;\n overflow-x:hidden;\n}\n\nimg {\n margin:5px;\n border:2px solid black;\n vertical-align:middle;\n width:75px;\n height:75px;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635724\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967659,"cells":{"text":{"kind":"string","value":"Q: How can I return control from my python script to the calling bash script? I am using a bash script to loop through a configuration file and, based on that, call a python script via ssh. Unfortunately once the Python script does its job and I call quit the bash script also gets closed, therefore the calling bash script's loop is terminated prematurely.\nHere's my Bash Script\ntarget | grep 'srv:' | while read l ; do srv $l $SSH ; done\n\n srv () {\n SSH=$2\n SRV=`echo $1 | awk -F: '{print $2}'`\n STATUS=`echo $1 | awk -F: '{print $3}'`\n open $SSH \"srv\" $SRV $STATUS\n }\n\nthen on the remote machine where the python script is called\nif __name__== \"main\":\n redirect('./Server.log', 'false')\n conn()\n if sys.argv[1] == \"srv\":\n ServerState(sys.argv[2], sys.argv[3])\n quit()\n\nSo looks like the quit() is also interrupting the script.\n\nA: Nothing that the remote Python script does should be able to kill your do loop unless you have done a set -e in the local bash first to make it sensitive to command failure — in which case it would die only if, as @EOL says, your remote script is hitting an exception and returning a nonzero/error value to SSH which will then die with a nonzero/error code locally.\nWhat happens if you replace do srv with do echo srv so that you just get a printout of the commands you think you are running? Do you see several srv command lines get printed out, and do they have the arguments you expect?\nOh: and, why are you using open to allocate a new Linux virtual terminal for every single run of the command? You do not run out of virtual terminals that way?\n\nA: It looks like quit() is the function that makes your program stop.\nIf you can remove the call to quit() (i.e. if it does nothing), just remove it.\nOtherwise, you can run your Python program by hand (not from a shell script) and see what happens: it is likely that your Python script generates an exception, which makes the shell script stop. By running your Python program manually with realistic arguments (on the remote machine), you should be able to spot the problem.\n\nA: You should be able to simply return from the main function.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635725\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967660,"cells":{"text":{"kind":"string","value":"Q: Extend ANTLR3 AST's With ANTLR2, you could define something like this in grammar definition file:\noptions\n{\n language = \"CSharp\";\n namespace = \"Extended.Tokens\";\n}\n\ntokens {\n TOKEN;\n}\n\nAnd then, you could create a class:\npublic class TokenNode: antlr.BaseAST\n{\n ...\n}\n\nAny ideea if something like this can be used (delegate class creation to AST factory instead of me doing the tree replication manually)? It's not working just by simple grammar definition copy from old to new format, and I tried to search their site and samples for somthing similar. Any hints?\nEDIT\nI'm not trying to create custom tokens, but custom 'node parsers'. \nIn order to 'execute' a tree you have 2 choices (as far as I understood): \n\n\n*\n\n*create a 'tree visitor' and handle values, or \n\n*create a tree parser by 'almost-duplicating' the grammar definition. \n\n\nIn v2 case, I could decorate the tree node to whateveer method I would have liked and then call them after the parser ran by just calling something like 'execute' from root node.\n\nA: I know little C#, but there shouldn't be much difference with the Java target.\nYou can create - and let ANTLR use - a custom tree by setting the ASTLabelType in the options { ... } section (an XTree in this case):\nT.g\ngrammar T;\n\noptions {\n output=AST;\n ASTLabelType=XTree;\n}\n\ntokens {\n ROOT;\n}\n\n@parser::header {\n package demo;\n import demo.*;\n}\n\n@lexer::header {\n package demo;\n import demo.*;\n}\n\nparse\n : Any* EOF -> ^(ROOT Any*)\n ;\n\nAny\n : .\n ;\n\nYou then create a custom class which extends a CommonTree:\ndemo/XTree.java\npackage demo;\n\nimport org.antlr.runtime.*;\nimport org.antlr.runtime.tree.*;\n\npublic class XTree extends CommonTree {\n\n public XTree(Token t) {\n super(t);\n }\n\n public void x() {\n System.out.println(\"XTree.text=\" + super.getText() + \", children=\" + super.getChildCount());\n }\n}\n\nand when you create an instance of your TParser, you must create and set a custom TreeAdaptor which creates instances of your XTree:\ndemo/Main.java\npackage demo;\n\nimport org.antlr.runtime.*;\nimport org.antlr.runtime.tree.*;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n String source = \"ABC\";\n TLexer lexer = new TLexer(new ANTLRStringStream(source));\n TParser parser = new TParser(new CommonTokenStream(lexer));\n parser.setTreeAdaptor(new CommonTreeAdaptor(){\n @Override\n public Object create(Token t) {\n return new XTree(t);\n }\n }); \n XTree root = (XTree)parser.parse().getTree();\n root.x();\n }\n}\n\nRunning the demo:\njava -cp antlr-3.2.jar org.antlr.Tool T.g -o demo/\njavac -cp antlr-3.2.jar demo/*.java\njava -cp .:antlr-3.2.jar demo.Main\n\nwill print:\nXTree.text=ROOT, children=3\n\nFor more info, see: http://www.antlr.org/wiki/display/ANTLR3/Tree+construction\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635729\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967661,"cells":{"text":{"kind":"string","value":"Q: Load / Performance tests (HTTP and Web) I'm looking for a load test tool, the main features that I need is:\n\n\n*\n\n*Distribution (very important) - I need to be able to run something like 20,000 - 30,000 request per seconds (and more), so one machine is not enough. It should be able to communicate on Amazon EC2 (jMeter for example, can not do it)\n\n*Collecting data - It doesn't matter if it can produce graphs or complex data or not, but I should be able to know what was the Throughput of the client and the server, how many errors occured etc. Since it will run on multiple computers, the data should be collected by the tool itself (again jMeter does it, but it has a lot of problems), I'm trying to avoid from fetching data from different machines and merging it \"manually\".\n\n*Graphs or more complex data are nice to have (for example: http://code.google.com/p/multi-mechanize/), but if the tool doesn't provide it, I should be able to get this data from the logs of the tests.\n\n\nI didn't find good reviews on load testing tools (and that's why I'm asking here), and currently the main tool that I'm want to check is Grinder, if you've worked with good tools please share :)\nI've worked with jMeter, and I've decided to look for a better tool. jMeter is old, it works with old protocols (So I can't work with it distributed on EC2), it slow and hard to work with, and its graphs make it very slow.\nBTW, It doesn't have to be free / open source, if it costs up to tens or hundreds of dollars its OK.\nThanks.\n\nA: Locust is a great load testing tool and it meets all of the OP's requirements.\nAs far as meeting the OP's requirements, some Locust features:\n\n\n*\n\n*can run in master/slave mode for distributed load generation\n\n*gives you access to raw and summarized result data in simple/parseable\nformats\n\n*integrates nicely with graphite/grafana for your visualization needs\n\n\nLocust is open source and written in Python... virtual users are also written in Python code. The power and ease of using Python to develop complex workloads is really nice (compare that to JMeter's clunky declarative XML style).\nLocust development is hosted on Github and has several active committers.\n\non the Locust website, the tagline is: \n\n\"Define user behaviour with Python code, and swarm your system with\n millions of simultaneous users.\"\n\n\nscreenshot of optional web UI:\n\n\nNote: I've worked with all the other tools recommended in other answers, and Locust is far superior\n\nA: Visual Studio's Web Performance Tests and Load Tests sound like a good fit here. If you get a license for Visual Studio Ultimate and then a license for Visual Studio Controller/Agents the controllers and agents handle the distribution of load. It is all very well documented and pretty easy to get set up. It has some default reporting that may meet your needs, but also has the ability to export to excel where you can create any custom reports or graphs using Pivot Tables (or external tools like PowerPivot). \nHere is the quick reference guide: http://vsptqrg.codeplex.com/ and more info is available all over on the web.\n\nA: The question states that it is not possible to use JMeter on Amazon ec2 [point 1.]. This is not true, it is possible, but it is made difficult because JMeter uses RMI to communicate and you have to play with tunnels and changing ports to make that work. \nThe other JMeter issue mentioned [point 2.] is that it has a 'lot of problems' collating data. I suspect this refers to a potential bottleneck where all the data from multiple clients is being written to one location. If so, then his issue is typically addressed by using 'batched' or 'statistical' mode in the properties, plus the latest JMeter version, 2.6, has advances in this area.\nHowever, I wrote a script that gets around both these problems and makes running JMeter on ec2 considerably easier. \n\nA: You can use WebLOAD.\nI has built in support for automatically launching load machines on EC2, collects all the data and has good reporting capabilities.\n\nA: For these numbers of requests I would look a Tsung although (similar to Jmeter) this is XML declarative in terms of load specification. If you are more comfortable with coding a web driver then the Grinder would be worth alook (both Open Source).\n\nA: Actually we use Amazon EC2 to run cloud load test with JMeter. It's not so hard as you think. Advantage of JMeter than two tools (Grinder, Tsung) is documentation and community. \n\njMeter is old, it works with old protocols (So I can't work with it\n distributed on EC2)\n\nJMeter last nightly build was yesterday and it means it's not so old as you think. You can check it here. EC2 uses WSDL for API calls, it's common protocol not new, here is EC2 API documentation.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635747\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967662,"cells":{"text":{"kind":"string","value":"Q: Using CodeModuleListener + Blackberry I am trying to use CodeModuleListener in my application. I am testing this on simulator. After I run my application I add another cod file to the simulator but the moduleAdded(..) method of CodeModuleListener is not called, when I expect it would be.\npublic static void main(String[] args) {\n Application_Load theApp = new Application_Load();\n theApp.enterEventDispatcher();\n\n try \n {\n CodeModuleManager.addListener(UiApplication.getApplication(), cmListener);\n } \n catch (NullPointerException e) \n {\n System.out.println(e.getMessage());\n e.printStackTrace();\n } \n}\n\n\npublic Application_Load()\n {\n cmListener = new CodeModuleListener() \n {\n\n public void modulesDeleted(String[] moduleNames) \n {\n String s = \"APP DELETED ====================>\";\n System.out.println(s); \n //writeFile(s, \"file:///SDCard/uploadedfile.txt\");\n deleteFile(\"file:///system/databases/TestApp/TestDB.db\");\n }\n\n public void modulesAdded(int[] handles) \n {\n String s = \"APP ADDED ====================>\";\n System.out.println(s); \n //writeFile(s, \"file:///SDCard/uploadedfile.txt\");\n deleteFile(\"file:///system/databases/TestApp/TestDB.db\");\n }\n\n public void moduleDeletionsPending(String[] moduleNames) \n {\n String s = \"APP IS DELETING ====================>\";\n System.out.println(s); \n //writeFile(s, \"file:///SDCard/uploadedfile.txt\");\n deleteFile(\"file:///system/databases/TestApp/TestDB.db\");\n }\n };\n\n UiApplication.getUiApplication().invokeLater(new Runnable(){\n public void run() {\n UiApplication.getUiApplication().pushScreen(new TestScreen()); \n }\n });\n }\n\n\nA: Add listener before the theApp.enterEventDispatcher(); call.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635751\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967663,"cells":{"text":{"kind":"string","value":"Q: Which features of BizTalk are essential? I collect information about BizTalk and all its stuff. I'm curious about what are the best practices when developing a new integration project? Should I really use ESB Toolkit (which seems to me quite odd and way complex)? Is it really a bad idea to use UDDI services? What components of BizTalk do you really use?\n\nA: I guess the answer to your question is dependent on the problem(s) you're trying to solve.\nI've recently finished a project for which I considered using the ESB Toolkit for error handling but eventually decided that the scope of the project wasn't big enough for the extra effort required to setup and learn how to use it!\nFor me, the most useful \"feature\" of BizTalk I use is direct-binding in my orchestrations to produce de-coupled orchestrations. But again, thats what I needed for the specific scenario.\nBizTalk is a massive product and I would suggest that you use the available functionality only if it solves you problem simply (don't attempt to provide over-engineered solutions!)\nBy all means investigate all the functionality that interests you; there's a huge store of resource available and lots of helpful individuals here on SO!\nThere's my pennies worth :)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635753\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967664,"cells":{"text":{"kind":"string","value":"Q: How to inject PesistenceContext in my tests using EJB 3.1? Hi in Spring it's easy to do so... as Spring doesn't require an Container, you just add an @autowired and it's done.\nBut in EJB 3.1, using @Inject is useless if the app is not deployed... I am getting nullpointer and it's looks logical to get them, because of the lack of a container during tests.\nHow can I inject a PersistenceContext into my TESTS for example using only EJB 3.1 features ? is it possible without a container ?\n\nA: Take a look at the Arquillian project. It allows outside container testing of Java EE applications.\nhttp://www.jboss.org/arquillian\n\nA: Glassfish 3.x will allow you to embed the container and run your tests. Here's a few links that should get you going:\n\n\n*\n\n*Unit Testing EJBs and JPA with Embeddable GlassFish\n\n*JPA Unit testing with the GlassFish 3 embedded EJB container\n\n*Adam Bien's Weblog\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635756\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967665,"cells":{"text":{"kind":"string","value":"Q: How to access non-visible flex components? I'm a newbie to flex and am building a flex 4.5 app that has a custom component extending SkinnableContainer. This custom component is basically a kind of collapsible panel. When you open it you see all the controls in the contentGroup, when you close they go away and you are left with the title. This is done in the skin by having the contentGroup included only in the open state.\nI have a bunch of these containers in the app, some open by default and some closed.\nSo in mxml the structure looks like:\n\n \n \n \n \n \n\n\nMy problem is that i cannot access (via actionscript, eg in event handling) the components from the closed containers (and indeed their initialize event code does not run) until they have been opened at least once.\nDoing some digging i found that flex has some kind of performance enhancement regarding deferred creation of components. So thinking that this must the answer i set creationPolicy to \"all\" on the SkinnableContainer:\n\n\nBut this does not work. Any ideas?\nUPDATE: Full example below\nRevealer.as The skinnable container (taken from book Flex 4 in Action and stripped down a bit)\npackage\n{\nimport flash.events.Event;\n\nimport spark.components.SkinnableContainer;\nimport spark.components.ToggleButton;\nimport spark.components.supportClasses.TextBase;\n\n[SkinState(\"open\")]\n[SkinState(\"closed\")]\n[SkinState(\"disabled\")] //Not used: just appeasing compiler in the skin when host component is defined.\n[SkinState(\"normal\")] //Not used: just appeasing compiler in the skin when host component is defined.\n\npublic class Revealer extends SkinnableContainer\n{\n private var m_open:Boolean = true;\n private var m_label:String;\n\n [SkinPart]\n public var toggler:ToggleButton;\n\n [SkinPart(required=\"false\")]\n public var labelDisplay:TextBase;\n\n\n public function Revealer()\n {\n super();\n }\n\n public function get open():Boolean { return m_open; } \n public function set open( value:Boolean ):void\n {\n if( m_open == value )\n return;\n m_open = value;\n invalidateSkinState(); \n invalidateProperties();\n } \n\n public function get label():String { return m_label; }\n public function set label( value:String ):void\n {\n if( m_label == value )\n return;\n m_label = value;\n if( labelDisplay != null )\n labelDisplay.text = value;\n }\n\n override protected function getCurrentSkinState():String { return m_open ? \"open\" : \"closed\"; }\n\n override protected function partAdded( name:String, instance:Object ):void\n {\n super.partAdded( name, instance );\n if(instance == toggler) \n {\n toggler.addEventListener( Event.CHANGE, toggleButtonChangeHandler );\n toggler.selected = m_open;\n }\n else if( instance == labelDisplay )\n {\n labelDisplay.text = m_label;\n }\n }\n\n private function toggleButtonChangeHandler( e:Event ):void\n {\n open = toggler.selected; \n }\n}\n}\n\nRevealerSkin.mxml The skin for the container\n\n\n[HostComponent(\"Revealer\")]\n\n \n \n \n \n\n\n \n\n\n \n\n\n\n\n\nMyControl.mxml A custom control placed inside the container\n\n\n\n \n\n\n \n\n\n \n \n \n\n\n\nRevealerTest.mxml A sample app to demonstrate the problem\n\n\n\n \n\n\n \n \n \n \n \n \n \n \n \n \n\n\n\nNote that if you hit the click me button before opening the second container we are unable to get the value from the control in the initially collapsed group. Opening the group once allows access to the value. Collapsing the group is still ok. It's the first time that's the problem. I have added creationPolicy to the container and itemCreationPolicy to the content group in the skin but no luck!\n\nA: Actually, it's not creationPolicyyou are looking for but itemCreationPolicy. This is a property of your hidden element (contentGroup). You have to set it to immediate to access the element event if it is not displayed due to currentState.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635759\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967666,"cells":{"text":{"kind":"string","value":"Q: Application selection dialog based on filetype I'm trying to create a Dialog, which will display a list of availible applications to open a given filetype.\nI've been looking at some question here on stackoverflow that work with the same issue, but I get lost due to lacking answer. In particular I've been looking at this question:\nIn Android, How can I display an application selector based on file type?\nMy follow-up question is then: \n\n\n*\n\n*What to do with the List?\n\n*How can I display the availible applications with name and icon?\n\n*When the user selects an application, how can I start it based on the ResolveInfo of the selected item?\n\n\nA: I found a solution, that gives me a full list of applications that can open a given mimetype. It's not the best, as I would like the list to be more specific and just a few applications (e.g. if it was an URL I wanted to open only browsers would show up) but serves the purpose.\nHere is what I did:\nFile file = new File( \"myFileLocation.txt\" );\nString extension = MimeTypeMap.getFileExtensionFromUrl( file.getPath() );\nString type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);\n\nIntent intent = new Intent();\nintent.setAction( Intent.ACTION_VIEW );\nintent.setDataAndType( Uri.fromFile( file ), type ); \ncontext.startActivity( intent );\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635764\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967667,"cells":{"text":{"kind":"string","value":"Q: jQuery: Finding link best matching to current URL I have the following code which tries to add a class of selected to a link that matches the url:\nvar pathname = window.location.pathname;\n\n$(document).ready(function ()\n{\n $('ul#ui-ajax-tabs li a').each(function()\n {\n if (pathname.indexOf($(this).attr('href')) == 0)\n {\n $(this).parents('li').addClass('selected');\n }\n });\n});\n\n1.) So for example if I have a url like /Organisations/Journal and /Organisations/Journal/Edit a link with Organisations and Journal will show as being selected. This is fine!\n2.) However sometimes I have urls like: /Organisations and /Organisations/Archived and if I have a link to the Archived then both will be selected BUT I don't want this to happen because the Organisations like doesn't have the second part of the url so shouldn't match.\nCan anyone help with getting this working for the second types Without breaking the first type? Also none of this can be hardcoded regex looking for keywords as the urls have lots of different parameters!\nCheers\nEXAMPLES:\nIf the url is /Organisations/ Or /Organisations then a link with /Organisations should be selected. If the URL is /Organisations/Journal/New then a link with /Organisations/Journal or /Organisations/Journal/New would be selected.\nBUT if I have a url with /Organisations/Recent and have two links: /Organisations and /Organisations/Recent then only the second should be selected! So the thing to note here is that it must have a third parameter before it should look for bits of the URL more loosly rather than an exact match.\nRemember it might not always be Organisations so it can't be hardcoded into the JS!\n\nA: Why dont u use \nif($(this).attr('href') == pathname )\n\ninstead of \nif (pathname.indexOf($(this).attr('href')) == 0)\n\n\nA: Edit: My previous solution was quite over-complicated. Updated answer and fiddle.\nvar pathname = window.location.pathname;\n\n$(document).ready(function ()\n{\n var best_distance = 999; // var to hold best distance so far\n var best_match = false; // var to hold best match object\n\n $('ul#ui-ajax-tabs li a').each(function()\n {\n if (pathname.indexOf($(this).attr('href')) == 0)\n {\n // we know that the link is part of our path name.\n // the next line calculates how many characters the path name is longer than our link\n overlap_penalty = pathname.replace($(this).attr('href'), '').length;\n if (overlap_penalty < best_distance) { // if we found a link that has less difference in length that all previous ones ...\n best_distance = overlap_penalty; // remember the length difference\n best_match = this; // remember the link\n }\n }\n });\n\n if (best_match !== false)\n {\n $(best_match).closest('li').addClass('selected');\n }\n});\n\nThe best match is calculated like so:\nAssume our pathname is \"/foo/bar/baz/x\".\nWe have two links in question:\n\n\n*\n\n*/foo/bar/\n\n*/foo/bar/baz\n\n\nThis is what happens:\n\n\n*\n\n*/foo/bar/baz/x (the first link's url is deleted from the path name pathname.replace($(this).attr('href'), ''))\n\n*\"baz/x\" is what remains.\n\n*The character count (length) of this remainder is 5. this is our \"penalty\" for the link.\n\n*We compare 5 to our previous best distance (if (overlap_penalty < best_distance)). 5 is lower (=better) than 999.\n\n*We save this (being the
DOM object) for possible later use.\n\n*The second link is handled in the same manner:\n\n*/foo/bar/baz/x (the second link's url is deleted from the path name)\n\n*\"/x\" is what remains.\n\n*The character count of this remainder is 2.\n\n*We compare 2 to our previous best distance (being 5). 2 is lower than 5.\n\n*We save this (being the DOM object) for possible later use.\n\n\nIn the end, we just check if we found any matching link and, if so, apply addClass('selected') to its closest
  • parent.\n\nA: \n\n\n \n \n \n \n\n\n \n\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635766\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967668,"cells":{"text":{"kind":"string","value":"Q: Android NDK setup in Ubuntu 10.10 Hi All I am new to Android JNI. I have Ubuntu 10.10, android sdk, android-ndk-r6. All my path vaiables are set like platform-tools in sdk, android ndk path, java path etc. When I try to compile Hello-Jni sample in ndk samples folder i getting error \n/home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:17:20: error: string.h: No such file or directory\n/home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:18:17: error: jni.h: No such file or directory\n/home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:27: error: expected '=', ',', ';', 'asm' or 'attribute' before 'Java_com_example_hellojni_HelloJni_stringFromJNI'\nWhat might be the issue?\nI searched google which provided following link\nhttp://comments.gmane.org/gmane.comp.handhelds.android.ndk/13082\nBut i didnot get what symbolic links he is talking.\nCan any one guide me?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635769\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967669,"cells":{"text":{"kind":"string","value":"Q: Warning while declaring versions of dependencies in POM When I specify version of my dependencies within pom.xml, there's a warning :\nOverrides version defined in PluginManagement. The managed version is _____.\n\nWhat does this mean and how do I rectify it ?\n\nA: That message would mean that the version you have specified for a plugin is different than the version \"recommended\" by the parent (has nothing to do with deps). You are allowed to do this. \nPlugin Management\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635775\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967670,"cells":{"text":{"kind":"string","value":"Q: projects and gitolite remote on same machine I'm trying to setup a new development server that also will serve as a git remote host.\nSome people will be developing on the server and push to the remote and some use there own machine and push to the server when there done.\nWe are using gitolite to facilitate those who work on there own machine so the can push and pull with there private key.\nThe problem now is that those working on the server itself have a hard time cloning, pushing and pulling. There are always permission problems with are hard to get around.\nIt just doest feel like this is the way it should work, so i was wondering if our setup is right or are we just using it in the wrong way (maybe we don't even need gitolite?)\n\nA: gitolite isn't really designed to also support people cloning on the local machine, since it does all of its permissions magic via ssh hooks.\nYou could just have those working on the server clone via SSH anyways, to make sure everyone's process is paralleled. Thus, instead of the people on the local machine doing this:\ngit clone /path/to/repo\n\nhave them do this:\ngit clone git@localhost:path/to/repo\n\n(And set up their ssh keys in gitolite as you do for everyone else.)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635784\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967671,"cells":{"text":{"kind":"string","value":"Q: trend towards MVC as opposed to web forms in ASP.net? I know there will always be uses for both methodologies, but to those who work various contract jobs or attend conferences, do you see a trend towards MVC as being the preference for most ASP.net development. I understand this will involve lots of opinion on if you prefer one method to the other, but was curious.\nThanks for insight you might have\nI apologize if this question is out of scope for the discussion. I didn't think about that when I asked it to begin with. I'm doing some dev in both and was trying to get a better idea of direction to take. No worries then if this question is deleted or just dies.\n\nA: I havn't been in the industry for very long, but from what I have noticed everyone seem to prefer MVC and all new projects we start are built using MVC3 :)\n\nA: Some people enjoy challenges, and Webforms can be very challenging for large scale applications. ;)\nSome people prefer to take the path of least resistance. MVC can often times be that.\nYes, it's new. And as such, there's a certain amount of \"oooh, shiny\" mentality, but MVC really does bring a lot to the table that Webforms makes more difficult. Webforms, however, still has the drag and drop features that many people crave.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635790\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967672,"cells":{"text":{"kind":"string","value":"Q: rails 3 not nil I'm trying to select all records that are not null from my table using where method\nMyModel.where(:some_id => !nil) \n\nbut it doesn't work, is there any other solution to do this?\n\nA: Use a string rather than a hash\nMyModel.where(\"some_id is not null\")\n\n\nA: You can use:\nMyModel.where(\"some_id IS NOT NULL\") \n\n\nA: You can do it using the Arel syntax (which has the bonus of being database independent):\nMyModel.where(MyModel.arel_table['some_id'].not_eq(nil))\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635791\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"8\"\n}"}}},{"rowIdx":1967673,"cells":{"text":{"kind":"string","value":"Q: How Long is the iPad Roation Duration? Pretty simple question but I can't seem to find an answer. Does anyone know the length in seconds the duration of the iPad Roation animation? I can guess that it's something short like 0.5 or 1 second long but if anyone knows an exact number it would be handy.\nThanks!\n\nA: - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration\nIf you are trying to do something in sync use the above method and grab the duration. And ideally also initiate the animation you wish to perform there as well.\nAlso I believe its 0.4, most standard animations are 0.3 or 0.4s. IIRC\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635794\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967674,"cells":{"text":{"kind":"string","value":"Q: jQuery Created Nested List Based on Attribute I get stuck when trying to implement recursive logic in jQuery--I don't have much practice with it. I have a simple need, which is to nest unsorted lists by class. What I have is two dynamic lists on a page (they're generated by two CAML queries). The first list will be the top level
  • and the second list will be nested. The first list has
  • s with numeric id's and the second list has
  • s with numeric classes that match the id's that they have to be nested under. i.e.:\n
      \n
    • Parent Item 1
    • \n
    • Parent Item 2
    • \n
    \n
      \n
    • Child 1
    • \n
    • Child 2
    • \n
    • Child X
    • \n
    \n\nThere will be an undetermined number of parents and child
  • s over time. Also, if it's better to use a different attr than class for the children that's fine. Ultimately I'll want to add more classes for CSS. Any help would be greatly appreciated.\n\nA: Working example here: http://jsfiddle.net/rkCKT/\nAssuming this markup:\n
      \n
    • Parent Item 1
    • \n
    • Parent Item 2
    • \n
    \n
      \n
    • Child 1
    • \n
    • Child 2
    • \n
    • Child X
    • \n
    \n\nthis would work:\n$(document).ready(function(){\n $('ul.children li').each(function(){\n probable_parent = $('ul.parents li#' + $(this).attr('class'));\n if (probable_parent.length)\n {\n if (!probable_parent.find('ul').length) probable_parent.append('
      ');\n $(this).detach().appendTo(probable_parent.find('ul'));\n }\n });\n});\n\n\nEdit:\nAs soon as you add any classes to the .children lis for presentational reasons, everything will be broken.\nFor this and half a million other reasons, if your document is HTML5, I strongly suggest using proper attributes for the parent-child relationship. Ideally, the markup would look something like this:\n
        \n
      • Parent Item 1
      • \n
      • Parent Item 2
      • \n
      \n
        \n
      • Child 1
      • \n
      • Child 2
      • \n
      • Child X
      • \n
      \n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635795\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967675,"cells":{"text":{"kind":"string","value":"Q: Get unique values using XSLT 1.0 (Without using XSL:Key) I'm facing a typical problem while am getting the Unique list using XSLT 1.0.\nSample XSLT:\n\n \n // Do something\n // I can't implement this using \"Muenchian Method\". \n // Since, I can't declare inside of \n // There is no chance to declare on top.\n // I should get unique list from here only\n\n\nfilepath variable would contain XML as follows:-\n\n \n \n Information 102\n \n \n \n \n Information 78\n \n \n \n \n Information 34\n \n \n \n \n Information 55\n \n \n \n \n Information 86\n \n \n \n \n Information 100\n \n \n\n\nOutput: Unique list of code should be \nabc\ndef\nxyz\n\nThanks\n\nA: \n \n\n \n \n \n\n \n \n &#xD;\n \n\n\n\n\nA: \n\n \n // Do something\n // I can't implement this using \"Muenchian Method\". \n // Since, I can't declare inside of \n // There is no chance to declare on top.\n // I should get unique list from here only\n\n\n\nIt isn't true that one cannot use and the key() function in such circumstances:\n\n \n \n\n \n\n \n\n \n \n \n \n Information 102\n \n \n \n \n Information 78\n \n \n \n \n Information 34\n \n \n \n \n Information 55\n \n \n \n \n Information 86\n \n \n \n \n Information 100\n \n \n \n \n\n \n\n \n \n \n \n \n \n \n \n \n\n\n\nwhen this transformation is applied to any XML document (not used in this example), the wanted, correct result is produced:\nabc def xyz \n\n\nA: Your reason for not using the Muenchian method or xsl:key is spurious. It will work perfectly well. You have probably failed to understand that when you declare a key definition, it is not specific to one particular source document, it allows you to use the key() function against any source document.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635799\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967676,"cells":{"text":{"kind":"string","value":"Q: Can compiler optimizations, like ghc -O2, change the order (time or storage) of a program? I've got the feeling that the answer is yes, and that's not restricted to Haskell. For example, tail-call optimization changes memory requirements from O(n) to O(l), right?\nMy precise concern is: in the Haskell context, what is expected to understand about compiler optimizations when reasoning about performance and size of a program? \nIn Scheme, you can take some optimizations for granted, like TCO, given that you are using an interpreter/compiler that conforms to the specification.\n\nA: Yes, in particular GHC performs strictness analysis, which can drastically reduce space usage of a program with unintended laziness from O(n) to O(1).\nFor example, consider this trivial program:\n$ cat LazySum.hs\nmain = print $ sum [1..100000]\n\nSince sum does not assume that the addition operator is strict, (it might be used with a Num instance for which (+) is lazy), it will cause a large number of thunks to be allocated. Without optimizations enabled, strictness analysis is not performed.\n$ ghc --make LazySum.hs -rtsopts -fforce-recomp\n[1 of 1] Compiling Main ( LazySum.hs, LazySum.o )\nLinking LazySum ...\n$ ./LazySum +RTS -s\n./LazySum +RTS -s \n5000050000\n 22,047,576 bytes allocated in the heap\n 18,365,440 bytes copied during GC\n 6,348,584 bytes maximum residency (4 sample(s))\n 3,133,528 bytes maximum slop\n 15 MB total memory in use (0 MB lost due to fragmentation)\n\n Generation 0: 23 collections, 0 parallel, 0.04s, 0.03s elapsed\n Generation 1: 4 collections, 0 parallel, 0.01s, 0.02s elapsed\n\n INIT time 0.00s ( 0.00s elapsed)\n MUT time 0.01s ( 0.03s elapsed)\n GC time 0.05s ( 0.04s elapsed)\n EXIT time 0.00s ( 0.00s elapsed)\n Total time 0.06s ( 0.07s elapsed)\n\n %GC time 83.3% (58.0% elapsed)\n\n Alloc rate 2,204,757,600 bytes per MUT second\n\n Productivity 16.7% of total user, 13.7% of total elapsed\n\nHowever, if we compile with optimizations enabled, the strictness analyzer will determine that since we're using the addition operator for Integer, which is known to be strict, the compiler knows that it is safe to evaluate the thunks ahead of time, and so the program runs in constant space.\n$ ghc --make -O2 LazySum.hs -rtsopts -fforce-recomp\n[1 of 1] Compiling Main ( LazySum.hs, LazySum.o )\nLinking LazySum ...\n$ ./LazySum +RTS -s\n./LazySum +RTS -s \n5000050000\n 9,702,512 bytes allocated in the heap\n 8,112 bytes copied during GC\n 27,792 bytes maximum residency (1 sample(s))\n 20,320 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Generation 0: 18 collections, 0 parallel, 0.00s, 0.00s elapsed\n Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed\n\n INIT time 0.00s ( 0.00s elapsed)\n MUT time 0.01s ( 0.02s elapsed)\n GC time 0.00s ( 0.00s elapsed)\n EXIT time 0.00s ( 0.00s elapsed)\n Total time 0.01s ( 0.02s elapsed)\n\n %GC time 0.0% (2.9% elapsed)\n\n Alloc rate 970,251,200 bytes per MUT second\n\n Productivity 100.0% of total user, 55.0% of total elapsed\n\nNote that we can get constant space even without optimizations, if we add the strictness ourselves:\n$ cat StrictSum.hs \nimport Data.List (foldl')\nmain = print $ foldl' (+) 0 [1..100000]\n$ ghc --make StrictSum.hs -rtsopts -fforce-recomp\n[1 of 1] Compiling Main ( StrictSum.hs, StrictSum.o )\nLinking StrictSum ...\n$ ./StrictSum +RTS -s\n./StrictSum +RTS -s \n5000050000\n 9,702,664 bytes allocated in the heap\n 8,144 bytes copied during GC\n 27,808 bytes maximum residency (1 sample(s))\n 20,304 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Generation 0: 18 collections, 0 parallel, 0.00s, 0.00s elapsed\n Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed\n\n INIT time 0.00s ( 0.00s elapsed)\n MUT time 0.00s ( 0.01s elapsed)\n GC time 0.00s ( 0.00s elapsed)\n EXIT time 0.00s ( 0.00s elapsed)\n Total time 0.00s ( 0.01s elapsed)\n\n %GC time 0.0% (2.1% elapsed)\n\n Alloc rate 9,702,664,000,000 bytes per MUT second\n\n Productivity 100.0% of total user, 0.0% of total elapsed\n\nStrictness tends to be a bigger issue than tail calls, which aren't really a useful concept in Haskell, because of Haskell's evaluation model.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635805\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"10\"\n}"}}},{"rowIdx":1967677,"cells":{"text":{"kind":"string","value":"Q: Java + Linked-List + Polymorphic Objects \"Would you recommend inheriting off of the built in Linked List in order to customize it for my polymorphic objects? or should I build a Linked List from scratch?\"\n\nA: I'm not really sure what the context is here, but I would never (well, almost never) build a Linked List from scratch. What you could consider instead of inheritance is using delegation by the way. Define an interface for your 'polymorphic objects' and simply delegate all linked list related calls to the Linked List.\n\nA: I wouldn't write your own unless you really really really have to. By \"polymorphic objects\" I am assuming you mean you have a class hierarchy and want to put instances of any of those classes in the list. Nothing prevents you from doing that, although the generics will place limits on the types the compiler sees, you can get around by casting as a last resort. Or you can just declare a list with no generic types, although in that case you lose all the compile-time checking you could get.\nFor 99.9999% of cases, the default LinkedList implementation is going to be fine. It's probably a better idea to use it than roll your own, unless the default implementation is completely inadequate. If you think it might be, update your question or start a new one with very explicit details. There is probably a good way to work with the default implementation.\nAll that said, if this is for learning, feel free to write you own linked list. Also note that anything you come up with will at best have to follow the same rules of generics/typing that the default LinkedList has. If you build your 'polymorphic objects' directly into the list, that's fine, but you have just created a really specific implementation that will only be useful for you (which might be ok).\n\nA: If you need to create your own version of LinkedList that changes the behavior of one or more methods, you should use the Decorator pattern. I would also suggest using Guava's ForwardingList class which does most of the work for you.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635806\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":1967678,"cells":{"text":{"kind":"string","value":"Q: How to use sed to remove all double quotes within a file I have a file called file.txt. It has a number of double quotes throughout it. I want to remove all of them.\nI have tried sed 's/\"//g' file.txt\nI have tried sed -s \"s/^\\(\\(\\\"\\(.*\\)\\\"\\)\\|\\('\\(.*\\)'\\)\\)\\$/\\\\3\\\\5/g\" file.txt\nNeither have worked.\nHow can I just remove all of the double quotes in the file?\n\nA: Additional comment. Yes this works:\n sed 's/\\\"//g' infile.txt > outfile.txt\n\n(however with batch gnu sed, will just print to screen)\nIn batch scripting (GNU SED), this was needed:\n sed 's/\\x22//g' infile.txt > outfile.txt\n\n\nA: Try this:\nsed -i -e 's/\\\"//g' file.txt\n\n\nA: Are you sure you need to use sed? How about:\ntr -d \"\\\"\"\n\n\nA: Try prepending the doublequote with a backslash in your expresssion:\nsed 's/\\\"//g' [file name]\n\n\nA: For replacing in place you can also do:\nsed -i '' 's/\\\"//g' file.txt\n\nor in Linux\nsed -i 's/\\\"//g' file.txt\n\n\nA: You just need to escape the quote in your first example:\n$ sed 's/\\\"//g' file.txt\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635807\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"55\"\n}"}}},{"rowIdx":1967679,"cells":{"text":{"kind":"string","value":"Q: Setting up multiple domains for single app_id Facebook recently added the option for multiple domain support within an app. You can find the post here:\nhttps://developers.facebook.com/blog/post/570/\nHowever, when I add the second domain to the app_domain, I get the following error:\nError\nsiteB.org must be derived from your Site URL.\nMy site URL is: fb.siteA.com\nCan you add additional site URLs that are comma delimited? e.g. fb.siteA.com, www.siteB.org\nThoughts? What needs to be adjusted?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635822\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967680,"cells":{"text":{"kind":"string","value":"Q: Distribute a sqlite database with a BlackBerry application How can I deploy my application with sqlite database?\n\nA: I do not understand your question but these articles may be helpful: \n\n\n*\n\n*A java.net article: Getting Started with Java and SQLite on Blackberry OS 5.0 \n\n*In the BlackBerry developer knowledge base: Storing data in SQLite databases\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635826\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":1967681,"cells":{"text":{"kind":"string","value":"Q: Load a webpage in another webpage with jQuery using .load I'm looking for a way to load a webpage in another webpage using .load in jQuery.\nThe instructions listed on the page weren't very clear.\nLet's say the domain is \"example.com\" and the page I'm trying to load is located at \"example.com/page\".\n\nA: API explains enough: http://api.jquery.com/load/\n$('#result').load('/page');\nWhere #result is the div with id result. Inside that div, the page /page will be loaded.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635831\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967682,"cells":{"text":{"kind":"string","value":"Q: Where to store methods in MVC projects In MVC3, where is the best place to store methods\nI am currently racking up quite a bit of code in my HomeController and feel that my methods should be seperate from the controller logic. \nShould I create a model with a class of \"HomeControllerMethods\" or something?\n\nA: Definitely do not put them inside your controllers if they are not specific to a controler and if they don't use the properties or methods of that controller.\nPut them some other place. Where you need to put them is up to you. I always create another project called MyApp.Infrastructure.\n\nA: Well, application architecture is your own choice which must be dictated by your conrete use cases. Try reading about three tier pattern to begin with\n\nA: Here is an answer https://codereview.stackexchange.com/questions/981/not-feeling-100-about-my-controller-design discussing a similar topic.\nAnother great resource is www.tekpub.com I've just gone through the ASP.NET MVC3 Real World series. This series goes along at a cracking pace, and Rob uses an Infrastructure folder similar to @tugberk's advice.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635833\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967683,"cells":{"text":{"kind":"string","value":"Q: How to check for Is Not Null in VBA? Hi I have the following expression. I'm trying to say \"if the second field Is Not Null\". Can you help.\nThanks\n=Iif((Fields!approved.Value = \"N\" & Fields!W_O_Count.Value IsNotNull), \"Red\", \"Transparent\")\n\n\nA: Use Not IsNull(Fields!W_O_Count.Value)\nSo:\n=IIF(Fields!approved.Value = \"N\" & Not IsNull(Fields!W_O_Count.Value)), \"Red\", \"Transparent\")\n\n\nA: you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise. \nNot IsNull(Fields!W_O_Count.Value)\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635835\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"38\"\n}"}}},{"rowIdx":1967684,"cells":{"text":{"kind":"string","value":"Q: Django queryset excluding many to many objects Let's assume we have a model:\n class a(models.Model):\n users = models.ManyToManyField(User) # django.contrib.auth.models.User\n\nand these variables:\nuser = request.user\nqueryset = a.objects.all()\n\nThen I want to exclude these records from a model that contains the user in users. How can I do that?\nqueryset.exclude(...)\n\n\nA: It's as simple as this:\nqueryset.exclude(users=user)\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635838\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":1967685,"cells":{"text":{"kind":"string","value":"Q: Deleting from a List In this code, when I select an element from the middle of the list and delete, the elements below the selected element are also removed from \"view\". But they are present in the database and appear once again when the app is run. Please help me with this mistake. Thanks.\nDeleteController delController = new DeleteController();\ndelController.deleteInfo(dbId);\nthis.jList1 = list;\nAbstractListModel model = (AbstractListModel) jList1.getModel();\nint numberElements = model.getSize();\nfinal String[] allElements = new String[numberElements + 1];\nfor (int i = 0; i < numberElements - 1; i++) {\n String val = (String) model.getElementAt(i);\n if (!dbId.equals(val)) {\n allElements[i] = (String) model.getElementAt(i);\n }\n}\njList1.setModel(new javax.swing.AbstractListModel() {\n\n String[] strings = allElements;\n\n public int getSize() {\n return strings.length;\n }\n\n public Object getElementAt(int i) {\n return strings[i];\n }\n});\n\n\nA: Use DefaultListModel. It has removeElementAt() method\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635840\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":1967686,"cells":{"text":{"kind":"string","value":"Q: Live checking value of textarea I have a textarea that have a id upload-message. And this jvavscript:\n // step-2 happens in the browser dialog\n $('#upload-message').change(function() {\n $('.step-3').removeClass('error');\n $('.details').removeClass('error');\n });\n\nBut how can i check this live? Now, i type in the upload message textarea. And go out of the textarea. Than the jquery function is fired. But how can i do this live?\nThanks\n\nA: With .keyup:\n$('#upload-message').keyup(function() {\n $('.step-3, .details').removeClass('error');\n});\n\nHowever, this'll keep on running for every keypress, which in the case you provided does not make sense.\nYou should rather bind it once with one:\n$('#upload-message').one('keyup', function() {\n $('.step-3, .details').removeClass('error');\n});\n\n...so that this event will only fire once.\n\nA: Simply bind some code to the keyup event:\n$('#upload-message').keyup(function(){\n //this code fires every time the user releases a key\n $('.step-3').removeClass('error');\n $('.details').removeClass('error');\n});\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635841\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":1967687,"cells":{"text":{"kind":"string","value":"Q: Securing cron file I've have a cron file, monthly.php and I want to prevent direct access using web browser. It should be accessible only through CPanel cron.\nThanks.\n\nA: Don't put it under the webroot. Just execute it using the command line php program.\n\nA: You can use a .htaccess to deny access to it. Or you can just move it out of the htdocs or public_html directory.\n\n Order deny,allow\n Allow from name.of.this.machine\n Allow from another.authorized.name.net\n Allow from 127.0.0.1\n Deny from all\n\n\nSo it can only be requested from the server.\n\nA: If you, for some reason, need to put it in a webroot, try the following: Can PHP detect if its run from a cron job or from the command line?\n\nA: Just pass in a key to it to protect it. And don't report \"Key parameter is missing\" to the browser, just die() if the key is not there. And please, dont use the parameter \"key\", use something of your own like:\nhttp://myscript.com/monthly.php?mycomplexkeyname=ksldhfguorihgiauzsiludrfthgo45j1234134\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635842\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967688,"cells":{"text":{"kind":"string","value":"Q: Posting two games with same bundle identifier i am using game center into my app only for the leaderboard. I planned to release the app in two different mode(free and premium). Can i able to have two apps with same name and bundle identifer? if not is there is any way to do that?\n\nA: You have to change the bundle identifier. It must be unique. If you try to load one version, it will wipe the other.\nIf you want to do two apps, just change the bundle identifier. iirc you can still use the same name for both.\n\nA: Even the correct answer is no it's not possible to use the same BundleID BUT as I assume you'd like to use the same leader board for both apps, and this is possible!\nFrom iOS 6 you can use Game Center Group and both or more apps could feed the same group leader boards or achievements.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635843\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967689,"cells":{"text":{"kind":"string","value":"Q: Querying the client periodically for update via sockets-Reusing ports using the Controller.java, I' implementing the run() in NetworkDiscovery.java which queries all the machine in the subnet . The active machines reply with their status. This happens at regular intervals.\npublic class Controller {\nNetworkDiscovery n;\npublic static int discoveryInterval=2000;\nPM pmList;\nList pmlist=(List) new PM();\n\npublic static void main(String[] args) throws UnknownHostException{\nTimer t1=new Timer();\nt1.scheduleAtFixedRate(new NetworkDiscovery(), 2000, discoveryInterval);\n}\n\npublic class NetworkDiscovery extends TimerTask{\n\nInetAddress controllerIP;\nint controllerPort;\n\nNetworkDiscovery() throws UnknownHostException {\n controllerIP=InetAddress.getLocalHost();\n controllerPort=4455;\n}\n\n@Override\npublic void run() {\n try {\n byte[] recvBuf = new byte[5000];\n DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);\n DatagramSocket dSock = new DatagramSocket(4445);\n dSock.receive(packet);\n//implementation related code follows\n**dSock.close();**\n}\n}\n\nOn the client's side a similar Datagram socket is opened and objects are received/sent.\nThe problem is that on the COntroller's side, I'm executing NetworkDiscovery's run() after a specific time interval and during the second execution it says - \n\njava.net.BindException: Address already in use\n\nSince I'm closing the Controller's socket by close(), why does it still show that this address is already being in use? How can I make sure that during the next iteration, the controller starts over fresh call of networkDiscovery?\n\nA: Perhaps the second task starts before the first was completly executed? Have you tried to insert debug messages and see if the first task was finished?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635844\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967690,"cells":{"text":{"kind":"string","value":"Q: Android switching between layout(Forms) I am fairly new to the android development platform.\nI am developing a small android help desk application, as a project. My problem is switching between my layouts. now there are a lot of help on the internet but could not find anything use full to my application.\nI have a \"main.xml\" layout file and a \"login.xml\" layout file. I can not find a proper way to switch between the two layouts.\nI though setting the context view to the other layout will work. but i keep on getting a force close message on my simulator\n setContentView(R.layout.login);\n\nSo as you can see i have an login screen and as soon as the user logged in the layout needs to change to the main layout.\n\nA: In Android, you can not change the content view of the activity.\nHowever, you can create a new activity for example LoginActivity and set its content view with\nsetContentView(R.layout.login); and then you can switch to this layout by creating an intent which will open the new activity as below.\nstartActivity(new Intent (YourActivity.this, TheActivitytobeopened.class));\n\nA: I have an activity with a LinearLayout. And then I dynamically add and remove views to it. \nLinearLayout llMain = (LinearLayout) this.findViewById(R.id.room_layout_main);\nroomView = new RoomView(this);\nllMain.addView(roomView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));\n//use llMain.removeView(roomView) to remove it\n\nI am pretty sure you can load views from xml but I am not sure. Hope that helps. \nEDIT- looks like you can load a view from xml, see here: http://www.aslingandastone.com/2011/dynamically-changing-android-views-with-xml-layouts/\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635848\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967691,"cells":{"text":{"kind":"string","value":"Q: How to get line number in XSLT? Is it possible to get the line number when we apply XSLT to an XML? I need to know the line number when there is a particular template match found in the XML. \nIs it possible to retrieve the line number?\n\nA: If you mean the line number of the node in the source document, Saxon provides this using an extension function saxon:line-number(), provided the source document is supplied via an interface (e.g. a SAX parser) that reports line numbers. There's no standard XSLT mechanism for this.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635850\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"6\"\n}"}}},{"rowIdx":1967692,"cells":{"text":{"kind":"string","value":"Q: How to store user credentials in an ASP.NET MVC website My settings is as follows: \nI have an MVC web application (EbWebApp) which has a service reference to an WCF service named EbServiceApp. For authentication purposes I implemented a forms authentication scenario: \nThe user logs on to the web site, and then in turn I authenticate the user to the web service (using forms authentication) too. For this I created another web service named AuthService. \nEverything works just fine but when the forms authentication ticket expires for the web service I would have to relog on the user to the webservice without asking for username and password (this scenario can happen for example if I set a persistent cookie on the website for the user). I don't know how could I store the user's credentials to be available for reconnection to the web service.\nAny help is appreciated.\n\nA: Warning! Warning! Warning!\nWhenever you think \"How can i store the users credentials so i can automatically log them in later?\" then you are doing something very dangerous. If you can log them in later, then someone can steal those credentials. It's ALWAYS a bad idea.\nIf the forms authentication ticket expires, then only the end user should be able to log himself back in. Otherwise, you're defeating the purpose of a ticket expiry. If you want the ticket to last longer, then just set its expiration to be longer.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635862\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967693,"cells":{"text":{"kind":"string","value":"Q: Store data in the internal memory not on the sd card? I've been developing a content-based app for Android and I have over 120 MB of data that i need to store on the phone. I download this data from a server when the user first runs the app. My first question is, is it ok if I store this data on the internal memory of the app using Context.getDir() method or is it better to store it on the sd card using Environment.getExternalStorageDirectory(). The problem with storing it on the sd card is that I would then have to secure this data somehow otherwise they would be accessible to every other app or person. My second question is if it's okey to store that amount of data in the internal memory of the app then are they secure there?\n\nA: For the First Question and For the Second Question\n\nIf you're intend to saving files to the internal memory, you'll just need to call a method like this: \nFileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); \nIf you set the Context.MODE_PRIVATE, it is not visible for other apps and even for you and user. Of course, this MODE_PRIVATE is useful only for the phone without root access. Those phones who have get rooted will have access to any folder in internal memory no matter if you set PRIVATE MODE or not.\nTherefore if you decide to save your files in internal memory, despite of the sizes, you need to use some kind of encryption if you think these files should be kept privately.\nAs for the sizes, 120MB is a little bit oversized for data files saving on internal memory. The phones in the same era of Nexus One usually has 512MB internal memory, so from the user point of view, they don't like oversized app to occupy their internal memory because insufficient internal memory sometimes will cause the Android OS to stop receiving SMS and stop synchronisation.\nAll in all, because of the root access in nearly all Android phone, it is not safe to directly save your app private data to either external or internal memory. As for your 120MB data size, I recommend you do a simple encryption and save to SD Card.\nHere's an excellent explanation on two storage types on saving files\nAnd here's the Saving Options from Android Developers for your reference.\n\nA: You must research on how to secure your data, cause your application data should be deployed/downloaded into the external storage sd card as an example.\nCause many modern smartphones relies on the internal storage in as ram memory to run the applications.\nThats why I think you shouldn't install you applicatino data in the internal storage.\nI learned this developing for windows ce, windows mobile similar OS devices. \nThanks,\n\nA: My suggestion is in internal memory.\nMost of the devices should have the same storage partition shared between internal storage and SD card. Either way, you consume the same storage space. From the users' perspactive, there is no different between SD Card and internal storage except that the data in SD card could be shared in some ways which is not what you want. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635865\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":1967694,"cells":{"text":{"kind":"string","value":"Q: How do you say not equal to in Ruby? This is a much simpler example of what I'm trying to do in my program but is a similar idea. In an, if statement how do I say not equal to?\nIs != correct?\ndef test\n vara = 1\n varb = 2\n if vara == 1 && varb != 3\n puts \"correct\"\n else\n puts \"false\"\n end\nend\n\n\nA: Yes. In Ruby the not equal to operator is:\n!= \nYou can get a full list of ruby operators here: \nhttps://www.tutorialspoint.com/ruby/ruby_operators.htm. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635867\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"64\"\n}"}}},{"rowIdx":1967695,"cells":{"text":{"kind":"string","value":"Q: JAX-RS and unknown query parameters I have a Java client that calls a RESTEasy (JAX-RS) Java server. It is possible that some of my users may have a newer version of the client than the server.\nThat client may call a resource on the server that contains query parameters that the server does not know about. Is it possible to detect this on the server side and return an error?\nI understand that if the client calls a URL that has not been implemented yet on the server, the client will get a 404 error, but what happens if the client passes in a query parameter that is not implemented (e.g.: ?sort_by=last_name)?\n\nA: \nIs it possible to detect this on the server side and return an error?\n\nYes, you can do it. I think the easiest way is to use @Context UriInfo. You can obtain all query parameters by calling getQueryParameters() method. So you know if there are any unknown parameters and you can return error.\n\nbut what happens if the client passes in a query parameter that is not implemented \n\nIf you implement no special support of handling \"unknown\" parameters, the resource will be called and the parameter will be silently ignored.\nPersonally I think that it's better to ignore the unknown parameters. If you just ignore them, it may help to make the API backward compatible.\n\nA: You should definitely check out the JAX-RS filters (org.apache.cxf.jaxrs.ext.RequestHandler) to intercept, validate, manipulate request, e.g. for security or validatng query parameters.\nIf you declared all your parameters using annotations you can parse the web.xml file for the resource class names (see possible regex below) and use the full qualified class names to access the declared annotations for methods (like javax.ws.rs.GET) and method parameters (like javax.ws.rs.QueryParam) to scan all available web service resources - this way you don't have to manually add all resource classes to your filter. \nStore this information in static variables so you just have to parse this stuff the first time you hit your filter.\nIn your filter you can access the org.apache.cxf.message.Message for the incoming request. The query string is easy to access - if you also want to validate form parameters and multipart names, you have to reas the message content and write it back to the message (this gets a bit nasty since you have to deal with multipart boundaries etc).\nTo 'index' the resources I just take the HTTP method and append the path (which is then used as key to access the declared parameters.\nYou can use the ServletContext to read the web.xml file. For extracting the resource classes this regex might be helpful\nString webxml = readInputStreamAsString(context.getResourceAsStream(\"WEB-INF/web.xml\"));\nPattern serviceClassesPattern = Pattern.compile(\"jaxrs.serviceClasses.*?(.*?)\", Pattern.DOTALL | Pattern.MULTILINE);\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635875\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"7\"\n}"}}},{"rowIdx":1967696,"cells":{"text":{"kind":"string","value":"Q: What are the performance implications of disabling the lock-screen? I am working on a timer application (it's my first app to try and learn the ropes). While the timer is running, I want to offer the user the ability to prevent the screen from locking.\nSince the screen is always displaying something (and refreshing the clock every second), what would the performance penalty be for doing this? The only things active on the screen are the timer (black background with just the running time) and \"split\" and \"stop\" buttons? I am mostly concerned with the battery life of the phone; e.g. if this were a long-running timer job (let's say long-distance running with split times).\n\nA: I have used both an iPhone and an android for running apps in the past. The first iPhone versions couldn't 'lock' the screen because it disabled the GPS too. Leaving the screen on, even with minimal backlight, absolutely ruins battery life, because the backlight and screen-refresh operations are quite expensive. Battery life went up from ~30 minutes to ~5 hours when running with the screen off.\nThere are some innovative solutions to this for runners, for example RunKeeper (and I'm sure most of the other ones too) has an option to fade the music out and give you updates on your stats every n minutes. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635877\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967697,"cells":{"text":{"kind":"string","value":"Q: ~/ not starting at app root I know this may be a basic question, but it is driving me crazy. I have an asp.net (4.0 framework) application that I have been working on. I have a masterpage in the root directory, and a secondary masterpage in a subdirectory. The secondary masterpage inherits the site master. \nThe issue is that even though I used ~/ to describe the location of the resource (\") they are not loading.\nUsing the console on firebug, I get this error: \"NetworkError: 404 Not Found - http://localhost:4601/Account/~/Images/myImage.jpg\" \nWhat do I need to do to correctly translate resources from masterpage to masterpage across subfolders? And what is it that I am misunderstanding about '~/'? \n\nA: Using \n\n\nIs mixing HTML code with .Net ASP code. The tilde (~) is not something of the HTML markup and this is why it does not produce what you want.\nTo make it works, you need to change the source with the <% %> tag that will let you add ASP code that will be translated into HTML code when processing.\n\" />\n\nInside ASP.NET tag, you should use the ResolveURL that will transform the URL into something that the HTML will be able to understand.\nIf you do not want to use this trick, you can also use instead of the HTML img tag the ASP.NET image control. This will automatically execute the ResolveUrl\n\n\n\nA: \" />\n\nor\n\" />\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/7635880\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":1967698,"cells":{"text":{"kind":"string","value":"Q: How to create an independent HTML block? I want to know if there is some way to create an independent HTML block . \nFor more explanation : \nMy problem is that I have a webpage in which I allow some users can add content (may contain HTML & CSS ) \nI allow them to add their content inside a certain block , but sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV \nThis sometimes distort my page completely \nIs there any way to make their content displayed independently from my parent div , so that my div is first displayed well , and then the content inside it is displayed ?\nI'm sorry for long message .\nThanks for any trial to help\n\nA: \nsometimes their content may not be clean code , and may contain some\n DIVS with no end , Or even some DIV end with no starting DIV This\n sometimes distort my page completely\n\nThe easiest solution for you is going to be to add the submitted content to your page inside an