{ // 获取包含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 }); }); } })(); \r\n\n\nA:\n\nBBC News Site/title>\n\nfix it into :\n<title>BBC News Site\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29291,"cells":{"text":{"kind":"string","value":"Q:\n\nTooltip over DataGrid row in C# .Net 4.0\n\nI want to add tooltip for every row (and for every cell) in DataGrid. How can I do this? I've tried RowDataBound and CellFormating, but it seems that I can't use this examples in my code (no similar events)\nDo you have any ideas how to handle it?\n\nA:\n\nHere Is an Example From MSDN, In which they Clearly described how to Gets or sets the ToolTip text associated with this cell. with the help of _CellFormatting event of the control; Consider the code below:\nvoid dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n if ((e.ColumnIndex == this.dataGridView1.Columns[\"column_name\"].Index) && e.Value != null)\n {\n DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];\n cell.ToolTipText = \"This is given ToolTip\";\n }\n}\n\nYou can try Conditional Tooltips Too like this(this too explained in the associated link):\nif (e.Value.Equals(\"some value\"))\n{\n cell.ToolTipText = \"ToolTip 1\";\n}\nelse if (e.Value.Equals(\"some other value\"))\n{\n cell.ToolTipText = \"ToolTip 2\";\n}\n// Like wise\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29292,"cells":{"text":{"kind":"string","value":"Q:\n\nNeed to delete all data after third colon of a string\n\ni have a file say test.txt with the following contents\napple:orange:mango:123:1234:12345\n\ni want all data after third colon to be removed \nExpected output\napple:orange:mango:\n\nKinldy help\n\nA:\n\nUsing backreference:\nsed 's/\\([^:]*:[^:]*:[^:]*:\\).*/\\1/' test.txt\n\nor with GNU sed:\nsed -E 's/(([^:]*:){3}).*/\\1/' test.txt\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29293,"cells":{"text":{"kind":"string","value":"Q:\n\nembed the string in view flipper ontouch\n\nI am creating an application in which i have used four custom view.I have embed that in the viewflipper now i want to add ontouch event to viewflipper.i have added the ontouchevent but i want that when user touch on the particular position then it will show some text on the canvas which is used by viewflipper.\n \nI have uploaded the image also can any one help me on this topic .\n\nA:\n\nI have mention in my question that i am using view.so i have used the invalidate method .\nViewflipper .invalidate (); \n\ninvalidate method force to redraw the view if you want more knowledge then refer this link \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29294,"cells":{"text":{"kind":"string","value":"Q:\n\nMurmurHash3_32 Java returns negative numbers\n\nI am trying to replicate the file hashing of MobileSheetsPro, an Android app, where there is a hashcodes.txt which includes a hash for each file, as well as the path, last modified date and filesize. We'll just focus on the hashing part.\nSo for the random song I uploaded here if you want to try it for yourself, I am using the murmurhash-native npm package to convert it to a buffer and then hash it like so:\nconst fs = require(\"fs\");\nconst { promisify } = require(\"util\");\nconst { murmurHash } = require(\"murmurhash-native\");\nconst readFileAsync = promisify(fs.readFile);\n\nasync function hashcodeObjFromFilePath(filepath) {\n const buf = await readFileAsync(filepath);\n const h = murmurHash(buf);\n console.log(h);\n}\n\nThis prints out a hash of 4275668817 when using the default seed of 0 and 3020822739 when using the seed 0xc58f1a7b as a second argument.\nThe problem: the app seems to calculate it differently. The developer wrote the following, but I don't see that exact function in the code he linked:\n\nCheck this out: github link\nThose are the classes I've utilized. I call\n Hashing.goodFast32Hash(HASH_KEY)) where HASH_KEY is equal to\n 0xC58F1A7B.\n\nEDIT I've got more infos from the dev:\n\nI call Files.hash(file, Hashing.goodFast32Hash(HASH_KEY)); Using the\n return value from that, I call \"asInt()\" on the HashCode object that\n is returned. So it's a signed integer value (negative values are just\n fine). And yes, HASH_KEY is the seed value passed to the function.\n\nSince I'm not good at Java I still have no idea to replicate this in node-js...\nThat's all the info I have, folks.\nAnyone see where I'm going wrong?\n\nA:\n\nFound it! The asInt() function in the Java lib returns a signed int32 *in little endian byte order\nThe following is probably not the easiest way but the code\nconst h = murmurHash(buf, \"buffer\", 0xc58f1a7b);\n// console.log(parseInt(h, 16).toString(2));\nconst fromHashFile = Buffer.alloc(4);\nfromHashFile.writeInt32BE(-1274144557);\nconsole.log(fromHashFile);\nconsole.log(h);\nconsole.log(h.readInt32BE());\nconsole.log(\"hash from hashcodes file: -1274144557\");\n\nPrints out the following to console:\n\n\n-1274144557\nhash from hashcodes file: -1274144557\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29295,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to smooth a scanned image using Gimp\n\nI have drawn an image which I then scanned into the computer and saved as a png. \nI just want to make the lines smooth on the image. The image is a logo \nAny help is much appreciated. I am using GIMP 2.8\n\nA:\n\nIn order to make lines smooth, you have to vectorize the bitmap in applications like Inkscape:\nYou can import the image and trace it:\n\nAfter the tracing operation the image is vectorized and you can work on the nodes. For example you can simplify the path, which is an automatic operation:\n\nIn this example the left image is the traced one and the right image is obtained simplifying the path (less nodes and more smooth). Obviously after this operation you can work on single nodes in order to adjust the details (in the example the eye of the lion needs a little work).\nIn GIMP you can blur the image in order to soften the edges, but I suggest you to vectorize the image.\n\nA:\n\nIf instead of going to a vectors app, you want to deal with pixes, inside GIMP, you can try these simple two steps, selct:filters->blur-> gaussian blue - try using a radius of 2-4, and then use colors->curves and pull the curve in an \"S\" shape to sharpen the borders back. The jaggies will smooth out, and you can fine tune how smooth you ant it with the curves.\nThe default curves settings will work for black over white or vice-versa - selet the appropriate channels to affect your drawing.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29296,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat are gradle task definitions in groovy language?\n\nI'm completely new to both gradle and groovy and I'm having trouble to find information about what the below actually is in the groovy language\ntask myTask(dependsOn: 'compile') << {\n println 'I am not affected'\n}\n\nAFAIK the {...} part is a closure which seems to be passed to whatever is defined before <<.\nIs task myTask() a call to a constructor? \nAnd what is the thing with the colon that looks like a parameter? \nWhat does << do? Is it an operator that was overloaded by gradle or is it standard groovy?\n\nA:\n\ndependsOn: 'compile' is a named argument. << is an overloaded operator that adds a task action to the task. (See Gradle User Guide for more information.) { ... } is a closure that implements the task action. myTask is syntactically a nested method call (task(myTask(dependsOn: 'compile') << ...)), but gets rewritten to a String using a Groovy compiler plugin (task('myTask', dependsOn: 'compile') << ...).\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29297,"cells":{"text":{"kind":"string","value":"Q:\n\nTranslating status codes to messages in log files\n\nI'm not overly efficient when it comes to coding, and I am looking for ways to improve the speed of a log translator I built.\nSeveral files are uploaded to a folder on a server and log files are selected for processing. Speed here is fine. Each log file has 5000-10000 lines possible a bit higher. They are space delimited files that look like this:\n20:04:13 + MA 00 61\n20:04:17 - MA 00 61\n20:04:18 + MA 00 61 optionaltxt\n20:04:20 - MA 00 61\n\nThere are at least 5 fields for every entry but more can be added if optional text exists. Field 5 is a status code, and it has to be cross referenced with a language file then replaced with the corresponding message so the result is like this:\n17:29:48 - MA 00 (061) Feed hold! X / Y axis is locked \n17:29:48 + MA 00 (061) Feed hold! X / Y axis is locked \n17:29:50 - MA 00 (061) Feed hold! X / Y axis is locked optionaltxt\n17:29:51 + MA 00 (061) Feed hold! X / Y axis is locked \n\nThe translated logs are saved to a new folder for download later. At the moment translation takes about 7-10 seconds per log file. The problem is that it is common to have 90 files or more and the time starts adding up. I have no control over the log format or language file format.\nThis part of my code looks like this:\n$shLANG = file_get_contents(\"ErrCODES/data_en.properties\");\n$SHarray = explode(\"\\n\", $shLANG);\n\n$logARRAY = glob($uploadDIR.$filepath.\"/original/*.[lL][oO][gG]\");\nforeach ($logARRAY as $logFILEarray) {\n\n$name = basename($logFILEarray);\n$logFILE = file_get_contents($uploadDIR.$filepath.\"/original/\".$name);\n$logFILEarray = explode(\"\\n\", $logFILE);\nforeach ($logFILEarray as $key => $line) {\n $newline=\"\";\n $LINEarray = explode(\" \", $line);\n\n if(isset($LINEarray[0])){$newline .= $LINEarray[0].\" \";}\n if(isset($LINEarray[1])){$newline .= $LINEarray[1].\" \";}\n if(isset($LINEarray[2])){$newline .= $LINEarray[2].\" \";}\n if(isset($LINEarray[3])){$newline .= $LINEarray[3].\" \";} \n if(isset($LINEarray[4])){\n foreach ($SHarray as $code) {\n if (strlen($LINEarray[4])>0){\n if (substr($code, 0, strpos($code, '=')) == $LINEarray[4]) {\n $newline .= trim(explode('null;', $code)[1]). \" \";\n }\n }\n } \n }\n\n if(isset($LINEarray[5])){$newline .= $LINEarray[5].\" \";}\n if(isset($LINEarray[6])){$newline .= $LINEarray[6].\" \";}\n if(isset($LINEarray[7])){$newline .= $LINEarray[7].\" \";}\n if(isset($LINEarray[8])){$newline .= $LINEarray[8].\" \";}\n $newline .= \"\\r\";\n $logFILEarray[$key] = $newline;\n }\n\n//var_dump($logFILEarray);\n$info = implode(\"\\n\",$logFILEarray);\nfile_put_contents($uploadDIR.$filepath.\"/translation/\".$name, $info);\n\n}//for all glob .log\n\nThe code works fine, but how can I improve the speed (greatly)?\n\nA:\n\nWhat you have looks problematic in a few ways.\n\nYou have a poor data structure for your localization strings. You have these in an array the must be iterated every single time you are doing a lookup against it. This is an linear complexity (O(n)) operation that when executed inside your loop (another O(n) iteration) give you O(n^2) overall performance. @TimSparrow has touched on a good alternative - to load the localization strings into an associative array the will allow O(1) lookup when being used - but perhaps didn't explain how critical this is to your performance. By building such a data structure up front, you whole algorithm goes to O(m) (to build localization data structure) + O(n) (from your log file loop) instead of O(m * n). To illustrate the impact to your performance, let assume you have a 10K line log file and a 100 line localization file. With your current code, this means you could have up to 1 Million lookup operations you have to perform vs. 10,100 if using a proper data structure.\nThis code is a memory hog. You store every file you are working with wholly in memory, as well as storing the same data in duplicate in the result arrays you are building, not to mention all the temporary array/string conversion you have that, again mean you are going to be holding that information in duplicate in memory. If you can get the memory utilization more optimized here, then you may be more able to do things like for each of the individual log into their own process to parallelize the work.\nYou should consider working with the rows in a more structured manner vs. working with them primarily as strings. fgetcsv(), fputcsv() or similar give you better ways to parse through and write your files.\n\nIncorporating the above thoughts should allow you to greatly streamline both the performance of your script as well as just simplify how it works. You might end up with something like:\n$localizations = [];\n$handle = fopen('ErrCODES/data_en.properties','r');\n// read lines from file one at a time.\nwhile ($line = fgetcsv($handle, 0, ' ')) {\n // this part may vary based on your format\n $localizations[$line[0]] = $line[1];\n}\nfclose($handle);\n\n$logFiles = glob($uploadDIR.$filepath.\"/original/*.[lL][oO][gG]\");\n// here is where at some point you may want to fork processes to paralellize\n// now it is serial foreach loop\nforeach ($logFiles as $logFile) {\n $translatedFile = str_replace('/original', '/translation/', $logFile); \n $logHandle = fopen($logFile,'r');\n $translateHandle = fopen($translatedFile, 'w+');\n while($line = fgetcsv($logHandle, 0, ' ') {\n // apply localization\n if(!empty($line[4]) && isset($localization[$line[4]])) {\n $line[4] = $localization[$line[4]];\n }\n fputcsv($translateHandle, $line, ' ');\n }\n fclose($translateHandle);\n fclose($logHandle);\n}\n\nA few final thoughts on style:\n - Your style is a little bit all over the place, which makes your code a littel hard to read.\n - Particularly variable naming is odd. PHP tends to use a mix of camelCase and snake_case in most code bases you will find (internal PHP functions mix both unfortunately). Your approach to variable syntax is very haphazard, sometimes oddly putting portions of variable names in upper case with apparent cohesive approach, sometimes first letter is uppercase, sometimes it is lower case, etc.\n - Your indentations are inconsistent.\n - You could be well-served by better use of spacing around flow control operators. A line of code like if(isset($LINEarray[0])){$newline .= $LINEarray[0].\" \";} is extremely hard to read.\n - Consider familiarizing yourself with the PHP-FIG PHP standards, particularly PSR-1 and PSR-2 which deal with aspects of coding style. These are pretty much the de-facto industry standards.\n\nA:\n\nFirst thing, I would prepare the errorCodes array:\nAfter\n$SHarray = explode(\"\\n\", $shLANG);\n\nAdd:\n$errors = []; \nforeach($SHArray as $line) {\n list($code, $message) = explode('=', $line);\n $errors[$code] = $message\n}\n\nNote: it is not clear from your code what additional processing is needed to get an associative array of $code => $message, you will need to add that yourself.\nSo instead of repeated substring search:\nforeach ($SHarray as $code) {\n if (strlen($LINEarray[4])>0){\n if (substr($code, 0, strpos($code, '=')) == $LINEarray[4]) {\n $newline .= trim(explode('null;', $code)[1]). \" \";\n }\n }\n} \n\nyou will have\nforeach($errors as $code => $message) {\n if($code == $LINEarray[4]) { \n $newline .= $message . \" \";\n }\n}\n\nAnother thing: instead of linear processing of each log field, I would update $lineArray[4], then re-assemble the array using implode, without processing other fields at all, if they do not need to be changed. Note that it may not increase productivity, but will improve code readability and size.\nLike this:\n$lineArray = explode(' ', $line);\n// use a separate function/method to translate one entry\n$lineArray[4] = translateErrorMessage($lineArray[4], $errors); \n$newLine = implode(' ', $lineArray);\n\nFinally, With speed and productivity, you need to consider not only your code, but other system factors as well. \n\nWhich version of php are you using? PHP 7 may give a speed benefit over older 5.xx\nAre you using standalone php (CLI) or run as a web server? On large files, web server may fail with a timeout, also it is no good to run such tasks with full stack, as it consumes way too much memory.\nIs it possible to install some PHP pre-compiler with your system? These usually save time, as pre-compiled code works much faster.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29298,"cells":{"text":{"kind":"string","value":"Q:\n\nYAWS Websocket Trouble\n\nI'm trying to get the YAWS websocket example from here running on my local. It's a basic ws-based echo server.\nI have \n\nYAWS set up and running on localhost:8080 (direct from the Debian repos; no conf changes except pointing it to a new root directory)\nthe code listing from the bottom of this page wrapped in tags saved as websockets_example_endpoint.yaws \nthis page saved as index.yaws (I literally copy/pasted the view-source for it, saved it as that file and pointed the socket request at localhost:8080 rather than yaws.hyber.org).\n\nWhen I visit localhost:8080/websockets_example_endpoint.yaws in-browser, it displays the text \"You're not a web sockets client! Go away!\", as expected. When I visit localhost:8080, it points me to the javascript enabled form, but the \"Connect\" button does nothing when clicked. If I leave index.yaws pointed at yaws.hyber.org instead of localhost:8080, the echo server connects and works exactly as expected.\nCan anyone give me a hint as to what I'm doing wrong (or alternatively, point me to source for a working example)?\n\nA:\n\nThere is a gitbub project, I've created:\nhttps://github.com/f3r3nc/yaws-web-chat/\nThis is also an example for embedding yaws and extended with group chat.\nNote, that the standard of WebSocket is under development thus yaws and the browser should support the same WS version in order to work correctly.\nyaws 1.91 works with Safari Version 5.1.1 (6534.51.22) but does not with Chrome (15.0.874.102) and probably not with (14.x). \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29299,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat is the connection between ULN2004 and ULN2804 drivers?\n\nI have an unipolar stepper motor that im driving with an Arduino. As a driver for the motor i bought a ULN2004 driver chip from Ebay. Or so i thought. I might be missing something, but the chip i received has 9 pins on each side, not 8 as my sketch illustrates, and the number on it is ULN2804, not ULN2004.\n\nThe link to the data sheet on the ULN2004 listing i bought from spinatronics says it's a ULN2804 chip. I'm unexperienced in how manufacturers set the numbers on the chips. \nHave i bought the wrong chip, or can a ULN2804 driver be used the same way as a ULN2004? \nHow do i then change my sketch to implement the last two additional pins of the chip?\n\nA:\n\nHere's the pdf for the ULN2004 chip\nIt looks like the same application and same specs, set of darlington arrays. ULN2004 has 7 circuits as oppose to ULN2804 which has 8. Both carry 6-15V (CMOS, PMOS compatible inputs), Output currents of 500 mA per driver, and Output Voltage of 50V\nIt might've been a careless mistake derived from laziness since the chips have the same type of circuitries.\nBecause these chips are practically the same, you can utilize 2804 the same way as 2004. Only in this circuit, you'd have in8, out8 pins setup the same as in7 and out7\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":292,"numItemsPerPage":100,"numTotalItems":29950,"offset":29200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzkzOTIzNiwic3ViIjoiL2RhdGFzZXRzL3N1b2x5ZXIvcGlsZV9zdGFja2V4Y2hhbmdlIiwiZXhwIjoxNzU3OTQyODM2LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.WM9DMsGX_JAr-YjexIl9dgSBxf71oznhA9K-5nZOhnZb4McCRr8OPrsCuMUzvwW8fN-KT3bFy4z0RclMDr8tAA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
175
47.7k
meta
dict
Q: Does suspending an account allows access to CPanel? I have a CPanel reseller account, and I want to suspend a site because it was hacked, but I want to know if will be available to site owner to restore it. A: When suspending a cPanel account, it will fully lock down the account... it prevents login into cPanel, SQL, Mail and all other services, crons and processes. The account can then only be restored via the Reseller administrator. CKB What happens when you suspend an account? The system uses the passwd -l command to lock the account's /etc/shadow password file. This command prepends the account's passwords with two exclamation marks (!!). The following list includes some of the effects that this action causes: - The user cannot log in to their cPanel account. - The account's database users cannot log in to their databases. - The suspended account's password cannot change.
{ "pile_set_name": "StackExchange" }
Q: execCommand - wrap content including tags in blockquote tags I am trying to wrap some selected elements in <blockquote> tags but the method I thought might work replaces the existing tags rather than wrapping them. Here's my code. $("input[value='Quote']").on("click", function() { document.execCommand('formatBlock', false, '<blockquote>'); }); and... <div contentEditable> <p>para 1</p> <p>para 2</p> </div> <input type="button" value="Quote" /> I want to end up with something like this... <div contentEditable> <blockquote> <p>para 1</p> <p>para 2</p> </blockquote> </div> rather than the following which is what I currently get... <div contentEditable> <blockquote> para 1 <br /> para 2 </blockquote> </div> Thanks A: This should do it $("input[value='Quote']").on("click", function() { $("<blockquote/>").insertBefore($("[contenteditable]").find("p:first")).append($("[contenteditable]").find("p")) });
{ "pile_set_name": "StackExchange" }
Q: (custom) UITableViewCell's mixing up after scrolling Ive been on this problem for a few weeks now. Basically when i scroll up/down within a TableView thar uses a Custom Cell designed in IB all the content gets mixed up and misplaced Ive tried multiple solutions but to no avail, your gonna have to excuse my code a little bit. People keep suggesting to make a subView for the table cell but i have no idea how to do that =/ still quite new to iOS development so if you have a possible answer, can you detail it as much as possible please. Once again, sorry for my code =/ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier]; NSInteger intCellTag; NSDictionary *dictionary = [[[self.tableDataSource objectAtIndex: indexPath.section] objectForKey: @"Rows"] objectAtIndex: indexPath.row]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; [[[NSBundle mainBundle] loadNibNamed:@"EventsCustomTVCell" owner:self options:nil] lastObject]; cell = tvCell; self.tvCell = nil; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.tag = intCellTag; intCellTag++; UIImage *customCellBG = [UIImage imageNamed:@"EventsCustomTableCellBG.png"]; UIImageView *customCellBGImageView = [[UIImageView alloc] initWithImage: customCellBG]; customCellBGImageView.contentMode = UIViewContentModeScaleToFill; cell.backgroundView = customCellBGImageView; [customCellBGImageView release]; [cell.contentView addSubview:imgThumbnail]; [cell.contentView addSubview:lblName]; [cell.contentView addSubview:lblDescription]; [cell.contentView addSubview:lblDate]; } imgThumbnail.image = [UIImage imageNamed:[dictionary objectForKey: @"Thumbnail"]]; lblName.text = [dictionary objectForKey:@"Title"]; lblDescription.text = [dictionary objectForKey:@"Description"]; lblDate.text = [dictionary objectForKey:@"Date"]; return cell; } A: It looks like you're trying to mix metaphors in defining each UITableViewCell -- loading from .xib, and creating subviews manually. Nothing wrong with this of course, but you could put the image and labels into the tableviewCell directly, like this: and here's the code to display each row (naturally in IB you've assigned non-zero unique tags to each UIKit object you want to customize on a per-row basis) #define kImageTag 1 #define kLabel1Tag 2 #define kLabel2Tag 3 #define kLabel3Tag 4 // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MyTvCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { self.tvCell = nil; [[NSBundle mainBundle] loadNibNamed:@"TvCell" owner:self options:nil]; cell = self.tvCell; } UIImageView *iv = (UIImageView *) [cell viewWithTag:kImageTag]; UILabel *lbl1 = (UILabel *) [cell viewWithTag:kLabel1Tag]; UILabel *lbl2 = (UILabel *) [cell viewWithTag:kLabel2Tag]; UILabel *lbl3 = (UILabel *) [cell viewWithTag:kLabel3Tag]; iv.image = [UIImage imageNamed:@"myimage.png"]; lbl1.text = @"howdy"; lbl2.text = @"there"; lbl3.text = @"foo"; return cell; }
{ "pile_set_name": "StackExchange" }
Q: index masked element Array I have a array z = np.random.random((10,10)) --> two dimensions with a mask y,x=np.mgrid[slice(0,61, 1),slice(0,106, 1)] sorted = np.sort(z,axis=None) mask = ma.masked_inside(z,sorted[10],sorted[-10]) mask is Array masked inside only the 10 min element and 10 max inside with a mask TRUE. I need the index position to put x,y in the annotate, but only like create element that is masked I will like return mask elements masked and the index position in the axis of all the elements to create a automatic annotates objects ax.annotate(str(j)+" Altura",xy=(i,j)) A: To return the "index position", use np.where on the mask. For example: import numpy as np A = np.array([[2,7,9],[9,1,4],[8,7,2]]) idx = A<3 # The mask print np.where(idx) print zip(*np.where(idx)) Gives: (array([0, 1, 2]), array([0, 1, 2])) [(0, 0), (1, 1), (2, 2)] that is, the locations where A<3. I find zipping over the elements and packaging them as a list of tuples useful, but use the first representation to index them back from the original array.
{ "pile_set_name": "StackExchange" }
Q: Webservice retornando erro Meu webservice está retornando um erro que eu ainda não consegui resolver. Segue o código: `<?php $dns = ‘mysql:host=localhost;dbname=diagnosys_db’; $user = ‘user_name’; $password = ‘user_password’; try{ $db = new PDO ($dns, $user, $pass); } catch( PDOException $e){ $error = $e->getMessage(); echo $error; } ?>` O erro retornado é o seguinte: Parse error: syntax error, unexpected ':' in /storage/ssd4/128/11623128/public_html/db.php on line 2 A: Vamos lá Você declarou uma variável chamada $password, mas quando está instanciando o PDO está utilizando uma variável chamada $pass, substitua $pass por $password Ajuste também as aspas, segue abaixo o código com os devidos ajustes. <?php $dns = 'mysql:host=localhost;dbname=banco-nome'; $user = 'usuario-do-banco'; $password = 'senha'; try{ $db = new PDO ($dns, $user, $password); } catch( PDOException $e){ $error = $e->getMessage(); echo $error; } ?>
{ "pile_set_name": "StackExchange" }
Q: Timeline title is displaying partially in Area 51 In the Area 51, if the question title is very lengthy, when viewing from the timeline, some part of the title text is not displaying. Screenshot for reference: A: In the recent responsive design, the timeline title alignment issue for the lengthy title has been fixed. Screenshot for reference:
{ "pile_set_name": "StackExchange" }
Q: java txt file is over writing when use file and formatter So i have tried every thing but the files keeps over writing the first line, i am passing these methods to another class so the three arguments in method add_records are passed through a scanner. here is the creating/opening method : public class Io_Files{ private Formatter output; public void open_file_normal(String filename) throws IOException { { try { FileWriter fileWriter = new FileWriter(filename, true); output = new Formatter(filename); } catch(FileNotFoundException fileNotFoundException) { System.err.println("Error"); } } } and here is the code for adding record method: public void add_records(String a, String b, int c) throws FileNotFoundException{ output.format ("[%s, %s, %d]%n", a, b, c); } please if you are able to help provide some comments on why and where to put the code so i can learn too. cheers A: Try using output = new Formatter(fileWriter); instead of output = new Formatter(filename);
{ "pile_set_name": "StackExchange" }
Q: Regex two special characters in a row I have this regex \[.+\]\(.+\) Why does it match this string entirely? [test1](test1) thisbitshouldnotmatch [test2](test2) It should only match [test1](test1) and [test2](test2). thisbitshouldnotmatch should not match. A: That is because the + operator is greedy. For expression \[.+\]\(.+\) the characters are matched as follows: [test1](test1) thisbitshouldnotmatch [test2](test2) [..........................................](.....) so, whole input matches! You'd need to either use nongreedy: \[.+?\]\(.+?\) Or, explicitery disallow some characters \[[^\]]+\]\([^)]+\) (notice how I replaced the catch-any . with a character group that excludes ] or ) respectively)` A: Try with this expression: \[.+?\]\(.+?\) That will limit the result so it only matches the first occurrence of [] and of (). Notice that by default an expression such as this: .+ will try to match as much of the input as possible. By adding a ? quantifier at the end: .+? we're specifying that the search should stop at the first match it finds. A: You need to make the dot lazy otherwise it will grab everything it can: \[.+?]\(.+?\) Or, even better, use a negated character class, so a [ followed by many not ] followed by a ] \[[^]]++]\([^)]++\) Also note that you don't need to escape ]
{ "pile_set_name": "StackExchange" }
Q: Has Skye become Kree? Last show of Agents of Shield we get to know that Skye's mother had the anti-aging thingy that Hydra head honcho somehow stole from her. Skye has touched the object and survived where everybody else died. Does one simply become alien ( blue one, Kree ) or is she going to turn into a superhero or is there anything in universe that can explain this? A: It has been revealed that Skye is in fact Daisy Johnson, a super hero who adopts the Moniker "Quake"... The crystals within the Diviner are Terrigen Crystals, which activate the latent abilities of 'Inhumans', who were a race genetically engineered by the Kree (but later abandoned) to Infiltrate earth. Each inhuman has a different, unique ability.. in the MCU, Quake is revealed to be an Inhuman and this is how she obtained her abilities (demonstrated at the end of the episode). Just like X-Men's mutants, abilities do not neccesarily change ones appearance... so it's likely Skye will remain as she is.
{ "pile_set_name": "StackExchange" }
Q: Should I move columns on a wide mysql table to the left if they are used often? I have a mysql user table that is around 35 columns wide, I notice that the things I query for most often, picture_url, username, onlinestatus are located on the far right side of the table. Would it be better performance to have the most used items be at the very beginning of the table? A: The column position makes no difference at all to performance in any MySQL storage engine. When you read any column from a row, you have already incurred the most expensive part, which is the I/O of seeking and reading that row from the data file on disk. If you want to improve performance of frequently-used columns, uses indexes. Also learn about covering indexes which allow queries to read a column's value from the index without having to also read the rest of the row from the table storage. But this also has nothing to do with the ordinal position of the column. One more tip about columns and performance: if your query only needs a subset of the columns, don't use SELECT *. Transferring all the columns over the network to your application does have a cost, and if you don't need all the columns, don't fetch them.
{ "pile_set_name": "StackExchange" }
Q: Android TextInputLayout Password toggle not visible in new support library I have compiled with following design library and it is displaying password HIDE/SHOW button at the right of EditText compile 'com.android.support:design:24.2.1' <android.support.design.widget.TextInputLayout android:id="@+id/login_password_text_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/spacing_normal"> <android.support.v7.widget.AppCompatEditText android:id="@+id/login_password_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawablePadding="@dimen/spacing_micro" android:hint="@string/prompt_password" android:imeActionId="@+id/login" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:text="password" /> </android.support.design.widget.TextInputLayout> like: after updating to compile 'com.android.support:design:25.0.1' Its not visible, Why? Is there any bug? Please guide. A: The TextInputLayout password toggle is now disabled by default to avoid unnecessarily overwriting developer-specified end drawables. It may be manually enabled via the passwordToggleEnabled XML attribute. from https://developer.android.com/topic/libraries/support-library/revisions.html A: I smashed my head with this one for hours. From the release notes: https://developer.android.com/topic/libraries/support-library/revisions.html# Fixed issues: The TextInputLayout password toggle is now disabled by default to avoid unnecessarily overwriting developer-specified end drawables. It may be manually enabled via the passwordToggleEnabled XML attribute. So to have it back, you have to: <android.support.design.widget.TextInputLayout ... ... app:passwordToggleEnabled="true"> <android.support.design.widget.TextInputEditText .... .... .... /> </android.support.design.widget.TextInputLayout>
{ "pile_set_name": "StackExchange" }
Q: Analytic properties of Eisenstein series Let $\Gamma$ be a discrete subgroup of $SL_2(\mathbb{R})$ which has a cusp at $\infty.$ suppose that $\mu(\Gamma\setminus\mathbb{H})<\infty,$ consider the Eisenstein series :$$E(z,s,\Gamma)=\sum_{\gamma\in\Gamma_\infty\setminus\Gamma}\dfrac{y^s}{|cz+d|^{2s}}$$ what is the analytic properties of $E(z,s,\Gamma)$ ? A: The main properties of these Eisenstein series (meromorphic continuation, functional equation, poles and residues) are discussed and derived in Chapter 6 of Iwaniec: Spectral methods of automorphic forms (2nd edition, AMS, 2002). For their role in the spectral decomposition of $L^2(\Gamma\backslash\mathbb{H})$ see Chapter 7 of the same book. Further analytic properties in the arithmetic case (e.g. results about their value distribution) can be found in recent papers and theses (e.g. Luo-Sarnak, Spinu, Young, Huang-Xu).
{ "pile_set_name": "StackExchange" }
Q: Python/Pandas - Converting columns with float values and Nones to int values and Nones I have a column with values in floats and I want to turn them into ints. pdsm: federation_unit_id city_id id 3 8.0 3.0 7 None None 17 8.0 3.0 18 8.0 3.0 19 8.0 9.0 Their types are of values in the columns are: class 'float', except by None that is a NoneType. If I try this: pdsm['federation_unit_id']=pdsm['federation_unit_id'].astype(int) pdsm['city_id'].iloc[0]=pdsm.city_id.astype(int) I get this: TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' If I try this: pdsm['federation_unit_id']=pdsm['federation_unit_id'].apply(lambda x: x.astype(int) if x is not None else None) pdsm['city_id'].iloc[0]=pdsm.city_id.apply(lambda x: x.astype(int) if x is not None else None) I get: AttributeError: 'float' object has no attribute 'astype' Can anyone help? I'm going nuts here. A: I think in pandas you can't have int and None or nan in the same column. Its' not supported yet. If you are ok with converting None to 0, you can do: df.fillna(0).astype(int) Out[157]: federation_unit_id city_id id 3 8 3 7 0 0 17 8 3 18 8 3 19 8 9
{ "pile_set_name": "StackExchange" }
Q: How to resolve type ambiguity in this unit test I can't figure out how to annotate the mylast3 test properly: import Test.HUnit mylast :: [a] -> Maybe a mylast [] = Nothing mylast [x] = Just x mylast (_:xs) = mylast xs testsMyLast = [TestCase $ assertEqual "mylast1" (Just 1) $ mylast [1], TestCase $ assertEqual "mylast2" (Just 'b') $ mylast "ab", TestCase $ assertEqual "mylast3" Nothing $ mylast [] <== how to test this correctly? ] main = do runTestTT $ TestList testsMyLast I'm getting the following error pointing at the line "TestCase $ assertEqual "mylast3": No instance for (Show a0) arising from a use of assertEqual The type variable a0 is ambiguous A: Since the list [] does not have any members, it can only be deduced from type inference that [] is of type [a]. For a list to be "showable" it must be an instance of the typeclass Show. A list is only an instance of Show if the members of the list are also instances of Show. But the type checker can't deduce the type of [] to a more specific type than [a]. We cannot know if a is an instance of Show so we also cannot know if [a] is in turn an instance of Show. If we simply annotate a specific type ([] :: [Int]) there will be no error! This is because we know that Int is an instance of Show and therefore [Int] is also an instance of Show. Now the compiler can infer the necessary information to print the list!
{ "pile_set_name": "StackExchange" }
Q: Bake and then Broil instead of flipping? If I wanted to cook a meal - ie chicken wings - in a baking tray evenly on both sides, instead of turning them halfway through the cooking process, could I just switch from bake to broil midway so that both sides cook evenly? This is using a conventional oven with a heating ring on the top and bottom. A: The reason for turning the food when baking is so the side that is in contact with the pan can get hit by the hot air. In the case of turning on the bake and then turning on the broil, you would still have the medium of what ever your food is sitting in. If you are willing to elevated your food above a drip pan, turn on just the bottom heating coil (if possible), and set the food directly on the rack you could eliminate the need of turning halfway through the process.
{ "pile_set_name": "StackExchange" }
Q: Heroku undefined method error in ActionView Heroku logs shows the following error: ActionView::Template::Error (undefined method `accepted_answer_id' for #<Question:0x000000052fd1e0>) As background, I have a model Question, which has_many Answers. Question also has a column accepted_answer_id. The undefined method error is referring a line in _question.html.erb, where its used to customized the display of the answer count in a different shaded background <% if question.answers.count > 0 %> <% if question.accepted_answer_id %> <div class="pickedanswer"> <h4><%= question.answers.count %></h4> </div> <% else %> <div class="numanswer"> <h4><%= question.answers.count %></h4> </div> <% end %> <% else %> <div class="noanswer"> <h4><%= question.answers.count%></h4> </div> <% end %> I think the error may be raised due to the fact that initially question.accepted_answer_id is nil.. but given the way I structured the logic I do not know why it couldn't simply follow along (as it has done successfully in development). Thanks for your help. A: Your schema is missing that attribute. If your code works locally, then either you added that column manually, or a migration is not in your version control. You can see what migrations have run like so: $ heroku run rake db:migrate:status --app app_name This will show if any of your migrations haven't been ran. You should match those to your local migrations. Are you maybe missing one? Running db:push will destroy your remote database and replace it with a local copy, at best. Generally you should use pgbackups:restore to do this kind of thing (https://devcenter.heroku.com/articles/heroku-postgres-import-export)
{ "pile_set_name": "StackExchange" }
Q: Hanging indent with makecell I'm using \usepackage{makecell} to break up some long text inside my tables. I would like to have a hanging indent for that cell. I see some documentation about customizing such aspects, but modifying it to fit this need is beyond me. Thanks for any help. \begin{table}[] \centering \caption{My caption} \label{my-label} \begin{tabular}{lc} \multicolumn{1}{c}{\textbf{Header}} & \multicolumn{1}{r}{\textbf{Header}} \\ \makecell[l]{Some really long text\\ which I would like\\ to break up\\ with a hanging indent} & Short Text \end{tabular} \end{table} Edit: In the makecell documentation here (starting on page 9) you'll see various alignment options, including indenting the first line http://ctan.mirrors.hoobly.com/macros/latex/contrib/makecell/makecell.pdf . However, I would like a hanging indent, as below. I know I can add a forced spacing to each line, but is there a more compact way? A: If I understand well what you mean by a hanging indent, I don't think it can be done within makecell, which is done for standard r, l or c cells. However, you can easily obtain it with a p{some length} cell. I took the opportunity to simplify the code for column heads, with the \thead command, and to have a better spacing between caption and table, with the caption package: \documentclass{article} \usepackage{array, tabularx, caption, makecell} \renewcommand\theadfont{\normalsize\bfseries} \usepackage{amsmath} \begin{document} \begin{table}[!htb] \centering \caption{My caption} \label{my-label} \begin{tabular}{>{\hangindent=1.5em\hangafter=1}p{4cm}c} \thead{Header} & \thead{Header} \\ Some really long text\newline which I would like\newline to break up\newline with a hanging indent & Short Text \end{tabular} \end{table} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Result should be 11 after incrementing, it is 12, why? using namespace std; int main() { int n, *p1, *p2; n = 10; p1 = &n; p2 = p1; (*p1)++; (*p2)++; cout << *p1 << " " << *p2 << " "<< n << endl ; return 0; } A: *p1 refers to the value pointed by the pointer p1. (*p1)++ will increment the value of n by 1 and (*p2)++ will again do the increment on n, since it is pointing to the same location of p1. So the n will be incremented to 12. *p1,*p2 and n will thus have 12. So it prints 12.
{ "pile_set_name": "StackExchange" }
Q: Equal Extrusions? I am trying to extrude this so all edges are equal distance from their origin edges? But when I extrude and size them it turns out like this. How can I get them equal distance apart? When I change the Offset it doesn't extrude like yours is? Mine goes to the side? A: You could use Extrude Along Vetex Normals on the side faces. It requires a bit of cleanup afterwards Delete the top faces Extrude side faces along vertex normals normals Alt + E Delete extra faces Bridge the two remaining edgeloops with Bridge Edge Loops s EDIT Make sure your your mesh is uniformly scaled on all axis, and you have applied scale to the object, otherwise the operation will still be deformed. Use the operator panel to the left of the 3D screen to introduce accurate distances
{ "pile_set_name": "StackExchange" }
Q: Image not store in sqlite I made one demo which stores an Image to the database. Currently I am not getting any error but my image is not store in sqlite database. Please see the below code and tell me where is my mistake. DBManager class sqlite3 *sqlite3DatabaseObject; sqlite3_stmt* sqlite3Statement; -(void)database { directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); documentsDirectory = [directoryPaths objectAtIndex:0]; NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"informationdb.sql"]]; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:databasePath] == NO) { const char *dbPath = [databasePath UTF8String]; if (sqlite3_open(dbPath, &sqlite3DatabaseObject)== SQLITE_OK) { char * errorMessage; const char *sqlite3Query = "CREATE TABLE IF NOT EXISTS PICTURES (PHOTO BLOB)"; if (sqlite3_exec(sqlite3DatabaseObject, sqlite3Query, NULL, NULL, &errorMessage)!= SQLITE_OK) { NSLog(@"failed = %@",sqlite3DatabaseObject); } sqlite3_close(sqlite3DatabaseObject); }else{ NSLog(@"failed to create database"); } } } - (void) SaveImagesToSql: (NSData*) imgData { NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"informationdb" ofType:@"sql"]; const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)"; int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL); if (openDatabaseResult == SQLITE_OK) { int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL); if( sqlite3Prepare == SQLITE_OK ) { sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT); sqlite3_step(sqlite3Statement); } else { NSLog(@"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject)); } sqlite3_finalize(sqlite3Statement); } else NSLog( @"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject) ); sqlite3_close(sqlite3DatabaseObject); } ViewController class - (void)viewDidLoad { [super viewDidLoad]; DBManager * dbmClass = [[DBManager alloc]init]; [dbmClass database]; imgView.userInteractionEnabled = YES; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(uploadOrCapture)]; [singleTap setNumberOfTapsRequired:1]; [imgView addGestureRecognizer:singleTap]; } - (IBAction)btnSave:(id)sender { DBManager*dbmClass = [[DBManager alloc]init]; NSData *imageInData = UIImagePNGRepresentation(imgView.image); [dbmClass SaveImagesToSql:imageInData]; [self dismissViewControllerAnimated:YES completion:nil]; } I am not able to find out the issue. It successfully executes all the code but when I download the database from device and checked, there is no image data stored. Thanks in advance. Mihir. A: just replace this function to my code because you got wrong database path - (void) SaveImagesToSql: (NSData*) imgData { directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); documentsDirectory = [directoryPaths objectAtIndex:0]; NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"informationdb.sql"]]; const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)"; int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL); if (openDatabaseResult == SQLITE_OK) { int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL); if( sqlite3Prepare == SQLITE_OK ) { sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT); sqlite3_step(sqlite3Statement); } else { NSLog(@"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject)); } sqlite3_finalize(sqlite3Statement); } else NSLog( @"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject) ); sqlite3_close(sqlite3DatabaseObject); } here this is database screenshot Don't drag to database in your project.if any problem than tell me
{ "pile_set_name": "StackExchange" }
Q: Permanent SSH Connection via Bash Script? I have two OpenSolaris servers. The remote server has a MySQL database. MySQL is configured with skip-networking; so, I can't access that database from the first server by simply using the hostname and port. I must have an ssh tunnel setup to connect to MySQL from the local server. I can do this with a simple : ssh -L 3350:localhost:3306 user@server and SSH keys. It works great. However, I need the connection to be permanent and preferably run on bootup as well. I've created a little bash script to create the connection. However, it simply connects, ends the script, and loses the ssh connection. If I modify the script to run a command on the remote server and and a sleep command, it will stay connected for X seconds. I can then connect with MySQL. However, I will surely lose the connection after X seconds. Does anyone have suggestions for a more elegant way to do this? Is there someway to use Solaris' svcadm to create the connection and maintain it at all times? UPDATE : I've discovered that if I add sleep X and then create the MySQL connection before X expires, the ssh connection stays up indefinitely. However, that is not a very stable solution. If I lose the database connection, the ssh connection dies and then I'll be stuck without being able to connect again. A: You want the -N option to OpenSSH. For example: ssh -N -L 3350:localhost:3306 user@server &
{ "pile_set_name": "StackExchange" }
Q: Why is array in collection view getting multiplied by amount of sections? When I want to see an array in a collection view in swift, it gets multiplied by the amount of sections in the collection view. Why is this and how do I stop it? let numbers = ["one", "two", "three"] func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let theCell = collectionView.dequeueReusableCell(withReuseIdentifier: "theCell", for: indexPath) as! cell for number in numbers { print("\(number)") } return theCell } I hoped that it would return: one two three but instead it returned: one two three one two three one two three A: Since you have three cells per section, and assuming you have only one section, collectionView(_:cellForItemAt:) gets called three times. Each time you are printing all the elements of the numbers array. To only print the element corresponding to the current index, replace the for loop by: print(numbers[indexPath.row])
{ "pile_set_name": "StackExchange" }
Q: "top x% this month" appears lower even though my rank is higher I was active mainly in Stack Overflow but recently joined the beta Arabic.SE. In Arabic.SE I am holding the 1st rank monthly, however it shows in my profile that I am in the top 8% this month: In the other hand, on SO, it shows I am in 2% this month: How is that possible? Shouldn't it be a better percentage where my rank is higher? A: For Stack Overflow this is the calculation: Your rank: 3,118 Users with reputation activity: 158,471 3,118 / 158,471 = 1,96% And Arabic Language: Your rank: 1 Users with reputation activity: 13 1 / 13 = 7,69% The point in this is: there are much less active users on Arabic than on SO, so your top % will be lower on Arabic, even when you are first.
{ "pile_set_name": "StackExchange" }
Q: Why is a cell in anaphase (without a nuclear envelope) be considered as a eukaryotic cell? Can anyone shed some light on this? All I can think of is that it has something to do with the chromosomes being paired A: It is still considered a Eukaryotic cell because the daughter cells and mother cell are both Eukaryotic; the chromosomes will condense and be contained in a Nucleus after Telophase and Cytokinesis. Furthermore, Prokaryotic binary fission does not involve the assembly of Spindle Fibers, whereas dividing Eukaryotic cells in Anaphase use Spindle fibers to transport the Chromosomes towards the poles of the dividing cell. I hope this answers your question!! :)
{ "pile_set_name": "StackExchange" }
Q: How to count each item in array with sql I have a user table which contain a membergroupids, and user table looks like this: userid membergroupids 1 1,2 2 2,3 3 2,3,4 and I want to use sql to output a result like this membergroupid count 1 1 2 3 3 2 4 1 I tried use SELECT membergroupids FROM user, then use php to loop through the result and get the count, but it works with small set of user table, but I have a really big user table, the select query itself will take more than 1min to finish, is there better way to do this? A: There is a much better way to do it. Your tables need to be normalized: Instead of userid membergroupids 1 1,2 2 2,3 3 2,3,4 It needs to be userid membergroupids 1 1 1 2 2 2 2 3 3 2 3 3 3 4 From here, it's a simple query to get the counts (assuming this table is called your_table: select count(membergroupids) as numberofgroups, userid from your_table group by userid order by userid The real problem, then, is getting your tables normalized. If you only have 9 membergroupids, then you could use a like '%1%' to find all userids with membergroupid #1. But if you have 10, then it won't be able to distinguish between 1 and 10. And sadly, you can't count on the commas to help you distinguish because the number might not be surrounded by commas. unless... Create new field with group ids encapsulated by commas you could create a new field and populate it with membergroupids and surround it with commas by using concat (check your database's docs). Something along this line: update your_table set temp=concat(',', membergroupids, ','); This could give you a table structure like so: userid membergroupids temp 1 1,2 ,1,2, 2 2,3 ,2,3, 3 2,3,4 ,2,3,4, Now, you have the ability to grab distinct member group ids in the new field, ie, where temp like '%,1,%' to find userids with membergroupid 1. (They will be encapsulated by commas) Now, you can manually build your new normalized table which I'll call user_member. Insert membergroupid 1: insert into user_member (userid,membergroupid) select userid,'1' from your_table where temp like '%,1,%'; You could make a php script that loops through all the membergroupids. Keep in mind that like %...% is not very efficient, so don't even think about relying on this to do your count. It'll work, but it's not scalable. It would be much better to use this to build the normalized table.
{ "pile_set_name": "StackExchange" }
Q: Coffeescript class object in array I have some class with some functions and properties exports.textareaWidget = class textareaWidget extends Widget name = null getHtml: -> this.generateHtml(widgetHtml) Then I create an object and add to array: obj = new w.textareaWidget() obj.name = "msgBody" console.log obj.getHtml() # works arr.push(obj) # getting from arr for field in arr result = result + field.getHtml() When I want to get it from array I can access properites (name) but I can't access functions (getHtml). Why and how can I make it working ? The error: TypeError: Object #<Object> has no method 'getHtml' A: You probably mean to indent the name and getHtml definitions: exports.textareaWidget = class textareaWidget name: null getHtml: -> this.generateHtml(widgetHtml)
{ "pile_set_name": "StackExchange" }
Q: Use one OrbitControls with two cameras in ThreeJS? I have two canvases on a page. I would like to have one OrbitControls that controls the cameras on each canvas. If the user zooms on canvas1, I would like canvas2 to zoom as well. How can I go about this? A: You can create two instances of orbit controls and move the other camera when you detect that the first has moved in the first scene. // initialize two scenes, renderers, and cameras const controls1 = new THREE.OrbitControls( camera1, renderer1.domElement ); const controls2 = new THREE.OrbitControls( camera2, renderer2.domElement ); controls1.addEventListener( 'change', () => { camera2.position.copy( camera1.position ); camera2.rotation.copy( camera1.rotation ); render(); } ); controls1.addEventListener( 'change', () => { camera1.position.copy( camera2.position ); camera1.rotation.copy( camera2.rotation ); render(); } ); Here's an example implementation: https://jsfiddle.net/62x8c139/. In this case both cameras will be positioned in the exact same spot in both scenes. Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Entity using include to load related tables but how to left outer join it I need to load some users and some stats, but not all the stats. Normal I can load something like this: db.stat_user.ToList() and access it by db.stat_user.local (it then have the added items, and the preloaded) stat_user is 1 to manny to stat_counter, and is set up with the relation, from the sql server. There holds stat and a year, I just want to preload etc. one year. This expression works, but it loads all related stat_counters db.stat_user.include("stat_counter").tolist(); Then I tried this: db.stat_user .Include("stat_counter") .Where(e => e.stat_counter.Any(a => a.year == year)) .ToList(); Still loads all, but only needs for one year! How to get data and still have the feature of etc. db.stat_user.local. have preloaded related stat_counters? I run with these flags: db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.LazyLoadingEnabled = false; Need to preload in memory, else it takes for ages to calculate. A: Well as Sergey mentioned its not possible right away so ended up with: List<stat_user> lsu = s.stat_user.ToList(); List<int> ids = lsu.Select(e => e.id).ToList(); List<stat_counter> lsc = s.stat_counter.Where(e => e.year == year && ids.Contains(e.user_fk)) .ToList(); Then lsu users is auto linked with those stat_counters loaded later in EF. That give antoher issue, how to clear the EF, only way i found is to create a hole new instance!
{ "pile_set_name": "StackExchange" }
Q: Нормально ли удалять комментарии о том, что всё работает под конкурирующими ответами? Вот вопрос с двумя ответами. Один из них получил от автора вопроса комментарий Спасибо. Вот это работает. а другой Эта конструкция почему-то не работает (Python 3.7)/(PyCharm 2020.2) Из-за того, что в первом комментарии есть слово "спасибо", любой человек может удалить его одним голосом, что и произошло. На мой взгляд, удаление подобных комментариев в принципе неправильно, поскольку в комментарии содержится полезная информация о том, что ответ действительно правильный. Ещё меньше мне нравится ситуация, когда такой комментарий удаляется автором конкурирующего ответа. И ещё меньше, когда под этим самым ответом написано, что он не подошёл. Считаем ли мы по-прежнему, что это нормально и любые комментарии с благодарностями могут удаляться кем угодно? A: На мой взгляд, удаление подобных комментариев в принципе неправильно Правильно. Если ответ работает, то его нужно принимать и ставить галочку, а не комментарий писать.
{ "pile_set_name": "StackExchange" }
Q: I have base class which implemented IClientValidatable I have base class(CompareAttribute) which implemented IClientValidatable [AttributeUsage(AttributeTargets.Property)] public class NotContainsAttribute : CompareAttribute { } I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override). So i just declare my own method in my NotContainsAttribute class public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { } After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.) But if I use new keyword public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty)); yield break; } In such case my method not used, base class method used instead. I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended? I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method. May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it? A: I don't think your assessment of the situation is correct: If the base class method is not marked as virtual then your method implementation will be hiding it by default. From MSDN: If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present. You just get a compiler warning because often this is not what the intention of the programmer is and it gives you a chance to correct this common mistake - usually you want to override a base class implementation. It should not make a difference whether or not you mark your method with new - this just makes it explicit that you are in fact hiding the base class method. Also note that hiding a base class method will not allow this method to be used in a polymorphic fashion: object references typed as the base class that point to an instance of your derived class will use the base class method instead: CompareAttribute foo = new NotContainsAttribute(); foo.GetClientValidationRules(..) // will call base class method So your method only will be called if you call the method on an object reference with type NotContainsAttribute : NotContainsAttribute bar = new NotContainsAttribute(); bar.GetClientValidationRules(..) // will call your method Also see "Versioning with the Override and New Keywords (C# Programming Guide)" and "Polymorphism, Method Hiding and Overriding in C#" as a reference.
{ "pile_set_name": "StackExchange" }
Q: The External Change Data Capture doesn't work with an error! I'm using OData v4.0 and the External Object is set in Salesforce, which is connected with Heroku Connect. However, the Change Data Capture feature does not work, and the following error occurs. "Error: Can't schedule the next polling request for data changes. The OData producer doesn't support change tracking. The Preference-Applied header for odata.track-changes is missing in the response." Please look a moment this issue. Thank you so much. A: As per OData doc - http://docs.oasis-open.org/odata/odata/v4.0/cs01/part1-protocol/odata-v4.0-cs01-part1-protocol.html#_Toc365046251 In a response to a request that specifies a Prefer header, a service MAY include a Preference-Applied header, as defined in [HTTP-Prefer], specifying how individual preferences within the request were handled. The value of the Preference-Applied header is a comma-separated list of preferences applied in the response. Salesforce typically checks that the prefer header should be sent back as Preference-Applied to make sure that the service understood the request and is able to track changes. Not all OData 4 providers are capable and if not, they may ignore the header and not track changes. AFAIK, Heroku DB does not implement data change tracking (yet) - I believe it is on their roadmap.
{ "pile_set_name": "StackExchange" }
Q: Using "this" keyword inside nested static class java I have a class say A, and a static nested class say B. public class A { public static class B { B(Temp x) { x.reg(this); // need to pass the nested class reference. } } } Is the above code correct? Can we use this keyword inside nested static class constructor? Please help me on this. Thanks. A: yes, it is. For the runtime, inner classes are just another, separate class. If the inner class is not static it will just have a reference to the outer class, but in your case it's static so not even, so it is exactly as if you created a new class in a new file Just make sure that you write "public", not "Public"
{ "pile_set_name": "StackExchange" }
Q: What are the typical differences between doing a math phd and an engineering phd on the same research topic? What are the typical differences between doing a math phd and an engineering phd on the same research topic? Take, for example, fluid dynamics. Does working on a phd thesis on a problem in fluid dynamics, in an engineering program make the problem "more applied" than working on the same problem in the math program? Do engineering phd programs do any work on theory at all? Or is it strictly applications? A: There is a wide spectrum of possibilities in doing research in either mathematics or engineering. There are definitely people doing research under the auspices of an engineering department that is nearly as mathematically rigorous as in a pure math program. The only exception to this is that pure mathematics programs do not look highly upon a fully applications-driven project under its auspices: there needs to be some sort of additional theory or analysis development. But it's certainly possible to do a very highly mathematical project in an engineer department. My own thesis work amounted to algorithm development and analysis, with very limited application demonstrations. While I didn't have formal proofs the way you might in a pure math thesis, the project wouldn't really look like an "engineering" project—and certainly wasn't published in engineering journals! So, in short, the main distinction I'd make is that one might expect to see more formal proofs and analysis, but no real distinctions in the kinds of problems that are tackled.
{ "pile_set_name": "StackExchange" }
Q: Почему возникает ошибка преобразования типов? void CMy2Dlg::OnBnClickedButton1() { UpdateData(true); int word_count; int word_letter; int letter_summ; CString main_temp; word_count = 0; word_letter = 0; letter_summ = 0; main_temp = m_in; for (int j = 0; j < main_temp.GetLength(); j++) { if (main_temp.Find(" ") >= 0) { word_count++; word_letter = main_temp.Find(" "); main_temp = main_temp.Right(main_temp.GetLength() - main_temp.Find(" ") - 1); } letter_summ += word_letter; word_letter = 0; } letter_summ += main_temp.GetLength(); word_count++; double temp; temp = double (letter_summ) / double (word_count); m_out.Format("Cреднее число букв в слове: %.3f", temp); UpdateData(false); } Выдаёт ошибку Не существует контекста, в котором такое преобразование возможно c:\users\вовка\documents\visual studio 2010\projects\2\2\2dlg.cpp(184): error C2664: int ATL::CStringT<BaseType,StringTraits>::Find(wchar_t,int) throw() const: невозможно преобразовать параметр 1 из "const char [2]" в "wchar_t" with [ BaseType=wchar_t, StringTraits=StrTraitMFC_DLL<wchar_t> ] A: надо .Find(L' ') вместо .Find(" ")
{ "pile_set_name": "StackExchange" }
Q: Trying to find factors of a number in JS I am just starting JS, and understand the concept of finding a factor. However, this snippet of code is what I have so far. I have the str variable that outputs nothing but the first factor which is 2. I am trying to add each (int) to the str as a list of factors. What's the wrong in below code snippet? function calculate(num) { var str = ""; var int = 2; if (num % int == 0) { str = str + int; int++; } else { int++; } alert(str); } calculate(232); A: ES6 version: const factors = number => Array .from(Array(number + 1), (_, i) => i) .filter(i => number % i === 0) console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36] https://jsfiddle.net/1bkpq17b/ Array(number) creates an empty array of [number] places Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9] .filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number. Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small). As @gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method: const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0); console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36] A: @Moob's answer is correct. You must use a loop. However, you can speed up the process by determining if each number is even or odd. Odd numbers don't need to be checked against every number like evens do. Odd numbers can be checked against every-other number. Also, we don't need to check past half the given number as nothing above half will work. Excluding 0 and starting with 1: function calculate(num) { var half = Math.floor(num / 2), // Ensures a whole number <= num. str = '1', // 1 will be a part of every solution. i, j; // Determine our increment value for the loop and starting point. num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2); for (i; i <= half; i += j) { num % i === 0 ? str += ',' + i : false; } str += ',' + num; // Always include the original number. alert(str); } calculate(232); http://jsfiddle.net/r8wh715t/ While I understand in your particular case (calculating 232) computation speed isn't a factor (<-- no pun intended), it could be an issue for larger numbers or multiple calculations. I was working on Project Euler problem #12 where I needed this type of function and computation speed was crucial. A: As an even more performant complement to @the-quodesmith's answer, once you have a factor, you know immediately what its pairing product is: function getFactors(num) { const isEven = num % 2 === 0; let inc = isEven ? 1 : 2; let factors = [1, num]; for (let curFactor = isEven ? 2 : 3; Math.pow(curFactor, 2) <= num; curFactor += inc) { if (num % curFactor !== 0) continue; factors.push(curFactor); let compliment = num / curFactor; if (compliment !== curFactor) factors.push(compliment); } return factors; } for getFactors(300) this will run the loop only 15 times, as opposed to +-150 for the original.
{ "pile_set_name": "StackExchange" }
Q: What's the proper way of setting environment variable in Netlify functions? What's the proper way of setting environment variables in netlify? I would like to be able to set different values for the variables depending on the environment. Pseudo code: let host; if (process.env.GATSBY_CUSTOM_CONTEXT === 'production') { host = process.env.PRODUCTION_HOST } else if (process.env.GATSBY_CUSTOM_CONTEXT === 'development') { host = process.env.DEVELOPMENT_HOST } I have tried passing env variable thru CLI, like GATSBY_CUSTOM_CONTEXT=production gatsby build and I also tried using same command with cross-env. My other attempt used netlify.toml: [build] base = "/" publish = "public" command = "yarn build" functions = "src/functions" [context.production] [context.production.environment] GATSBY_CUSTOM_CONTEXT = "production" All of these options worked with netlify dev locally, but in production GATSBY_CUSTOM_CONTEXT is always undefined. A: The reason you can't resolve the environment variables in your Netlify functions is because as of the time of your question, Netlify does not transfer the environment variables from the netlify.toml file. You must put them into the admin panel in your site settings in the app.netlify.com dashboard.
{ "pile_set_name": "StackExchange" }
Q: Angular Service Worker can't fetch SVG files I use a service worker in my Angular app. All the files in my assets folder are cached, as declared in my ngsw-config.json file. { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ] } } I have .svg and .png files in my assets folder. When I build my app for production and visit my site for the first time, eveything works fine, but as soon as I reload the page, I get the following error in my console. Uncaught (in promise) Error: Hash mismatch (cacheBustedFetchFromNetwork) This problem only occurs when the browser tries to fetch a .svg file. It works fine with .png files I load all my .svg file inside of an <img> tag. I wonder if I did something wrong, or if it is a problem with the Angular Service Worker? A: I had the same problem, consider using the svg files inline and not like that: <img src="assets/imgs/img.svg" /> Hope that helps
{ "pile_set_name": "StackExchange" }
Q: Symfony cache:clear php.CRITICAL: Fatal error: Allowed memory size I am encoutering the following error with Symfony when trying to php app/console cache:clear or php app/console cache:warmup Fatal error: Allowed memory size of xxx bytes exhausted. I already set memory limit to very large size 1024M, 2048M. I removed all twig templates from my project I unactivated vendors bundles leaving only FOSUSer and FOSRestBundle. I am unable to track from where this error comes from. Any idea? Thanks I get the following error A: In the end, it was that little piece of code that was the problem: # config.yml ... twig: paths: "%kernel.root_dir%": app Thanks guys for confirming me that it was Twig the problem.
{ "pile_set_name": "StackExchange" }
Q: how to pass params as json in ajax call from ruby? I am making ajax rest call from ruby and its going to python to do rest call proccess. when i trying to call rest and passing params in json formate, i think its may not passing this as json data. My ajax call is following: get '/cnet' do temp="mynet" url = URI.parse('http://192.168.1.9:8080/v2.0/networks') params = {'net_name'=>temp}.to_json resp = Net::HTTP.post_form(url, params) resp_text = resp.body puts resp_text erb resp_text end Python code is following: @app.route('/v2.0/networks',methods=['POST']) def net_create(): net_res=request.json print "=======================" print net_res['net_name'] print "=======================" net_name=net_res['net_name'] when i am trying to read json data from python its giving following error: File "/network-ui/neutron_plugin.py", line 226, in net_create net_name=net_res['net_name'] TypeError: 'NoneType' object has no attribute '__getitem__' I don't know what is exactly happening. I am following there link for ajax post call: http://rest.elkstein.org/2008/02/using-rest-in-ruby.html http://developer.yahoo.com/ruby/ruby-rest.html Any help much appreciated. Thanks A: Don't pass JSON to Net::HTTP. The method requires a simple ruby hash. In fact, you send POST params - POST params are sent through the HTTP request body, they are not JSON or whatever, just simple strings. This is HTTP basics, so i suggest you read a bit about how things work over this protocol, it will be a lot easier if you understand it. Regarding the python side, I don't know much Python but if you really need JSON (which i doubt), you will have to somehow parse the params.
{ "pile_set_name": "StackExchange" }
Q: Different versions of django I have just moved my django application to another server, which I have configured a long time ago, so I'm not really sure what's installed and configured. When running the application, I started getting weird errors, which pointed to running an old version of django. Hence, I decided to check the version. First, I ran: python -c "import django; print(django.get_version())" which showed version 1.3.1. So then I did sudo easy_install --upgrade django which ran fine, but when running the first command again, it still shows 1.3.1, so I decided to do: django-admin.py version and this returned 1.6.5. Therefore, I assume that I have installed the latest django version, but for some reason python is using 1.3.1. How can I get python to use the latest version of django? A: Firstly do not use easy_install but pip: easy install pip Try to install/update from pip: pip install django --upgrade If it fails, try to uninstall and after réinstall: pip uninstall django Be careful if you've installed django with Ubuntu's apt-get. It's a bad thing to mix system and python installers. Uninstall from apt-get if it's the case: apt-get remove python-django
{ "pile_set_name": "StackExchange" }
Q: Why does the code below give a segmentation fault? #include <stdio.h> #include <stdlib.h> struct node{ int data; struct node *next; }; void print (struct node* ptr) { struct node* iter = ptr; while (iter!=NULL) { printf ("%d",iter->data); iter = iter -> next; } } void printWantedIndice (struct node*ptr,int indice) { struct node*iter=ptr; int counter=1; while (counter<indice) { iter = iter -> next; counter++; } printf ("%d",iter->next->data); } int main () { struct node* head = (struct node*)malloc(sizeof(struct node)); head -> data = 15; head -> next -> data = 44; head -> next -> next = NULL; print(head); } i tried to code linked list, first "print" function is for printing every indice, the second function "printWantedIndice" is a function for printing the wanted Indice .it gives a segmentation fault. i couldn't understand why. can you help with that? A: The following line is the cause: head->next->data = 44; Since head->next is not initialized, you'll get a segmentation fault from trying to access it.
{ "pile_set_name": "StackExchange" }
Q: Formik reset errors I am trying to reset all errors in the form. I tried using setErrors and setStatus, none of these are working. Errors in Formik state is not getting cleared. setErrors({errors: {}}) and setStatus({ errors: {}}); None of the above worked. resetForm() clears all errors, but the form values are also reset which I don't want. Any pointers to clear only the errors object? A: While using setErrors, just pass the state of errors object you want. So to reset all errors, pass an empty object({}). setErrors({}) Codesandbox demo here.
{ "pile_set_name": "StackExchange" }
Q: newline in Leaflet marker popup text I have a form to associate some text to a marker on a Leaflet map: <form action="map.php" method="POST"> <section> <label>write some text here</label> <textarea id="text" rows="3" name="area"></textarea> </section> <input type="submit" value="show map" /> </form> As you can see above, the content of the textarea is passed to the page map.php, where a map is shown. On the map, the place marker is shown, and a popup contains the text posted through the textarea (variable $text): <?php $text = htmlspecialchars($_POST["text"]); ?> <center> <div id="map" class="embed-container"></div> </center> <script> var map = L.map('map').setView([46.13, 11.11], 9); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', maxZoom: 17, minZoom: 9 }).addTo(map); </script> <script> var icon = L.icon({ iconUrl: 'img/gps.png', iconSize: [25, 25], }); var marker = L.marker(['<?=$latitude;?>', '<?=$longitude;?>'], {icon: icon}).addTo(map); marker.bindPopup('<?=$text;?>'); </script> The problem is that if I press ENTER while I write something in the textarea, nothing is passed to the popup marker. I tried with \n and such, but nothing works. They are shown in the popup text as strings, not as newlines. Any ideas? A: The problem is that if I press ENTER while I write something in the textarea, nothing is passed to the popup marker. This is inaccurate. The HTML inside the popup is receiving a newline character. The problem is that the newline character is being displayed as collapsed whitespace. This is the default in HTML. Let me quote the documentation for the white-space CSS property, inherited by default by all HTML elements: normal Sequences of whitespace are collapsed. Newline characters in the source are handled as other whitespace. Breaks lines as necessary to fill line boxes. HTML collapses whitespace characters, including tabs and line breaks (but excluding &nbsp;s). Text inside Leaflet popups simply follow the same rule. Replace your newlines with HTML <br> line breaks, or otherwise wrap every line in a block-level element like a <div>. If you are using php, the easiest way is to use the nl2br function. This is not necessarily the best way, as it is very prone to allowing XSS attacks in the hands of inexperienced developers. Using htmlspecialchars will not help if you are outputting JavaScript strings, enclosed in quotes. For these cases I recommend using json_encode to provide the quotes and the quote scaping, i.e. var foo = <?= json_encode(nl2br(str)); ?>;
{ "pile_set_name": "StackExchange" }
Q: reverse_iterator related crashes in Visual C++. Is it legal code? I was playing around with some code today, and was very surprised to find out that the following code crashes in Visual C++. Does it look OK? gcc prints out 1 when I run the code. So does Intel. #include <iostream> #include <set> #include <assert.h> int main() { std::set<int> sampleSet; sampleSet.insert(1); sampleSet.insert(2); sampleSet.insert(3); std::set<int>::iterator normalIt(sampleSet.begin()); std::set<int>::reverse_iterator reverseIt(sampleSet.rbegin()); ++normalIt; ++reverseIt; int test1(*reverseIt); // 2 assert(*normalIt == *reverseIt); //they're both = 2 std::set<int>::iterator gonnaDelete((++reverseIt).base()); // gonnaDelete points to 2 int test2(*reverseIt); // 1 sampleSet.erase(gonnaDelete); int test3(*reverseIt); // 1??? Visual Studio 2010 crashes here.... gcc is fine, but not sure if this is legal std::cout << test3 << std::endl; return 0; } A: It's not legal. According to [lib.associative.reqmts] in C++98, "the erase members shall invalidate only iterators and references to the erased elements." Since reverse_iterator is defined something like: template<typename Iter> class reverse_iterator { Iter current; Iter tmp; public: ... Iter base() { return current; } reference operator*() { tmp = current; --tmp; return *tmp; } }; when you erase gonnaDelete you also invalidate reverseIt.current, so when you subsequently dereference reverseIt, you get undefined behavior. Now, set iterators tend to be simple pointers to nodes, and optimized allocators sometimes leave the memory of a deleted node alone, so the code sometimes happens to do what you expect even after you've invalidated one of them, but it's not at all guaranteed to work. I suspect VC++ has a debugging mode on by default to catch this kind of mistake. To turn on gcc's equivalent mode, try building with -D_GLIBCXX_DEBUG: http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/manual/manual/bk01pt03ch17s03.html
{ "pile_set_name": "StackExchange" }
Q: JavaScript and why capital letters sometimes work and sometimes don't In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working. I has used the auto-complete plugin provided with Notepad++, which presented me with onClick. When I changed the capital C to a small c, it did work. So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals. But when you change getElementById to getelementbyid, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters. So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't? A: Javascript is ALWAYS case-sensitive, html is not. It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this: <div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C' or: <div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C' but through the DOM you must use the correct case. So this works: getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C' but you cannot do this: getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C' EDIT: CMS makes a great point that most DOM methods and properties are in camelCase. The one exception that comes to mind are event handler properties and these are generally accepted to be the wrong way to attach to events anyway. Prefer using addEventListener as in: document.getElementById('divYo').addEventListener('click', modifyText, false); A: A few objects is IE aren't always case-sensitive, including some/most/all ActiveX -- why both XHR.onReadyStateChange and XHR.onreadystatechange would work fine in IE5 or IE6, but only the latter would work with the native XMLHttpRequest object in IE7, FF, etc. But, a quick reference for "standard" API casing: UPPERCASE - Constants (generally symbolic, since const isn't globally supported) Capitalized - Classes/Object functions lowercase - Events camelCase - everything else No 100% guarantees. But, majority-wise, this is accurate.
{ "pile_set_name": "StackExchange" }
Q: Does a LSA or better license count for drone use? I have a FAA private pilot license. Does that allow me the same flight privileges while flying a drone, as a FAA certificated drone pilot? A: No, it does not. But because you are an "existing pilot", the application process is a little different: FAA: Becoming a (Drone) Pilot Existing Pilots – What to Expect Eligibility: Must hold a pilot certificate issued under 14 CFR part 61 Must have completed a flight review within the previous 24 months Remote Pilot Certificate Requirements Must be easily accessible by the remote pilot during all UAS operations Valid for 2 years – certificate holders must pass either a recurrent online training course OR recurrent knowledge test every two years Application Process: Complete the online training course "Part 107 small Unmanned Aircraft Systems (sUAS) ALC-451" available on the FAA FAASTeam website – initial training course areas include: a. Applicable regulations relating to small unmanned aircraft system rating privileges, limitations, and flight operation b. Effects of weather on small unmanned aircraft performance c. Small unmanned aircraft loading and performance d. Emergency procedures e. Crew resource management f. Determining the performance of small unmanned aircraft g. Maintenance and preflight inspection procedures Complete FAA Form 8710-13 (FAA Airman Certificate and/or Rating Application for a remote pilot certificate) a. Online or by paper (see instructions in previous section) Validate applicant identity a. Contact a FSDO, an FAA-designated pilot examiner (DPE), an airman certification representative (ACR), or an FAA-certificated flight instructor (CFI) to make an appointment. b. Present the completed FAA Form 8710-13 along with the online course completion certificate or knowledge test report (as applicable) and proof of a current flight review. c. The completed FAA Form 8710-13 application will be signed by the applicant after the FSDO, DPE, ACR, or CFI examines the applicant's photo identification and verifies the applicant's identity.    - The identification presented must include a photograph of the applicant, the applicant's signature, and the applicant's actual residential address (if different from the mailing address). This information may be presented in more than one form of identification.    - Acceptable methods of identification include, but are not limited to U.S. drivers' licenses, government identification cards, passports, and military identification cards (see AC 61-65 Certification: Pilots and Flight and Ground Instructors) d. The FAA representative will then sign the application. An appropriate FSDO representative, a DPE, or an ACR will issue the applicant a temporary airman certificate (a CFI is not authorized to issue a temporary certificate; they can process applications for applicants who do not want a temporary certificate). A permanent remote pilot certificate will be sent via mail once all other FAA-internal processing is complete.
{ "pile_set_name": "StackExchange" }
Q: Slick slider "position: fixed" I'm using slick.js and trying to position the slider at the bottom of the page. I'm using position:fixed but it simply breaks the slider, meaning every movement causes each cell to grow, double in size I think. Is there a workaround for this? Here's my code: <div class="cappa__holder"> <div class="cappa">111</div> <div class="cappa">222</div> <div class="cappa">333</div> <div class="cappa">444</div> <div class="cappa">555</div> <div class="cappa">666</div> <div class="cappa">777</div> </div> .cappa__holder { /* uncomment next line to see it break */ //position: fixed; bottom: 0; } .cappa { text-align: center; background:#f1f1f1; margin: 4px; border: 1px solid blue; } $(document).ready(function(){ $('.cappa__holder').slick({ infinite: true, arrows: true, slidesToShow: 4, slidesToScroll: 4, speed: 600 }); }); Here's a fiddle to show the problem A: Problem: when .cappa__holder has position:fixed; and does not have height, the slick can not calculate the size of slides. However, you only need to give width to the .cappa__holder to solve your problem(for example width:100%). Jsfiddle
{ "pile_set_name": "StackExchange" }
Q: No Font-Awesome icons of theme Can anybody tell me how to set up Font Awesome to work with a theme? I have put this in my template file: <div id="social-media-bar" class="container"> <div class="row"> <div class="col-md-2 col-md-offset-2"> <i class="fa fa-linkedin-square fa-3" aria-hidden="true"></i> </div> <div class="col-md-2"> <i class="fa fa-facebook-square fa-3" aria-hidden="true"></i> </div> <div class="col-md-2"> <i class="fa fa-xing-square fa-3" aria-hidden="true"></i> </div> <div class="col-md-2"> <i class="fa fa-twitter-square fa-3" aria-hidden="true"></i> </div> </div> </div> But there are no icons loaded. They aren't loaded in admin mode either but the IP menus have their FA icons as they should. What am I doing wrong? Are some LESS entries necessary in my theme? A: I have used Bootstraps CDN in the head now: <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
{ "pile_set_name": "StackExchange" }
Q: How can I get the length (duration) of an audio file? I'm pulling media files (audio and video) into a template with Assets add-on. It doesn't appear to have the ability to grab the length (duration) of the media being uploaded. Is there a quick and easy way to get it? Edit: MX GetID3 does the trick but not for remote files. If your files are on another subdomain (as mine were), use {server_path} instead of {url} to grab the file path. A: You can use MX GetID3 plugin for this purpose. This addon seems updated before 1 year but it would work.
{ "pile_set_name": "StackExchange" }
Q: How to get color from the pixel? OpenGL I would like to get color from the pixel in my game and save this color in variable. How to do it in opengl? A: glReadPixels(): #include <GL/glut.h> #include <iostream> using namespace std; void display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-10, 10, -10, 10, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glScalef(5,5,5); glBegin(GL_TRIANGLES); glColor3ub(255,0,0); glVertex2f(-1,-1); glColor3ub(0,255,0); glVertex2f(1,-1); glColor3ub(0,0,255); glVertex2f(1,1); glEnd(); glPopMatrix(); glutSwapBuffers(); } void motion(int x, int y) { y = glutGet( GLUT_WINDOW_HEIGHT ) - y; unsigned char pixel[4]; glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixel); cout << "R: " << (int)pixel[0] << endl; cout << "G: " << (int)pixel[1] << endl; cout << "B: " << (int)pixel[2] << endl; cout << endl; } int main(int argc, char **argv) { glutInitWindowSize(640,480); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutCreateWindow("glReadPixels()"); glutDisplayFunc(display); glutPassiveMotionFunc(motion); glutMainLoop(); return 0; } A: struct{ GLubyte red, green, blue; } pixel; glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pixel);
{ "pile_set_name": "StackExchange" }
Q: MySQL: UPDATE with SUM and JOIN I'm trying to do a SUM and store it in another table. The SUM is simple : SELECT award.alias_id, SUM(award.points) AS points FROM award INNER JOIN achiever ON award.id = achiever.award_id I now want to store that. I figured out how to do it on a row-by-row basis : UPDATE aliaspoint SET points = (SELECT SUM(award.points) AS points FROM award INNER JOIN achiever ON award.id = achiever.award_id WHERE achiever.alias_id = 2000) WHERE alias_id = 2000; I thought something like this might work but I get: ERROR 1111 (HY000): Invalid use of group function UPDATE aliaspoint INNER JOIN achiever ON aliaspoint.alias_id = achiever.alias_id INNER JOIN award ON achiever.award_id = award.id SET aliaspoint.points = SUM(award.points) And some table definitions to help : mysql> show create table aliaspoint; | metaward_aliaspoint | CREATE TABLE `aliaspoint` ( `id` int(11) NOT NULL AUTO_INCREMENT, `alias_id` int(11) NOT NULL, `points` double DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `alias_id` (`alias_id`), KEY `aliaspoint_points` (`points`) ) ENGINE=MyISAM AUTO_INCREMENT=932081 DEFAULT CHARSET=latin1 | mysql> show create table achiever; | metaward_achiever | CREATE TABLE `achiever` ( `id` int(11) NOT NULL AUTO_INCREMENT, `modified` datetime NOT NULL, `created` datetime NOT NULL, `award_id` int(11) NOT NULL, `alias_id` int(11) NOT NULL, `count` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `achiever_award_id` (`award_id`), KEY `achiever_alias_id` (`alias_id`) ) ENGINE=MyISAM AUTO_INCREMENT=87784996 DEFAULT CHARSET=utf8 | mysql> show create table award; | metaward_award | CREATE TABLE `award` ( `id` int(11) NOT NULL AUTO_INCREMENT, `points` double DEFAULT NULL, PRIMARY KEY (`id`), ) ENGINE=MyISAM AUTO_INCREMENT=131398 DEFAULT CHARSET=utf8 | A: You're missing the GROUP BY clause in: SET points = (SELECT SUM(award.points) AS points FROM award INNER JOIN achiever ON award.id = achiever.award_id WHERE achiever.alias_id = 2000) There isn't enough information on the AWARD and ACHIEVER tables, so I recommend testing this before updating the UPDATE statement: SELECT t.id, -- omit once confirmed data is correct a.alias_id, -- omit once confirmed data is correct SUM(t.points) AS points FROM AWARD t JOIN ACHIEVER a ON a.award_id = t.id GROUP BY t.id, a.alias_id Once you know the summing is correct, update the INSERT statement: SET points = (SELECT SUM(t.points) FROM AWARD t JOIN ACHIEVER a ON a.award_id = t.id WHERE a.alias_id = 2000 --don't include if you don't need it GROUP BY t.id, a.alias_id)
{ "pile_set_name": "StackExchange" }
Q: Developing a whole application (not a single class) with TDD (BDD)? After a lot of reading, learning examples and making simple class tests I desided to create my first simple real-life application using TDD. My application should have the following behavior: it's a console application with no user interface it will download a Json (which represents an array) from some URL extract some data from this array download another Jsons using data from the first step pass all this data in a file in a specified format. Actually this application pulls a list of regions and cities from some website. I able to perform refactoring, know what is low coupling, etc. but after several attempts I realize that I completely don't know an idea on how to design a whole application with TDD. What are my first steps to build this particular application using TDD? What is the base which will grow into the complete application? I'm using PHP but this doesn't matter as I don't need code examples. Just an idea and, ideally, how this idea could be embodied in my particular case. What are the concrete first tests I should implement? Why? I think there are a lot of people would love to know an answer. Thank you very much TDD guys! A: Test Driven Design starts with a test plan. The first cut of the test plan doesn't involve code in any way; it only looks at determining what a successful solution looks like. From your example: Invoking the application will create a file that has the following information in it ... The next cut of your test plan looks at the resulting file in a lot more detail. How do you test that the content of the file is well-formed and is valid? How do you verify the content of the file? For instance, well-formed XML files can be passed through an XML parser of any kind without an error report. Valid XML files can be validated against a schema. To this point, you don't need to write any code. Create the XML schema, and create test files that are well-formed and also test files that are valid against the schema. Your testing process will only look at the result. The next cut involves generating the output file. Your first piece of code consists of some test harness (to feed test data in) and the file generator. You can add some correctness tests now. For instance, create examplar output files and compare the files-under-test against the exemplars. diff and cmp are your friends here, but you may need to get a little creative if the XML formatting gets in the way. Keep moving backwards on your input chain. Create JSON files that correspond to the test data from the previous step. Verify the well-formedness and validity of the JSON files using appropriate off-the-shelf tools. Again, use your test harness to match up a JSON file to the desired data to the desired output file. The code you create/deploy here is the JSON parser. Similar step for the next stage. Start by using curl or wget to fetch the JSON file and feed this into your test harness. Again no code is required, just a pipeline of commands. You will have to construct by hand the exemplars for correctness testing, but the well-formedness and validity testing remain the same. Finally, your application embeds the curl functionality and you have end-to-end testing already in place.
{ "pile_set_name": "StackExchange" }
Q: How to pass parameters to devexpress XtraReport from combobox I have a form that contains 3 comboboxes and a button like shown below and a report that containes 3 parameters that are bounded to richtext i used the following code for this process when clicking the button Print but parameters aren't passed and richtext fields are empty private void btnPrint_Click(object sender, EventArgs e) { // Create a report instance. var report = new XtraReport1(); // Obtain a parameter, and set its value. report.ClassName.Value = cmbClass.SelectedText; report.SubclassName.Value = cmbDivision.SelectedText; report.StudentName.Value = cmbStudent.SelectedText; report.RequestParameters = false; // Hide the Parameters UI from end-users. report.ShowPreview(); } A: Use XtraReport.Parameters collection to pass combobox values into parameter names as shown in below example: private void btnPrint_Click(object sender, EventArgs e) { // Create a report instance. var report = new XtraReport1(); // Obtain a parameter, and set its value. report.Parameters["ClassName"].Value = cmbClass.SelectedText; report.Parameters["SubclassName"].Value = cmbDivision.SelectedText; report.Parameters["StudentName"].Value = cmbStudent.SelectedText; report.RequestParameters = false; // Hide the Parameters UI from end-users. report.ShowPreview(); } Or you may declare an overload constructor which assigns parameter values inside it, then create XtraReport instance using overloaded constructor arguments: // XtraReport public partial class ReportName : DevExpress.XtraReports.UI.XtraReport { // default parameterless constructor here public ReportName(string ClassName, string SubclassName, string StudentName) { InitializeComponent(); this.Parameters["ClassName"].Value = ClassName; this.Parameters["SubclassName"].Value = SubclassName; this.Parameters["StudentName"].Value = StudentName; } } // Form code private void btnPrint_Click(object sender, EventArgs e) { // Create a report instance. var report = new XtraReport1(cmbClass.SelectedText, cmbDivision.SelectedText, cmbStudent.SelectedText); report.RequestParameters = false; // Hide the Parameters UI from end-users. report.ShowPreview(); } Reference: Passing Parameter Values at Runtime Update: If SelectedText property for each textbox always have null value, you can use Text or SelectedItem property to get actual combo box value (similar issue here). private void btnPrint_Click(object sender, EventArgs e) { // Create a report instance. var report = new XtraReport1(); // Obtain a parameter, and set its value. report.Parameters["ClassName"].Value = cmbClass.Text; report.Parameters["SubclassName"].Value = cmbDivision.Text; report.Parameters["StudentName"].Value = cmbStudent.Text; report.RequestParameters = false; // Hide the Parameters UI from end-users. report.ShowPreview(); }
{ "pile_set_name": "StackExchange" }
Q: WPF DataGrid SelectionChanged and DataGridCheckBoxColumn I have a datagrid to which I bind some items. I only allow selecting rows (single item) on this grid. This grid has a DataGridCheckBoxColumn and a SelectionChanged event. The problem is that when the user presses a checkbox, it also selects the row (and triggers the SelectionChanged event). This is not the behaviour I would like. Is there a way I can either prevent the SelectionChanged event from triggering when pressing the checkbox OR detect if was the checkbox column that was pressed in the selectionchanged event? Thanks! A: What about adding a Mouse_Click event on DataGrid row and if it's original source is Checkbox then set e.handled = true otherwise go ahead.
{ "pile_set_name": "StackExchange" }
Q: On the number of monic polynomials Let $a,b,c,d\in\Bbb N$ with $c<b$. Let $N_+(a,b,c,d)$ be the number of monic polynomials $f\in \Bbb Z[x]$of degree $d$ with non-negative coefficients such that $$f(a)=b$$ $$f(0)=c$$ What is the value of $$\sum_{d=0}^tN_+(a,b,c,d)?$$ Are there sharp estimates? A: Not a complete answer, but note that by definition $N_+(a,b,c,d)$ is the number of ways of writing $b$ as a sum $b=\sum_{k=0}^d c_ka^k$ with non-negative $c_k$, and with $c_0=c$ and $c_d=1$. In particular it is certainly zero unless $a|(b-c)$ and $b-c\ge a^d$, in which case $N_+(a,b,c,d):=A\big(\frac{b-c-a^d}{a}\big)$, where $A(n)$ is the number of ways of writing $n$ as a sum $n=\sum_{k=0}^{d-2}x_k a^k$, with non-negative integers $x_k$, therefore corresponding to a g.f. $$\sum_{n=0}^\infty A(n)x^n=\frac{1}{(1-x)(1-x^a)(1-x^{a^2})\dots (1-x^{a^{d-2}}) }\ .$$
{ "pile_set_name": "StackExchange" }
Q: Is 5D good as a second body beside a 5D mark II? I own a 5D mark II and I do event photography. I have numbers of lenses in my collection and that's the reason I am looking for a second body, because changing lenses in event is a real pain. Do you think a 5D will be good as a second body beside 5D mark II? Or do you suggest a crop body? A: What are you looking for in your second body? Backup in case first body fails? Ability to use two cameras a once; One with a 135 f/2 one with a 50 f/1.4? Ability to use same lens on different camera but get a different look? Ability to use same lens on different camera but get the same look? You need and choice of a 2nd body may change depending on your answers. I think a 5D would be a great 2nd body, but so would a 7D or maybe even the cheapest available Canon (in your case) SLR. A: With the advent of the 5D mkIII and the subsequent price reduction on the mkII, I think I would be buying a 5D mkII instead. The biggest reason would be comparable output, though if you had the money, a mkIII and mkII combo would be better. Net effect, the original 5D is simply passed by and I wouldn't consider it. As an aside, I made a similar decision with the Pentax K-5. At first I was dual shooting with the K-5 and K20D, but the limitations in the K20D became way too obvious and I sold it off and bought a second K-5 instead. My sense is that you'll run into the same basic issue with the 5D options, so don't spend the money, you won't recover it.
{ "pile_set_name": "StackExchange" }
Q: Var value breaks on url format I have an url as a var, from a div with data: <div data="$firstID-$secondID-$url"> Then we split 'data': ids = ids.split('-'); var firstID = ids[0]; var secondID = ids[1]; var url = ids[2]; I open it with: window.open(url, 'opener'); That all works fine, except that the link contains all these characters, and stops at 'http://domain.com/word': http://domain.com/word-word/Product/show/name-name-name-name-(name-name)/case{id-id} How can I pass this insane link as var to the 'window.open' and still in tact? A: ids = ids.split('-'); //get rid of first 2 parts var urlParts = ids.slice(2, ids.length) // join the remaining parts back var url = urlParts.join('-')
{ "pile_set_name": "StackExchange" }
Q: How to get rid of nasality in singing Whenever I sing I can notice my voice is overly showing nasality and I hate it.I tried to keep my tongue flat rather than bulging to touch the top surface of the mouth. But nothing works exactly as I thought. So, please help me. Is there a surgery to help me? And Can I consult a doctor for this? If so, what type of doctor should I want to consult? Also, I am thinking of going for a vocal training. How many months would it take to learn all? I am including my voice here: http://vocaroo.com/i/s1OMk8S2QFjb http://vocaroo.com/i/s0QpArKbE0Xj Please examine and say. Although, I just sang unprofessionally. A: First, relax. At 14 you are much, much, much to young to be considering any type of surgery. Further, surgery for vocalists is pretty much contained to removing nodules that develop on the vocal chords from improper technique and abuse. There are several reasons why you sound "nasily": The music you listen to - your second sound clip featured you singing a Miley Cyrus song, and naturally, you imitate the people you listen to. Miley has fairly poor vocal technique and sings with a nasily, strident tone. If you want to make beautiful sounds you must listen to beautiful sounds. You are young - at 14 your voice has just begun to develop out of adolescence and it is a process that will take many years before your voice is fully mature. That's just the way our bodies work. Your voice is very young and you should not push it into places it shouldn't go. If you sing and get tired, take a rest, don't force it. Lack of training - lessons, knowledge, technique, and guidance from an experienced voice teacher (not a "vocal coach") will set you up for success and many years of beautiful singing. Too tense / Need more air - tenseness causes restriction of airflow and vocal cord resonance. If your vocal cords can't resonate fully (with a good supply of air!) your tone will suffer. Vocal training (taking lessons) is something that will be on-going and it will take years and years for your voice to develop. In an age where everyone expects everything to be immediate, if it's worth doing, isn't it worth taking the time to do it right?
{ "pile_set_name": "StackExchange" }
Q: Is it better to write Integer or just Int? We usually use Pascal in our school for programming, but in my personal life I prefer newer languages such as Python, C, or C++. All of these three languages use a data-type Int but Pascal uses Integer. It's actually the same but "Integer" is a little bit longer. Is writing something like this: Type int=integer; a "good" or "bad" habit? A: I think in Pascal, it is bad habit, regardless of what one thinks about C or Cpp or whatever else, and whether int is good in those languages. Redefining types in a language or in any way trying to create another language from Pascal or else is usually not a good idea. If you don't like Pascal, you should not use it, but if you redefine things, it will be harder and will take more time for Pascal programmers to understand or review your code. Having said this, there are languages (like for instance Ruby) that allow creating very nice DSLs (domain specific languages), which are somewhat similar to the root of your problem if I understand correctly. If designed correctly, DSLs can indeed be very nice for specific problem domains. A: bad habit int is already a function in most Pascals, so that would not be wise. Even if this were not the case, I'd reserve it for external interfacing, in case an externally declared "int" type, OS or C compiler differs from the pascal language "integer". And I also agree with Thilo. Adapt to the expected conventions, don't roll your own (even if based on major other languages). It will lead to a mixing of conventions which is worse than using either systematically.
{ "pile_set_name": "StackExchange" }
Q: How to join a collection in VBA Is there a way to join a collection in VBA? I can find join(array, ";"), but this function can not be applied to a collection. Thanks. A: Unfortunately, no, there's nothing built-in. You'll have to either convert the collection to an array (no built-in for that either, you'll have to loop through all the items) and then use Join(array, ";") or join your collection "the hard way" (set first flag, loop through items, add ";" if not first, clear first, add item). A: This is how to join it: Join(CollectionToArray(colData), ",") And the function: Public Function CollectionToArray(myCol As Collection) As Variant Dim result As Variant Dim cnt As Long ReDim result(myCol.Count - 1) For cnt = 0 To myCol.Count - 1 result(cnt) = myCol(cnt + 1) Next cnt CollectionToArray = result End Function
{ "pile_set_name": "StackExchange" }
Q: Not getting values from jQuery loop I'm trying to get the text and the link of an element on a website using Nightmare.js and jquery. I'm looping through every element with the same class, I get no error, but the text and link are empty. Here is what I tried: nightmare .goto("https://myanimelist.net/anime/season") .wait(2000) .evaluate(() => { let links = []; $('.link-title').each(() => { item = { "title": $(this).text(), "link": $(this).attr("href") }; links.push(item); }); return links; }) .end() .then(result => { console.log(result); }) .catch(function (error) { console.error('Failed', error); }); The output in the console looks like this: [ { title: '' }, { title: '' }, { title: '' }, ... 99 more items ] A: $('.link-title').each(() => { item = { "title": $(this).text(), "link": $(this).attr("href") }; links.push(item); }); Inside each() method, use normal function instead. Arrow functions make this not work as you expected
{ "pile_set_name": "StackExchange" }
Q: How to use stream of change events in mat-select? I am trying to use the optionSelectionChanges observable property in Angular Materials mat-select. It gives a combined stream of all of the child options' change events. I want to get the previous value when a user changes the option to update validators on it. I don't know how to handle observable streams from the template to the component or if this property is best to do it? html: <mat-form-field> <mat-select (optionSelectionChanges)='getStream' formControlName='value1'> <mat-option value='1'>Option1</mat-option> <mat-option value='2'>Option2</mat-option> </mat-select> </mat-form-field> Component: import { Component, OnInit } from '@angular/core'; import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms'; import { MatOptionSelectionChange } from '@angular/material'; @Component({ selector: 'test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { form: FormGroup; getStream: Observable<MatOptionSelectionChange>; constructor(private _fb: FormBuilder) { } ngOnInit() { this.getStream.subscribe(res => {console.log(res)}) this.form = this._fb.group({ 'value1': [null, Validators.compose([])] }); } } Thanks A: optionSelectionChanges is a property not an Output. It is meant to be used from your script code - I don't think you can use it from the template. Here's an example: <mat-select #select="matSelect" formControlName='value1'> <mat-option value='1'>Option1</mat-option> <mat-option value='2'>Option2</mat-option> </mat-select> import { AfterViewInit, Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { MatSelect} from '@angular/material/select'; @Component({ selector: 'test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements AfterViewInit, OnInit { @ViewChild('select') select: MatSelect; form: FormGroup; constructor(private _fb: FormBuilder) { } ngOnInit() { this.form = this._fb.group({ 'value1': [null, Validators.compose([])] }); } ngAfterViewInit() { this.select.optionSelectionChanges.subscribe(res => {console.log(res)}); } }
{ "pile_set_name": "StackExchange" }
Q: How to separate warning message from stdout/result in powershell redirection? I'm trying to write a simple test script in PowerShell to separate warning message from stdout/result in order to get two separate text files, one for warnings and one for standard results in PowerShell Redirection. Here is my simple output.ps1 script: Write-Output "This is result" Write-Warning "This is warning" I'm trying to run output.ps1 using a .bat file using below command: PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt pause But my problem is warning.txt is completely empty, while both – warning and result – are written to results.txt. This is result WARNING: This is warning What I am missing in PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt to separate warnings and errors into two files? Edit: Modified to see standard error, 2> is working. Even if I redirect standard error to separate file using 2>error.txt by using PowerShell.exe -Command "& '%~dp0output.ps1'" 2>error.txt 3>warning.txt >results.txt and if I modify output.ps1 to generate an error in the following manner Write-Output "This is result" Write-Warning "This is warning"" This will generate error because this is not a ps command. it will generate the error as expected to a file error.txt with results.txt where results.txt is the combination of warning and stdout/result. warning.txt is still empty. I still can't figure out why PowerShell warnings are not filtered and redirected properly to a separate file. error.txt: this : The term 'this' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\Dell\Desktop\output.ps1:3 char:1 + This will generate error because this is not a ps command. + ~~~~ + CategoryInfo : ObjectNotFound: (this:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException results.txt: This is result WARNING: This is warning I'm using Windows 10 and PowerShell Version 5.1.14393.1358. A: Real problem, in the below example, is, When you use powershell.exe to execute a ps1 file verbose, warning, and debug streams are merged into STDOUT) -Source. (---resulting a blank warning.txt) PowerShell.exe -Command "& '%~dp0output.ps1'" 3>warning.txt >results.txt To circumvent this limitation in powershell.exe, there is a workaround for above example using extra intermediate ps1 file. You can use two powershell files and a bat file and get three separate files for error/warning/results. (2>error.txt 3>warning.txt >results.txt) Have the same content for output.ps1 with below content. Write-Output "This is result" Write-Warning "This is warning"" This will generate error because this is not a ps command. Then create another powershell file. (I will call it newout.ps1) and newout.ps1 can run output.ps1 with below content. .\output.ps1 2>error.txt 3>warning.txt >results.txt Finally your bat file can run newout.ps11 instead of output.ps1 in this manner. PowerShell.exe -Command "& '%~dp0newout.ps1'" Which gives you three separate files with desired results.
{ "pile_set_name": "StackExchange" }
Q: GWT set caret position on content editable div I'm writing a web based code editor, where every line is a content editable div. I wrote a native method to set caret position on a given index, but it works only in chrome. opera and firefox always sets caret on a beggining of a line. public native void setCursorPos(int index) /*-{ //console.log(index); var that = [email protected]::getElement()(); var position = index; var el = that; var treeWalker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, function(el) { return NodeFilter.FILTER_ACCEPT; }, false); while (treeWalker.nextNode()) { if (position - treeWalker.currentNode.length <= 0) { var range = document.createRange(); var sel = window.getSelection(); console.log(position); range.setStart(treeWalker.currentNode, position); range.setEnd(treeWalker.currentNode, position); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.focus(); return; } else { position = position - treeWalker.currentNode.length; } } while testing a code i was using this http://jsbin.com/EcETajo/5/edit and it works in chrome, ff and opera. is the function wrong or something on the gwt generated code changes caret position ? EDIT: im using treewalker because i want to handle text hightlighting by wrapping text in span nodes in future EDIT2: ok, ive found a problem by myself. var range = document.createRange(); var sel = window.getSelection(); those lines were wrong. js code in gwt is in iframe, so to access my html elements i had to use something like this var range = $doc.createRange(); var sel = $doc.getSelection(); wher $doc is a variable set by gwt A: proper use of document and window objects in gwt native method is by using $wnd and $doc that are set by gwt framework
{ "pile_set_name": "StackExchange" }
Q: Trying to calculate the difference between two dates I'm trying to calculate the duration between when an item is created and the last time it was modified. I'm not sure what's wrong with my formula though because the equation is saying there are 41XXX days when it should be 3. This doesn't happen for all items though, only certain ones. =IF(DATEDIF(Created,Modified,"d")>1,DATEDIF(Created,Modified,"d")&" days ",DATEDIF(Created,Modified,"d")&" day ")&TEXT(Modified-Created,"hh:mm:ss") A: SharePoint seems confused as it is displaying the numerical (integer) representation of 8/18/2013 (US) which is 41504. Your formula displays a result directly in Excel, although the days difference is 2, not the 3 that it displays. You might simplify it with: =TEXT(Modified-Created,"d ""day(s)"" hh:mm:ss") which in Excel displays 2 day(s) 17:34:00 I am not able to test it from SharePoint though. I suppose if you really want to display either day or days then you might try: =TEXT(Modified-Created,"d ""day"""&IF(VALUE(TEXT(Modified-Created,"d"))>1,"""s""","")&" hh:mm:ss") This could possibly be simplified (if SP can cope) to: =TEXT(Modified-Created,"d ""day"""&IF(Modified-Created>1,"""s""","")&" hh:mm:ss")
{ "pile_set_name": "StackExchange" }
Q: Android Progress dialog within listview My app is designed as follows: Main Activity uses action bars First tab is a fragment that is split into 3 sections | Linear Layout containing List view | |Linear Layout containing List View | | Linear Layout containing media controls and image view| I have two AsyncTasks within this activity, one that fills the centre list view, the other that starts with the media controls to fill the image view (album art). Both of these are working well. The List view AsyncTask throws a progress dialog spinning wheel. This is coming up in the centre of the screen. I understand that I can put this spinner into the top right of the application. But can i place it either in the top right of the list views linear layout, or centred at the back of the linear layout? That way it would be unobtrusive yet obvious what the progress bar applied to? Thanks in advance A: I understand that I can put this spinner into the top right of the application. But can i place it either in the top right of the list views linear layout, or centred at the back of the linear layout? If you can calculate the position of the view, you would probably be able to position the ProgressDialog where you want(for example see this question I answered Change position of progressbar in code). Also, keep in mind, that this could be very counter intuitive for the user who would see the screen for the dialog and the dialog placed at some weird position(he may not make the correlation between the position of the ProgressDialog and the view for which the data is loaded). Another option could be to modify the current layout for the ListView part to add on top an initial gone FrameLayout(which will cover the entire ListView) with a background that simulates the background for a screen with a Dialog(this FrameLayout will contain a ProgressBar placed where you want). This FrameLayout would be made visible when the AsyncTask kicks in(it may be wise to block the touch events for the underlining ListView). This way the user can still do stuff in your app and it has a clear indication for the View that is loading its data. Of course this will work well if it's possible for the user to work with the other data independently from the loading ListView.
{ "pile_set_name": "StackExchange" }
Q: iPad simulator doesn't do the emails? I am trying to test out email sending from my app on iPad simulator (using mailto:... URLs...) but it doesn't seem to work. Any way how I can test it? Or only on the "real thing"? A: As far as I can tell you can only do it from a device. I think this is because the simulator does not come with the mail app installed and there are no settings to configure mail accounts which is what the device looks at when determining if it can send an e-mail. The strange thing though is that you always get a "success" when sending e-mail in the simulator even though the mail never really gets sent. A: Okay, as I figured out if you try to send email via mailto:... openURL on iPad this doesn't seem to work in simulator. However, using MessageUI API actually does work..
{ "pile_set_name": "StackExchange" }
Q: Finite-dimensional argument for Morse-Smale pairs? Using the Sard-Smale theorem, it is relatively easy to show that Morse-Smale pairs on a manifold $M$ (i.e. pairs $(f,g)$ where $g$ is a metric on $M$, $f$ is a Morse function on $M$, and the stable/unstable disks corresponding to th flow of $-\nabla f$ intersect transversely) are dense in the appropriate topology. However, this argument requires the use of Banach manifolds. For the sake of a more accessible exposition, I was hoping to find an argument that uses only finite-dimensional methods, such as Thom transversality. My thought was the following: Perhaps if we fix the metric $g$, we can show that functions $f$ such that $(f,g)$ is Morse-Smale are dense. (Just looking for a function seems to be more in the realm of classical applications of Thom transversality than also looking for a metric.) The Sard-Smale result certainly guarantees that this will be true for a generic $g$, but will it hold for any $g$? It would certainly seem very strange to me if there were a metric $g$ not admitting any such function $f$. A: The Sard-Smale result certainly guarantees that this will be true for a generic , but will it hold for any ? If $g$ is fixed, you can certainly use the Sard-Smale theorem to prove the existence of a Morse function $f$ so that the pair $(f,g)$ is Morse-Smale. And yes, there's also a proof with less heavy machinery, see for instance Theorem 6.6 in the book "Lectures on Morse Homology" by Banyaga and Hurtubise.
{ "pile_set_name": "StackExchange" }
Q: More precedence/specificity to CSS class in LESS I've a LESS code like: .block__element { background: red; &--modifier { background: yellow; } } I want more specificity to .block__element--modifier such as: .block__element.block__element--modifier { background: yellow: } So that it can overrides some other styles. I can achieve it by: .block__element { background: red; &--modifier.block__element { background: yellow; } } I want to know is there any easy way? A: .block__element { background: red; &&--modifier { background: yellow; } } link
{ "pile_set_name": "StackExchange" }
Q: Does strict order-preservation of powerset curtail the candidates for violation of CH? Thus, let $\mathrm{OPP}$ be the axiom that $|A|\lt|B| \Rightarrow |2^A|\lt|2^B|$ for any sets $A$ and $B$; and, for any ordinal $\alpha$, let $\mathrm{CH}_\alpha$ be the hypothesis that $\aleph_\alpha=\frak c$ (so that $\mathrm{CH}_1=\mathrm{CH}$) . Define $S$ to be the set of those ordinals $\alpha\in\frak c$ such that $\mathrm{CH}_\alpha$ does not provably (within $\mathrm{ZFC}$) violate $\mathrm{ZFC}$ (for example, it is known that $\omega\backslash${$0$}$\subseteq S$ and $\omega \notin S$); and let $S'$ be the set of those $\alpha\in\frak c$ such that $\mathrm{CH}_\alpha$ does not provably (within $\mathrm{ZFC}$) violate $\mathrm{ZFC}$ $\&$ $\mathrm{OPP}$. Clearly $S'\subseteq S$. But is $S'= S$ ? Or are any elements of $S$ known to be not in $S'$ ? My guess is that $\mathrm{OPP}$ can't restrict the possibilities for violations of $\mathrm{CH}$ because the sets it talks about in the consequent---especially $2^B$--- are too big to be relevant; but I'm not sure of my footing here. A: First, let me remark that the particular way that you've posed the question has several problematic issues of formalization. One issue, noted by François, Andres and Andreas, is that it doesn't make sense to speak about proving an assertion with an ordinal parameter (one would instead want to speak of definitions of particular ordinals). Another issue is that for all we know, we may be living in a universe with ZFC + $\neg\text{Con}(\text{ZFC})$, and in this universe everything is provable, so even if we are able to resolve the first issue nevertheless the sets $S$ and $S'$ will be empty, since everything is provable. So let me propose a more semantic, alternative version of the question, which to my of thinking gets at the issue in which I believe you are interested. Question. If $\alpha$ is an ordinal and the continuum $2^{\aleph_0}$ can be $\aleph_\alpha$ in a forcing extension of the universe, then can the continuum be $\aleph_\alpha$ in a forcing extension of the universe in which also the OPP holds? The answer is yes, and so in this sense the OPP imposes no additional constraints on the value of the continuum. In this question and in the theorem below, I am speaking about possibly proper class forcing, and this is required, since if the OPP fails unboundedly often, it will require proper class forcing to force OPP again. Theorem. If the universe $V$ satisifes ZFC, then for any ordinal $\alpha$, the following are equivalent: There is a forcing extension in which $2^\omega=\aleph_\alpha$. There is a forcing extension in which $2^\omega=\aleph_\alpha$ and the OPP holds. Either $\alpha$ is a successor ordinal or $\alpha$ has uncountable cofinality. Proof. Clearly 2 implies 1, and 1 implies 3. Suppose 3 holds, and I argue for 2. Fix any ordinal $\alpha$ as in $3$. First, we may simply force the GCH by the canonical forcing of the GCH. This forcing (which may be a proper class), is countably closed and hence preserves the property of having uncountable cofinality. So $3$ still holds about $\alpha$ in the extension with GCH. We may now simply apply Easton's theorem, using an Easton function $E$ that takes $\aleph_0$ to the current $\aleph_\alpha$, and more generally which takes $\aleph_\beta$ to $\aleph_{\alpha+\beta+1}$. (But any strictly increasing Easton function will do, and there are many variations.) Note that $\alpha+\beta=\beta$ once $\alpha\cdot\omega\leq\beta$, and so this pattern is eventually the GCH pattern. By Easton's theorem, there is a further forcing extension in which $2^{\aleph_0}=\aleph_\alpha$ and the continuum function is given by $E$, which is strictly increasing, so the OPP holds. QED In particular, for any ordinal $\alpha$ that you care to define, then you can provably force the continuum to become $\aleph_\alpha$ if and only if you can do so while also ensuring the OPP. Notice that in the proof of the theorem, the value of $\aleph_\alpha$ may have changed, during the forcing of the GCH, since this will collapse cardinals if the GCH did not already hold. So there is another version of the question, which is about cardinals, rather than about ordinals. If we start with the GCH, then a similar conclusion can be made. Theorem. If $V$ is a model of ZFC+GCH, then for any cardinal $\delta$ the following are equivalent: There is a forcing extension $V[G]$ in which the continuum is $\delta$. There is a forcing extension $V[G]$ in which the continuum is $\delta$ and the OPP holds. The cardinal $\delta$ has uncountable cofinality. The proof is essentially the same as above. The nontrivial part is 3 implies 2, which can be achieved via Easton's theorem by using a strictly increasing Easton function $E$ with the property that $E(\aleph_0)=\aleph_\alpha$. There are many choices of such $E$, such as $E(\aleph_\beta)=\aleph_{\alpha+\beta+1}$, as above. Any such $E$ will ensure the right value for $2^{\aleph_0}$ and, because it is strictly increasing, will also achieve the OPP. In this case, since we started with the GCH, one requires only set-sized forcing. By the way, there seems to be alternative terminology to refer to what you call the OPP. For example, in my paper, "Is the dream solution of the continuum hypothesis attainable?", I refer to the power set size axiom, denoted, PSA, and this is the same as what you call OPP. This axiom also appears in the MO question on reasonable-sounding statements that are independent of ZFC.
{ "pile_set_name": "StackExchange" }
Q: Mouse cursor invisible after 15.04 update My mouse pointer became invisible after some updates after I upgraded to 15.04 from 14.10. In all standard settings the mouse pointer is activated (system settings, dconf...) I also tried different cursor icons with no success. The pointer is sometimes visible after I shut down and reboot the system. But only sometimes and I couldn't figure out a patterns why it sometimes shows up. I found the following solution which did not work gsettings set org.gnome.settings-daemon.plugins.cursor active false Any help appreciated! thanks! A: This bug is still around for a Xubuntu 16.04 system using lightdm. A fix for Xubuntu, and possibly other DE's, as described on the Xubuntu 16.04 Release Post is to bring the cursor back with Ctrl+Alt+F1 followed by Ctrl+Alt+F7 . This worked for me, where none of the other solutions had without reloading everything and closing every page. A: I have the same problem after upgrading to 15.04 from 14.10. Sometimes the mouse pointer will appear, this happens approx 1 in 5 computer switch on times. I found a way to get round this as suggested above. (note: this will hard-kill any running processes). sudo service lightdm restart This does have to be issued after every start up . Does anybody know of a more long-term fix? I have now found a long-term fix. Switch to gdm instead. sudo apt-get install gdm after trying several reboots this fix seems to work every time. I don't know if lightdm gives any advantages over gdm, but to me seeing the cursor is a big advantage of GDM over lightdm. A: A dirty hack I do (which surprisingly works for me) is to open terminal by pressing Ctrl+Alt+T and then type ls then the mouse shows in 1-2 seconds. That said, the normal way that works is to restart the mouse driver. This solution also works when the mouse pointer is misbehaving (like flickering randomly out of control). You restart the mouse driver like: sudo modprobe -r psmouse # disable the driver sudo modprobe psmouse # enable the mouse driver
{ "pile_set_name": "StackExchange" }
Q: Kernel and image of $\varphi:GL_2(F) \rightarrow S_4$ I'm working on the following question from Artin's Algebra: Let $F=\mathbb{F}_3$. There are four one-dimensional subspaces of the space of column vectors $F^2$.List them. Left multiplication by an invertible matrix permutes these subspaces. Prove that this operation defines a homomorphism $\varphi:GL_2(F) \rightarrow S_4$. Determine the kernel and image of this homomorphism. Am I on the right track? Here's what I found: The four one dimensional subspaces are scalars of $(0\;1)^t$, $(1\;0)^t$, $(1\;1)^t$, $(1\;2)^t$, so let $S$ be the set of those 4 vectors. There exists a bijection between operators of $GL_2(F)$ on $S$ and permutation representations $GL_2(F) \rightarrow S_4$, which is stated in the book. Since we are given such an operation, there exists a homomorphism $\varphi:GL_2(F) \rightarrow S_4$. I count 30 elements in $GL_2(F)$, half of which are scalar multiples of others, so there's a maximum of $15$ elements in the image. I started a proof by exhaustion of the 15 matrices for each of the four subspaces, but this seems excessive. I'm guessing that the kernel is scalar matrices, so the image is isomorphic to $GL_2(F)/Z_2(F)$ A: First of all, note that there are $48$ elements in $\operatorname{GL}_2(F)$. After all, we can construct any invertible matrix by first choosing the first column vector, which can be any nonzero vector $v_1\in F$, and then choosing the second column vector, which can be any vector that is linearly independent of $v_1$, i.e. any vector not on the line spanned by $v_1$. This yields a total of $8\times6$ invertible matrices. Now as you already note, if two matrices in $\operatorname{GL}_2(F)$ differ by a scalar multiple, then their action on the set of lines is the same. What this means is that all scalar matrices are in the kernel of $\varphi$; these matrices act trivially on the set of lines. Are there any other matrices that act trivially on the set of lines? (Your guess is right). What does this tell you about (the size of) the kernel? And then what does this tell you about (the size of) the image?
{ "pile_set_name": "StackExchange" }
Q: Can a java exploit circumvent browser plug in permission? Since Java 7 is vulnerable i am asking myself if the vulnerability is circumventing the plug in permission of any given browser. For example: http://www.youtube.com/watch?v=pn1Rbnidhl8 here you see an exploit in which the user needs to give the plug in permissions to run. Does the current exploit act without being recognized at all? PS: Since i am using NoScript i feel pretty safe to not get affected. A: Yes. Java WebStart runs at Medium Integrity. In order to protect yourself from this exploit, you should immediately disable Java in all of your browsers and wait for a patch to be released. You should also make sure that any anti-virus software you have is fully up-to-date. This will reduce, but not eliminate the risk that you are successfully exploited using this vulnerability in Java.
{ "pile_set_name": "StackExchange" }
Q: State Design Pattern - ASP .NET Webform I'm thinking of implementing the state design pattern on an ASP .NET Webform. The state would be determined by the query string passed to the page. Based on the state of the page, any action would call the method on the concrete implementation. What I am trying to achieve is a page that can handle any number of different implementations of the same general functionality. My questions are: Will this work? Does this sound like the right approach? A: I think what you are suggesting would be a sound approach. The only advice I can really offer is to not get hung up on implementing the State Pattern perfectly. I think it would be perfectly acceptable to just have a switch which calls a method based on a query string value.
{ "pile_set_name": "StackExchange" }
Q: Dynamic sql query(string template) Let's say I have a working function that prints first record from DataBase: class DataBase: def db_firstrecord(self): self.execute("SELECT * FROM Flat") row = self.fetchall() row = row[0] print(row) def main(): DB.DataBase.db_firstrecord(cur) I have recently found that there are several ways of making dynamic sql queries(sql string templates). And I want to use my initial function with different table names. How can I implement it in clean and safety manner ? I want something like this: class DataBase: def db_firstrecord(self,`Table_name`): self.execute("SELECT * FROM `Table_name`") row = self.fetchall() row = row[0] print(row) def main(): DB.DataBase.db_firstrecord(cur,`Table_name`) A: Use a whitelist of valid table names. class Database: table_names = {'table1', 'table2', ...} def db_firstrecord(self, table_name): if table_name not in table_names: raise ValueError self.execute(f"SELECT * FROM `{table_name}` LIMIT 1") row = self.fetch() return row Note that you can't put backticks in around the Python variable in the parameter list. It needs to be in the SQL string. And there's no reason to fetch all rows if you just want the first. Tell the query to return only one row, and just use fetch() rather than fetchall().
{ "pile_set_name": "StackExchange" }
Q: volume rendering: maintain interactivity I try to implement Raycasting volume rendering using OpenGL, GLSL and C++. As we all know, it is computationally intensive and it is very hard to get good interactivity such as move the viewpoint and zoom in and out. We can use an adaptive scheme for modifying parameters to achieve reactivity during interaction. One parameter that we can modify is Image Sample Distance: the distance in x and y direction on the image plane between neighboring rays. When I do raycasting volume rendering, in the first I draw a cube and then render its back face(exit points) and its front face(entry points), then I can do the raycasting pass. My question is: how to decrease the Image Sample Distance? A: My question is: how to decrease the Image Sample Distance? Ideally by downsampling your original volume data. If your sampling distance is farther than your voxel distance you'll get nasty rendering artifacts. As a general rule your sampling distance should exactly match your voxel distance along the ray. The application I'm currently programming does deal with high resolution medical images as well. May I ask what resolution your volumes have? The main problem you'll run into is to fit the volume into your GPUs fast memory. If your data exceeds those limits, then the GPU must swap in data from system memory which is slow. This makes easily a difference between interactive rates and a very slow slide show.
{ "pile_set_name": "StackExchange" }
Q: multiple if stamens inside for loop I have a for loop like so: for(var i = 0; i < data.reviews.length; i++){ if(data.reviews[i].rating.overall > 80){ console.log(i); if(i > 1){ console.log('more than 80 and more than 1'); } else{ console.log('more than 80 and only 1'); } } } and a reviews array as follow: "reviews":[ { "rating":{"overall": 91} }, { "rating":{"overall": 77} }, { "rating":{"overall": 94} }, { "rating":{"overall": 74} } ], I have some conditions that I need to meet to append some HTML: 1) if the reviews overall is more than 80 and there is more than one reviews (append slide show) 2) if the reviews overall is more than 80 and there is only one review (append plain text, jus tone review without slideshow) Based on the reviews data provided I should get console.log('more than 80 and more than 1'); printed only twice instead in my console I get: more than 80 and only 1 more than 80 and only 1 more than 80 and more than 1 A: If I'm understanding your problem correctly, then you simply need to change the inner if statement to check how many reviews there are - not the counter for iterating them... var data = { "reviews": [ { "rating":{"overall": 91} }, { "rating":{"overall": 77} }, { "rating":{"overall": 94} }, { "rating":{"overall": 74} } ] }; for (var i = 0, l = data.reviews.length; i < l; i++) { if (data.reviews[i].rating.overall > 80) { if (l > 1) { // check the overall count, instead of the current index document.write('more than 80 and more than 1<br />'); } else { document.write('more than 80 and only 1<br />'); } } }
{ "pile_set_name": "StackExchange" }
Q: Emulating RHEL for apt get I am constantly requiring the use of multiple packages for my work, but alas my work PC doesn't have an internet connection. Hence, I am always stuck on downloading the package on a separate PC which has Ubuntu. I was wondering if it was possible to emulate my OS as RHEL6 and download the required packages to an rpm file via apt-get or something since most common answers to my problems seem to be answered in an apt-get install format. A: You can use Docker to spin up a CentOS 6 container. Then use yumdownloader to download packages and their dependency RPMs.
{ "pile_set_name": "StackExchange" }
Q: Download file with pause and resume button? I've googled much and I don't find my solution about two pause and resume button. I use from this code and this . But I don't know how implement pause and resume capability and set what to my pause and resume button onclick event: pausebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopdownload(); AND resumedownload(); <------ } }); Thanks in advance. A: To stop download call downloadTask.cancel(false); To support resuming download you can use the code from Resume http file download in java: HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){ File file=new File(DESTINATION_PATH); if(file.exists()){ downloaded = (int) file.length(); connection.setRequestProperty("Range", "bytes="+(file.length())+"-"); } }else{ connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); } connection.setDoInput(true); connection.setDoOutput(true); progressBar.setMax(connection.getContentLength()); in = new BufferedInputStream(connection.getInputStream()); fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true); bout = new BufferedOutputStream(fos, 1024); byte[] data = new byte[1024]; int x = 0; while ((x = in.read(data, 0, 1024)) >= 0) { bout.write(data, 0, x); downloaded += x; progressBar.setProgress(downloaded); }
{ "pile_set_name": "StackExchange" }
Q: Can casperjs/phantom.js can run on Amazon EC2 server? I've managed to build and run scripts on my computer. What if I want it to work on a server? I'd like to be able to send requests to a server and process them using CasperJS. I imagine that on a regular web server, such thing is possible. Is such thing possible on Amazon's EC2? Is there any other web server hosting solutions that allow such thing? A: Today I ran casperjs (and phantomjs) on a fresh Amazon EC2 instance, running Ubuntu 12.04. Setup was pretty minimal: sudo apt-get update sudo apt-get install npm sudo npm install -g phantomjs sudo npm install -g casperjs sudo apt-get install fontconfig Worked like a charm. You don't need to setup a web server. You just need the command line.
{ "pile_set_name": "StackExchange" }
Q: How to ignore certain characters while doing diff in google-diff-match-patch? I'm using google-diff-match-patch to compare plain text in natural languages. How can I make google-diff-match-patch to ignore certain characters? (Some tiny differences which I don't care.) For example, given text1: give me a cup of bean-milk. Thanks. and text2: please give mom a cup of bean milk! Thank you. (Note that there are two space characters before 'Thank you'.) google-diff-match-patch outputs something like this: [please] give m(e)[om] a cup of bean(-)[ ]milk(.)[!] Thank(s)[ you]. It seems that google-diff-match-patch only ignores different numbers of white spaces. How can I tell google-diff-match-patch to also ignore characters like [-.!]? The expect result would be [please] give m(e)[om] a cup of bean-milk. Thank(s)[ you]. Thanks. A: google-diff-match-patch can output a list of tuples The first element specifies if it is an insertion (1), a deletion (-1) or an equality (0). The second element specifies the affected text. For example: diff_main("Good dog", "Bad dog") => [(-1, "Goo"), (1, "Ba"), (0, "d dog")] Thus we just need to filter this list. Example code in Python: Ignored_marks = re.compile('[ ,\.;:!\'"?-]+$') def unmark_minor_diffs(diffs): #diffs are list of tuples produced by google-diff-match-patch cooked_diffs = [] for (op, data) in diffs: if not Ignored_marks.match(data): cooked_diffs.append((op, data)) else: if op in (0, -1): cooked_diffs.append((0, data)) return cooked_diffs
{ "pile_set_name": "StackExchange" }
Q: Recording in an underground parking lot There is a shoot happening in an underground packing lot with a low cement ceiling and a cement floor as well as a low end hum that will be constant in the background. The genre is a crime drama where there is a lot of yelling and screaming. My fear as I have encountered this before is distortion and muddiness of the dialogue due to the acoustic environment. I have recommended a pad of about -15 to -20dB with a hyper-cardiod mic to record the close and medium shots with radio mics for the wide shots. What other recommendations might you have in relation to such a location? A: Eek... I think you've recommended everything thats possible. I would ask for a few takes of wild tracks of wide shots and grab an impulse response recording of the location incase you need to get the actors in for ADR. Other than that good luck! :)
{ "pile_set_name": "StackExchange" }
Q: High Speed Python Web Scraper Optimised I needed a lot of data for a tensorflow project so I made a web scraper to get all of the text and links off of websites then to repeat the process at all of those links. I left it on overnight and it did not get much done, so I spent the day optimizing it. I can't find any ways to optimize it more (If anyone knows a way I would like to hear it.) I used it on CNN and now I have a 9 gig text file. BTW: I used faster_than_requests and selectolax because they are faster then urllib3 and bs4 and you should check them out import cython # helps speed up code from selectolax.parser import HTMLParser #bs4 but faster import faster_than_requests #urllib but faster import _pickle as pickle #saving code from colorama import init #just makes error messages stand out from colorama import Fore, Back, Style init() #colorama thing #cdef is a cython thing, helping speed up code cdef int i = 0 cdef list urls cdef list text cdef set visits #is a set for efficiency cdef str mainsite = "https://www.cnn.com" #The main site keeps the scraper #from straying too far from its original site. cdef str source parsing = True try: with open('visits.pickle', 'rb') as f: visload = pickle.load(f) visits = visload[1] i = visload[0] except Exception as e: print(Back.RED + "Error loading Visits: " + str(e)) visits = set('') i = 0 try: with open('txt.pickle', 'rb') as f: txt = pickle.load(f) except Exception as e: print(Back.RED + "Error loading txt: " + str(e)) txt = [] try: with open('links.pickle', 'rb') as f: urls = pickle.load(f) except Exception as e: print(Back.RED + "Error loading urls: " + str(e)) urls = ["https://www.cnn.com"] while parsing: try: if urls[0][0] == "/": #checks to see if it can go # to the site directly or it needs to add #the main site to the front source = faster_than_requests.get2str(mainsite + urls[0]) dom = HTMLParser(source) print(Back.BLACK + mainsite + urls[0]) else: source = faster_than_requests.get2str(urls[0]) dom = HTMLParser(source) print(Back.BLACK + urls[0]) for tag in dom.tags('p'): txt.append(str(dom.text())) #finds text and saves it for tag in dom.tags('a'): attrs = tag.attributes if 'href' in attrs: urls.append(attrs['href']) #finds links and saves them except: print(Back.RED + f"Error: {urls[0]}") # it will through up an error # if it tries to go to a sub-page # of another site, but this is # an intended feature visits.add(urls[0]) #visits keeps track of visites web pages i = i + 1 clean = True #clean make shure that it does not repeat a webpage. while clean: if urls[0] in visits: del(urls[0]) else: clean = False print(Back.BLACK + f"urls:{len(urls)}, i:{i}, text lang:{len(txt)}") if i % 10000 == 0: #Save every 10000 webpages with open('txt.pickle', 'wb') as f: pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL) with open('links.pickle', 'wb') as f: pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL) with open('visits.pickle', 'wb') as f: pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL) if 0 == len(urls): parsing = False print(txt) with open('txt.pickle', 'wb') as f: pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL) with open('links.pickle', 'wb') as f: pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL) with open('visits.pickle', 'wb') as f: pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL) A: If you want absolute performance You could avoid printing anything at all. Since that can be slow in some cases. If you absolutly need to know at least what happened you could try flushing at the end of the process. I know with python is delicated, but you could try visiting multiple pages at the same time? Threads or the equivalent in python
{ "pile_set_name": "StackExchange" }
Q: How can I set time for insertAfter How can I set time for insertAfter , more details : $(z).find(".post--"+a).insertAfter(".post:last"); for example when i use .slideDown(time) it will slide with the time I set now i want to know how can do that for insertAfter A: As I suggested in the comment, you can try $(z).find(".post--"+a).hide().insertAfter(".post:last").slideDown(500);
{ "pile_set_name": "StackExchange" }
Q: How can I do in javacard a power of 2 with a floating exponent? I need to do a power of 2 with a floating exponent in Java Card. As you probably know, float type is forbidden in the Java Card specification. I need to do an operation like this: short n = 2 ^ (float) (31/4) The expected n is n = 215. Somebody knows how can I calculate this? A: To expand on my comment, and give a partial answer, consider calculating 2^(a/b) as (2^a)^(1/b). Raising 2 to an integer power is easy: 1 << a. Depending on the numbers involved, you may need some form of extended precision, such as manually using two int variables. That leaves computing the bth root of an integer. If b is a power of two, it can be done by repeated square root operations, using e.g. Newton-Raphson for each square root. If b can be any positive integer, you need more sophisticated methods. One possible approach to the bth root part of the problem is a binary search. The root must be between 1 and 2^ceil(a/2). A: As Patricia said, it makes sense to calculate (2^a)^(1/b). From your comments I see that b is always 4. Then it becomes a lot simpler. Because you always have a power of 2, and always need the quad root, you can divide the number a up in portions of 4 (i.e. 2^4) and a rest. There can only be 4 values for the rest, and for that, you can use a lookup table. I would code that as fixed point value, e.g. scaled by 2^16. So, in fact, if quotient = a // 4 and remainder = a % 4 you calculate: 2^(quotient) * (2^(remainder / 4) * 65536) // 65536, where // denotes integer division and / denotes float division (I know this is not valid Java, but I use different operators to show the difference). This should be much faster and easier than using Newton-Raphson to calculate a square root repeatedly. I don't know Java very well, so please excuse if the syntax is not correct, but it should look more or less like this: public class MyClass { public static int[] factors; public static void initfactors() { factors = new int[4]; factors[0] = 65536; // 2^(0/4) * 65536 factors[1] = 77936; // 2^(1/4) * 65536 factors[2] = 92682; // 2^(2/4) * 65536 factors[3] = 110218; // 2^(3/4) * 65536 } // Returns 2^(a/4) as integer public static int calc(int a) { int quotient = a / 4; int remainder = a % 4; // a == 4 * quotient + remainder int factor = factors[remainder]; // calculate 2^(a/4) * (2^(remainder/4) * 65536) / 65536 return ((1 << quotient) * factor) >> 16; } The factors can be found like this: you simply use a calculator to calculate 2^0, 2^0.25, 2^0.5, 2^0.75 and multiply the results by 65536 (2^16), preferrably rounding up so the shift does not result in a number slightly below the value you want. Usage example: public static void main(String[] args) { initfactors(); int result = calc(31); System.out.println(result); } Your example: quotient: 31 / 4 --> 7 remainder: 31 % 4 --> 3 factor: factors[3] --> 110218 result: ((1 << 7) * 110218) >> 16 --> 128 * 110218 / 65536 --> 215.
{ "pile_set_name": "StackExchange" }
Q: How/When does a function returned from Observable.create execute (rxjs) I have the following code from 'https://chrisnoring.gitbooks.io/rxjs-5-ultimate/content/observable-anatomy.html': const Observable = require('rxjs/Observable').Observable; require('rxjs/add/observable/of'); require('rxjs/add/operator/map'); let stream = Observable.create((observer) => { let i = 0; let id = setInterval(() => { observer.next(i++); }, 500); return function () { // Line 11 clearInterval(id); }; }) let subscription = stream.subscribe((value) => { console.log('Value: ', value); }) setTimeout(() => { subscription.unsubscribe(); }, 1500); The output of this program is below. The program terminates automatically after 'Value: 1' output. > node index.js Value: 0 Value: 1 Since the statement is returning a function reference and the returning function does not get called anywhere outside, my question is, how/when does the returning function from line 11 gets executed? We can definitely infer that it is being executed, since the timer is actually getting cleared and node is terminating the program. A: The cleanup action function gets run whenever an observer unsubscribes its subscription. This includes: calling subscription.unsubscribe() using some operator like take() that automatically unsubscribes after a condition is met if/when the observable completes or errors
{ "pile_set_name": "StackExchange" }
Q: expand div, fixing in right center point Here is my example: http://jsfiddle.net/lcssanches/qtaUA/ $(" .inner_left, .inner_right ").hover(function() { $(this).css("z-index", "99999"); $(this).stop(true,false).animate({ width: "240px",height: "180px" }, 250); $(this).css("background-color", "#D0D0D0"); },function() { $(this).css("z-index", ""); $(this).stop(true,false).animate({ width: "125px",height: "130px" }, 250); $(this).css("background-color", "#ffffff"); }); I have 3 divs, like a column with 3 rows. When hover in the first div, it grows from top-to-bottom and right-to-left When hover in the third div, it grows from bottom-to-top and right-to-left The problem is the div that is in the second line. It need to grow part to top, and part to bottom. But fixed in the center. Now, in the example it only grow from top to bottom. I already try to put "top: -25px" int the jQuery animate, but it go to the top of wrapper. Thanks Sorry if I choose wrong words to explain. A: The following modifications in your code will solve your problem. Please note that this solution is specific to your provided absolute numbers and your provided code. You can tweak it easily to make it shorter and make it work across your solution dynamically. My intention is to show you how you can work around this. The HTML part: <div class="wrapper"> <div class="menu_right"> <div class="item_right"><div class="inner_right" style="top: 0px; right:0px;"><a href="#">1</a></div></div> <div class="item_right"><div class="inner_right" id="middleRow" style="top: 130px; right:0px;"><a href="#">2</a></div></div> <div class="item_right" ><div class="inner_right" style="bottom: 0px; right:0px;"><a href="#">3</a></div></div> </div> </div> The JavaScript part: $(" .inner_left, .inner_right ").hover(function() { var currentId = $(this).attr('id'); if (currentId == "middleRow") { var topPos = $(this).position().top - 25; var topPosPx = topPos + "px"; //or you could simply put 105px here specific to your code $(this).css("z-index", "99999"); $(this).stop(true,false).animate({ width: "240px",height: "180px", top: topPosPx }, 250); $(this).css("background-color", "#D0D0D0"); } else { $(this).css("z-index", "99999"); $(this).stop(true,false).animate({ width: "240px",height: "180px" }, 250); $(this).css("background-color", "#D0D0D0"); } },function() { var currentId = $(this).attr('id'); if (currentId == "middleRow") { $(this).css("z-index", ""); $(this).stop(true,false).animate({ width: "125px",height: "130px", top: "130px" }, 250); $(this).css("background-color", "#ffffff"); } else { $(this).css("z-index", ""); $(this).stop(true,false).animate({ width: "125px",height: "130px" }, 250); $(this).css("background-color", "#ffffff"); } }); For the CSS, no changes are needed on the provided css in your jsfiddle.net code.
{ "pile_set_name": "StackExchange" }
Q: Updating many-to-many navigation property in Entity Framework 6, changes not being saved I've been pulling my hair out for about 2 days now, as I simply cannot get EF to save changes whenever I add a many-to-many entity to an existing entity. My structure is plain simple: I have a table called Person, it has an ID (Primary, identity), and a few other string fields A table called Keyword with an ID (Primary, identity) and a string field called Value and a PersonKeywordRelation, with a PersonId, and a KeywordId field When I have generated my entities (Database first), I get a class Person, with an ICollection<Keyword> - all good, works as expected. The problem arises when I try to save an existing Person, with a modified list of keywords. Only the scalar properties (strings) are saved, not my keywords! I've tried disabling Lazy Loading, no effect. I tried loading each individual keyword from the database again, no effect. I tried loading all keywords into the context to see if that would help EF detect changes, it didn't. I am pretty sure I'm not the only one who have had this problem, (in fact I am entirely sure as I have seen a couple questions on here already, on the same subject, yet I am unable to find a working answer...), mostly for older versions of EF, which is another good reason as to why I started yet another question: Has nothing changed that addresses this issue at all? Here is my code that does the updating (and creation) of persons. You'll notice my attempt on making EF save changes accordingly. public void SavePersons(IList<Person> persons) { // Create a EF Context using (var ctx = new MyDbEntities()) { foreach (var person in persons) { // Attach ctx.Persons.Attach(person); // Insert or update? ctx.Entry(person).State = person.Id == 0 ? EntityState.Added : EntityState.Modified; // Get current keywords before clearing from entity var keywords = new List<Keyword>(person.Keywords); // Clear keywords from entity, so we can add fresh ones, hopefully // EF will have an easier time handling this.. person.Keywords.Clear(); // Add keywords keywords.ForEach(kw => { ctx.Keywords.Attach(kw); ctx.Entry(kw).State = EntityState.Modified; person.Keywords.Add(kw); }); } // Save ctx.SaveChanges(); } } A: Finally.. Finally I can rest! I found the solution! It's not a pretty one, but it works! Here's the code - sharing is caring. This is definitely the last time I will work with Entity Framework. Causes more pain & agony than good. public void SavePersons(IList<Person> persons) { // Create a EF Context using (var ctx = new MyDbEntities()) { // Iterate foreach (var person in persons) { // Get current keywords var keywords = new List<Keyword>(person.Keywords).ToList(); // Fetch Person from DB (if its not a NEW entry). Must use Include, else it's not working. var newPerson = ctx.Persons .Include("Keywords") .FirstOrDefault(s => s.Id == person.Id) ?? person; // Clear keywords of the object, else EF will INSERT them.. Silly. newPerson.Keywords.Clear(); // Insert or update? ctx.Entry(newPerson).State = newPerson.Id == 0 ? EntityState.Added : EntityState.Modified; // Apply new scalar values if(newPerson.Id != 0) { person.Id = newPerson.Id; ctx.Entry(newPerson).CurrentValues.SetValues(person); } // Iterate through all keywords foreach (var kw in ctx.Keywords) { // If the current kw exists in OUR list, add it // - if not, remove the relation from the DB. if (keywords.Any(k => k.Id == kw.Id)) { //ctx.Entry(kw).State = EntityState.Unchanged; ctx.Keywords.Attach(kw); newPerson.Keywords.Add(kw); } else newPerson.Keywords.Remove(kw); } } // Save ctx.SaveChanges(); } }
{ "pile_set_name": "StackExchange" }
Q: are all the numbers in Euclid proof prime numbers? in Euclid for infinite primes we define $p_0= 2, p_n = p_0p_1...p_{n-1}+1$ that way we get a series so that for every $n \in \mathbb{N}$ we get that $p_n$ is divided by a prime not one of $ p_0,...,p_{n-1} $. my question is: does for every $n \in \mathbb{N}$ we get that $ p_n $ is a prime itself ? i will be grateful if someone will give me a counterexample or a proof for this statement. A: No. Your series starts by $$2, 3, 7, 43, 1807, 3263443, 10650056950807, \ldots$$ and $$1807= 13 \times 139$$ $$10650056950807=547 \times 607 \times 1033 \times 3105.$$ Anyway $$2\times3\times5\times7\times11\times13+1=59 \times 509$$
{ "pile_set_name": "StackExchange" }
Q: Bootstrap 4 compiling javascript vendors error using Codekit 3 I'm a little bit old school with how I compile stuff. I'm still using codekit rather than npm, grunt etc. I'm not good with terminal. Anyway... I can compile the SCSS files fine from my Bootstrap 4 repo. But I'm getting error when I'm trying to compile the javascript vendors. It's a simple error but if anyone can shed some light that would be great! See below how I have compiled all my bootstrap js vendors into my main.js javascript file. I've not included jQuery because of old habits I normally put the latest CDN jQuery inline. // bootstrap 4 core js // @codekit-prepend "js/src/alert" // @codekit-prepend "js/src/button" // @codekit-prepend "js/src/carousel" // @codekit-prepend "js/src/collapse" // @codekit-prepend "js/src/dropdown" // @codekit-prepend "js/src/index" // @codekit-prepend "js/src/modal" // @codekit-prepend "js/src/tooltip" // @codekit-prepend "js/src/popover" // @codekit-prepend "js/src/scrollspy" // @codekit-prepend "js/src/tab" // @codekit-prepend "js/src/tooltip" // @codekit-prepend "js/src/util" // my shizzle (function ($) { alert("WTF!"); }); So when I run this block of code using Codekit 3 to watch and compile. I can compile it fine without minifying it. But when I minify it, I think it uses UglifyJS (I think) from the message and this is the error I get... UglifyJS minification failed with this error: Parse error at /Users/joshmoto/Sites/joshmoto.wtf/development/assets/.codekit-cache/alert.js:1,7 import $ from 'jquery' ^ SyntaxError: Unexpected token: name ($) at JS_Parse_Error.get (eval at <anonymous> (/Applications/CodeKit.app/Contents/Resources/engines/node_modules/uglify-js/tools/node.js:27:1), <anonymous>:86:23) at /Applications/CodeKit.app/Contents/Resources/engines/node_modules/uglify-js/bin/uglifyjs:384:40 at time_it (/Applications/CodeKit.app/Contents/Resources/engines/node_modules/uglify-js/bin/uglifyjs:620:15) at /Applications/CodeKit.app/Contents/Resources/engines/node_modules/uglify-js/bin/uglifyjs:345:9 at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3) Is something broken, or does this new Bootstrap 4 require jquery in the compiled file? Any help would be hugely appreciated as I don't get this problem with bootstrap 3. I just tried to use the non minified script file and I get this error in chrome debugger... So yeah its proper ballsed. A: I finally found a solution to my main javascript file compiling problem. The only way I could get the file to compile was to do this... /** ** Bootstrap 4 Core JS **/ // @codekit-prepend "vendor/jquery-3.3.1" // @codekit-prepend "vendor/popper.min" // @codekit-prepend "js/dist/alert" // @codekit-prepend "js/dist/button" // @codekit-prepend "js/dist/carousel" // @codekit-prepend "js/dist/collapse" // @codekit-prepend "js/dist/dropdown" // @codekit-prepend "js/dist/tooltip" // @codekit-prepend "js/dist/modal" // @codekit-prepend "js/dist/popover" // @codekit-prepend "js/dist/scrollspy" // @codekit-prepend "js/dist/tab" // @codekit-prepend "js/dist/util" // jQuery (function ($) { alert("Boom!"); })(jQuery);
{ "pile_set_name": "StackExchange" }
Q: What I am doing wrong here, my style sheet is not loading up I have created an external style sheet and name it style.css. style.css #topbar { background-color: red; width: 1000px; height: 40px; } body{ background-color: green; } Now I am calling this style.css from the root folder but its not working. I copied the style.css on both within internal folder and on root but still not loading up. <html> <head> <title>BBC News Site/title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> </body> </html> A: <title>BBC News Site/title> fix it into : <title>BBC News Site</title>
{ "pile_set_name": "StackExchange" }
Q: Tooltip over DataGrid row in C# .Net 4.0 I want to add tooltip for every row (and for every cell) in DataGrid. How can I do this? I've tried RowDataBound and CellFormating, but it seems that I can't use this examples in my code (no similar events) Do you have any ideas how to handle it? A: Here Is an Example From MSDN, In which they Clearly described how to Gets or sets the ToolTip text associated with this cell. with the help of _CellFormatting event of the control; Consider the code below: void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if ((e.ColumnIndex == this.dataGridView1.Columns["column_name"].Index) && e.Value != null) { DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; cell.ToolTipText = "This is given ToolTip"; } } You can try Conditional Tooltips Too like this(this too explained in the associated link): if (e.Value.Equals("some value")) { cell.ToolTipText = "ToolTip 1"; } else if (e.Value.Equals("some other value")) { cell.ToolTipText = "ToolTip 2"; } // Like wise
{ "pile_set_name": "StackExchange" }
Q: Need to delete all data after third colon of a string i have a file say test.txt with the following contents apple:orange:mango:123:1234:12345 i want all data after third colon to be removed Expected output apple:orange:mango: Kinldy help A: Using backreference: sed 's/\([^:]*:[^:]*:[^:]*:\).*/\1/' test.txt or with GNU sed: sed -E 's/(([^:]*:){3}).*/\1/' test.txt
{ "pile_set_name": "StackExchange" }
Q: embed the string in view flipper ontouch I am creating an application in which i have used four custom view.I have embed that in the viewflipper now i want to add ontouch event to viewflipper.i have added the ontouchevent but i want that when user touch on the particular position then it will show some text on the canvas which is used by viewflipper. I have uploaded the image also can any one help me on this topic . A: I have mention in my question that i am using view.so i have used the invalidate method . Viewflipper .invalidate (); invalidate method force to redraw the view if you want more knowledge then refer this link
{ "pile_set_name": "StackExchange" }
Q: MurmurHash3_32 Java returns negative numbers I am trying to replicate the file hashing of MobileSheetsPro, an Android app, where there is a hashcodes.txt which includes a hash for each file, as well as the path, last modified date and filesize. We'll just focus on the hashing part. So for the random song I uploaded here if you want to try it for yourself, I am using the murmurhash-native npm package to convert it to a buffer and then hash it like so: const fs = require("fs"); const { promisify } = require("util"); const { murmurHash } = require("murmurhash-native"); const readFileAsync = promisify(fs.readFile); async function hashcodeObjFromFilePath(filepath) { const buf = await readFileAsync(filepath); const h = murmurHash(buf); console.log(h); } This prints out a hash of 4275668817 when using the default seed of 0 and 3020822739 when using the seed 0xc58f1a7b as a second argument. The problem: the app seems to calculate it differently. The developer wrote the following, but I don't see that exact function in the code he linked: Check this out: github link Those are the classes I've utilized. I call Hashing.goodFast32Hash(HASH_KEY)) where HASH_KEY is equal to 0xC58F1A7B. EDIT I've got more infos from the dev: I call Files.hash(file, Hashing.goodFast32Hash(HASH_KEY)); Using the return value from that, I call "asInt()" on the HashCode object that is returned. So it's a signed integer value (negative values are just fine). And yes, HASH_KEY is the seed value passed to the function. Since I'm not good at Java I still have no idea to replicate this in node-js... That's all the info I have, folks. Anyone see where I'm going wrong? A: Found it! The asInt() function in the Java lib returns a signed int32 *in little endian byte order The following is probably not the easiest way but the code const h = murmurHash(buf, "buffer", 0xc58f1a7b); // console.log(parseInt(h, 16).toString(2)); const fromHashFile = Buffer.alloc(4); fromHashFile.writeInt32BE(-1274144557); console.log(fromHashFile); console.log(h); console.log(h.readInt32BE()); console.log("hash from hashcodes file: -1274144557"); Prints out the following to console: <Buffer b4 0e 18 d3> <Buffer b4 0e 18 d3> -1274144557 hash from hashcodes file: -1274144557
{ "pile_set_name": "StackExchange" }
Q: How to smooth a scanned image using Gimp I have drawn an image which I then scanned into the computer and saved as a png. I just want to make the lines smooth on the image. The image is a logo Any help is much appreciated. I am using GIMP 2.8 A: In order to make lines smooth, you have to vectorize the bitmap in applications like Inkscape: You can import the image and trace it: After the tracing operation the image is vectorized and you can work on the nodes. For example you can simplify the path, which is an automatic operation: In this example the left image is the traced one and the right image is obtained simplifying the path (less nodes and more smooth). Obviously after this operation you can work on single nodes in order to adjust the details (in the example the eye of the lion needs a little work). In GIMP you can blur the image in order to soften the edges, but I suggest you to vectorize the image. A: If instead of going to a vectors app, you want to deal with pixes, inside GIMP, you can try these simple two steps, selct:filters->blur-> gaussian blue - try using a radius of 2-4, and then use colors->curves and pull the curve in an "S" shape to sharpen the borders back. The jaggies will smooth out, and you can fine tune how smooth you ant it with the curves. The default curves settings will work for black over white or vice-versa - selet the appropriate channels to affect your drawing.
{ "pile_set_name": "StackExchange" }
Q: What are gradle task definitions in groovy language? I'm completely new to both gradle and groovy and I'm having trouble to find information about what the below actually is in the groovy language task myTask(dependsOn: 'compile') << { println 'I am not affected' } AFAIK the {...} part is a closure which seems to be passed to whatever is defined before <<. Is task myTask() a call to a constructor? And what is the thing with the colon that looks like a parameter? What does << do? Is it an operator that was overloaded by gradle or is it standard groovy? A: dependsOn: 'compile' is a named argument. << is an overloaded operator that adds a task action to the task. (See Gradle User Guide for more information.) { ... } is a closure that implements the task action. myTask is syntactically a nested method call (task(myTask(dependsOn: 'compile') << ...)), but gets rewritten to a String using a Groovy compiler plugin (task('myTask', dependsOn: 'compile') << ...).
{ "pile_set_name": "StackExchange" }
Q: Translating status codes to messages in log files I'm not overly efficient when it comes to coding, and I am looking for ways to improve the speed of a log translator I built. Several files are uploaded to a folder on a server and log files are selected for processing. Speed here is fine. Each log file has 5000-10000 lines possible a bit higher. They are space delimited files that look like this: 20:04:13 + MA 00 61 20:04:17 - MA 00 61 20:04:18 + MA 00 61 optionaltxt 20:04:20 - MA 00 61 There are at least 5 fields for every entry but more can be added if optional text exists. Field 5 is a status code, and it has to be cross referenced with a language file then replaced with the corresponding message so the result is like this: 17:29:48 - MA 00 (061) Feed hold! X / Y axis is locked 17:29:48 + MA 00 (061) Feed hold! X / Y axis is locked 17:29:50 - MA 00 (061) Feed hold! X / Y axis is locked optionaltxt 17:29:51 + MA 00 (061) Feed hold! X / Y axis is locked The translated logs are saved to a new folder for download later. At the moment translation takes about 7-10 seconds per log file. The problem is that it is common to have 90 files or more and the time starts adding up. I have no control over the log format or language file format. This part of my code looks like this: $shLANG = file_get_contents("ErrCODES/data_en.properties"); $SHarray = explode("\n", $shLANG); $logARRAY = glob($uploadDIR.$filepath."/original/*.[lL][oO][gG]"); foreach ($logARRAY as $logFILEarray) { $name = basename($logFILEarray); $logFILE = file_get_contents($uploadDIR.$filepath."/original/".$name); $logFILEarray = explode("\n", $logFILE); foreach ($logFILEarray as $key => $line) { $newline=""; $LINEarray = explode(" ", $line); if(isset($LINEarray[0])){$newline .= $LINEarray[0]." ";} if(isset($LINEarray[1])){$newline .= $LINEarray[1]." ";} if(isset($LINEarray[2])){$newline .= $LINEarray[2]." ";} if(isset($LINEarray[3])){$newline .= $LINEarray[3]." ";} if(isset($LINEarray[4])){ foreach ($SHarray as $code) { if (strlen($LINEarray[4])>0){ if (substr($code, 0, strpos($code, '=')) == $LINEarray[4]) { $newline .= trim(explode('null;', $code)[1]). " "; } } } } if(isset($LINEarray[5])){$newline .= $LINEarray[5]." ";} if(isset($LINEarray[6])){$newline .= $LINEarray[6]." ";} if(isset($LINEarray[7])){$newline .= $LINEarray[7]." ";} if(isset($LINEarray[8])){$newline .= $LINEarray[8]." ";} $newline .= "\r"; $logFILEarray[$key] = $newline; } //var_dump($logFILEarray); $info = implode("\n",$logFILEarray); file_put_contents($uploadDIR.$filepath."/translation/".$name, $info); }//for all glob .log The code works fine, but how can I improve the speed (greatly)? A: What you have looks problematic in a few ways. You have a poor data structure for your localization strings. You have these in an array the must be iterated every single time you are doing a lookup against it. This is an linear complexity (O(n)) operation that when executed inside your loop (another O(n) iteration) give you O(n^2) overall performance. @TimSparrow has touched on a good alternative - to load the localization strings into an associative array the will allow O(1) lookup when being used - but perhaps didn't explain how critical this is to your performance. By building such a data structure up front, you whole algorithm goes to O(m) (to build localization data structure) + O(n) (from your log file loop) instead of O(m * n). To illustrate the impact to your performance, let assume you have a 10K line log file and a 100 line localization file. With your current code, this means you could have up to 1 Million lookup operations you have to perform vs. 10,100 if using a proper data structure. This code is a memory hog. You store every file you are working with wholly in memory, as well as storing the same data in duplicate in the result arrays you are building, not to mention all the temporary array/string conversion you have that, again mean you are going to be holding that information in duplicate in memory. If you can get the memory utilization more optimized here, then you may be more able to do things like for each of the individual log into their own process to parallelize the work. You should consider working with the rows in a more structured manner vs. working with them primarily as strings. fgetcsv(), fputcsv() or similar give you better ways to parse through and write your files. Incorporating the above thoughts should allow you to greatly streamline both the performance of your script as well as just simplify how it works. You might end up with something like: $localizations = []; $handle = fopen('ErrCODES/data_en.properties','r'); // read lines from file one at a time. while ($line = fgetcsv($handle, 0, ' ')) { // this part may vary based on your format $localizations[$line[0]] = $line[1]; } fclose($handle); $logFiles = glob($uploadDIR.$filepath."/original/*.[lL][oO][gG]"); // here is where at some point you may want to fork processes to paralellize // now it is serial foreach loop foreach ($logFiles as $logFile) { $translatedFile = str_replace('/original', '/translation/', $logFile); $logHandle = fopen($logFile,'r'); $translateHandle = fopen($translatedFile, 'w+'); while($line = fgetcsv($logHandle, 0, ' ') { // apply localization if(!empty($line[4]) && isset($localization[$line[4]])) { $line[4] = $localization[$line[4]]; } fputcsv($translateHandle, $line, ' '); } fclose($translateHandle); fclose($logHandle); } A few final thoughts on style: - Your style is a little bit all over the place, which makes your code a littel hard to read. - Particularly variable naming is odd. PHP tends to use a mix of camelCase and snake_case in most code bases you will find (internal PHP functions mix both unfortunately). Your approach to variable syntax is very haphazard, sometimes oddly putting portions of variable names in upper case with apparent cohesive approach, sometimes first letter is uppercase, sometimes it is lower case, etc. - Your indentations are inconsistent. - You could be well-served by better use of spacing around flow control operators. A line of code like if(isset($LINEarray[0])){$newline .= $LINEarray[0]." ";} is extremely hard to read. - Consider familiarizing yourself with the PHP-FIG PHP standards, particularly PSR-1 and PSR-2 which deal with aspects of coding style. These are pretty much the de-facto industry standards. A: First thing, I would prepare the errorCodes array: After $SHarray = explode("\n", $shLANG); Add: $errors = []; foreach($SHArray as $line) { list($code, $message) = explode('=', $line); $errors[$code] = $message } Note: it is not clear from your code what additional processing is needed to get an associative array of $code => $message, you will need to add that yourself. So instead of repeated substring search: foreach ($SHarray as $code) { if (strlen($LINEarray[4])>0){ if (substr($code, 0, strpos($code, '=')) == $LINEarray[4]) { $newline .= trim(explode('null;', $code)[1]). " "; } } } you will have foreach($errors as $code => $message) { if($code == $LINEarray[4]) { $newline .= $message . " "; } } Another thing: instead of linear processing of each log field, I would update $lineArray[4], then re-assemble the array using implode, without processing other fields at all, if they do not need to be changed. Note that it may not increase productivity, but will improve code readability and size. Like this: $lineArray = explode(' ', $line); // use a separate function/method to translate one entry $lineArray[4] = translateErrorMessage($lineArray[4], $errors); $newLine = implode(' ', $lineArray); Finally, With speed and productivity, you need to consider not only your code, but other system factors as well. Which version of php are you using? PHP 7 may give a speed benefit over older 5.xx Are you using standalone php (CLI) or run as a web server? On large files, web server may fail with a timeout, also it is no good to run such tasks with full stack, as it consumes way too much memory. Is it possible to install some PHP pre-compiler with your system? These usually save time, as pre-compiled code works much faster.
{ "pile_set_name": "StackExchange" }
Q: YAWS Websocket Trouble I'm trying to get the YAWS websocket example from here running on my local. It's a basic ws-based echo server. I have YAWS set up and running on localhost:8080 (direct from the Debian repos; no conf changes except pointing it to a new root directory) the code listing from the bottom of this page wrapped in <erl> tags saved as websockets_example_endpoint.yaws this page saved as index.yaws (I literally copy/pasted the view-source for it, saved it as that file and pointed the socket request at localhost:8080 rather than yaws.hyber.org). When I visit localhost:8080/websockets_example_endpoint.yaws in-browser, it displays the text "You're not a web sockets client! Go away!", as expected. When I visit localhost:8080, it points me to the javascript enabled form, but the "Connect" button does nothing when clicked. If I leave index.yaws pointed at yaws.hyber.org instead of localhost:8080, the echo server connects and works exactly as expected. Can anyone give me a hint as to what I'm doing wrong (or alternatively, point me to source for a working example)? A: There is a gitbub project, I've created: https://github.com/f3r3nc/yaws-web-chat/ This is also an example for embedding yaws and extended with group chat. Note, that the standard of WebSocket is under development thus yaws and the browser should support the same WS version in order to work correctly. yaws 1.91 works with Safari Version 5.1.1 (6534.51.22) but does not with Chrome (15.0.874.102) and probably not with (14.x).
{ "pile_set_name": "StackExchange" }
Q: What is the connection between ULN2004 and ULN2804 drivers? I have an unipolar stepper motor that im driving with an Arduino. As a driver for the motor i bought a ULN2004 driver chip from Ebay. Or so i thought. I might be missing something, but the chip i received has 9 pins on each side, not 8 as my sketch illustrates, and the number on it is ULN2804, not ULN2004. The link to the data sheet on the ULN2004 listing i bought from spinatronics says it's a ULN2804 chip. I'm unexperienced in how manufacturers set the numbers on the chips. Have i bought the wrong chip, or can a ULN2804 driver be used the same way as a ULN2004? How do i then change my sketch to implement the last two additional pins of the chip? A: Here's the pdf for the ULN2004 chip It looks like the same application and same specs, set of darlington arrays. ULN2004 has 7 circuits as oppose to ULN2804 which has 8. Both carry 6-15V (CMOS, PMOS compatible inputs), Output currents of 500 mA per driver, and Output Voltage of 50V It might've been a careless mistake derived from laziness since the chips have the same type of circuitries. Because these chips are practically the same, you can utilize 2804 the same way as 2004. Only in this circuit, you'd have in8, out8 pins setup the same as in7 and out7
{ "pile_set_name": "StackExchange" }