{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n\n\nA: I think the issue you have is that you have not validated your code, even down to whether you have matching curly braces or not (hint, you do not!)\nmoving the open and send commands back into the first function and removing the extra curly brace shoudl work.\nthe below should work :\n\n\n\n\n\n\n

Let AJAX change this text

\n\n\n \n\n\nhope that helps\nOlly\n\nA: I think the problem is with the following line in ajax_object.html file:\nif (xmlhttp.readyState==4 && xmlhttp.status==200)\n\nIf you run the file with the above line and look at the 'Show Page Source', \nit will be apparent that the 'Request & Response' header has its \n-- Status and Code --- set to nothing\n\nSo, delete the line and you will get:\n\n\n\n\n\n \n \n \n\n \n\n\n

Let AJAX change this text

\n\n\n\n\nIf you run this code it will output the ajax_info.txt file."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":305,"cells":{"_id":{"kind":"string","value":"d306"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"From your images it seems like that you don't set the top constraint of the top view to top safeAreaLayoutGuide instead you set it to superView here\n\n, also you can't set the top of the button to safeArea , as it's only appears for direct subviews of thw main vc's view not to nested subviews"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":306,"cells":{"_id":{"kind":"string","value":"d307"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"yum -y remove php* to remove all php packages then you can install the 5.6 ones.\n\nA: Subscribing to the IUS Community Project Repository\ncd ~\ncurl 'https://setup.ius.io/' -o setup-ius.sh\n\nRun the script:\nsudo bash setup-ius.sh\n\nUpgrading mod_php with Apache\nThis section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.\nBegin by removing existing PHP packages. Press y and hit Enter to continue when prompted.\nsudo yum remove php-cli mod_php php-common\n\nInstall the new PHP 7 packages from IUS. Again, press y and Enter when prompted.\nsudo yum install mod_php70u php70u-cli php70u-mysqlnd\n\nFinally, restart Apache to load the new version of mod_php:\nsudo apachectl restart\n\nYou can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:\nsystemctl status httpd"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":307,"cells":{"_id":{"kind":"string","value":"d308"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Try\n\n\n\nA: In your controller declare pelangganArr as $scope.pelangganArr.\nOnly scope variables are recognised by angular in the DOM and provide 2 way binding."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":308,"cells":{"_id":{"kind":"string","value":"d309"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I suppose com.fasterxml.jackson's @JsonIgnore annotation should help.\npublic class Entity {\n private String name;\n @JsonIgnore\n private String entityType;\n @JsonIgnore\n private Entity rootEntity;\n}\n\n\nA: In Json-lib you have a JsonConfig to specify the allowed fields:\nJsonConfig jsonConfig=new JsonConfig();\njsonConfig.registerPropertyExclusion(Entity.class,\"rootEntity\");\njsonConfig.registerPropertyExclusion(Entity.class,\"entityType\");\n\nJSON json = JSONSerializer.toJSON(objectToWrite,jsonConfig);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":309,"cells":{"_id":{"kind":"string","value":"d310"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"While the Dropbox API was designed with the intention that each user would link their own Dropbox account, in order to interact with their own files, it is technically possible to connect to just one account. We generally don't recommend doing so, for various technical and security reasons, but those won't apply if you're the only user anyway.\nSo, there are two ways to go about this:\n1) Implement the normal app authorization flow as documented, and log in and authorize the app once per app installation. The SwiftyDropbox SDK will store the resulting access token for you, which you can programmatically re-use after that point each time using authorizedClient.\n2) Manually retrieve an access token for your account and hard code it in to the app, using the DropboxClient constructor shown here under \"Initialize with manually retrieved auth token\"."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":310,"cells":{"_id":{"kind":"string","value":"d311"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Per the Dockerfile ARG docs,\n\nThe ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg = flag. \n\nin order to accept an argument as part of the build, we use --build-arg.\nDockerfile ENV docs:\n\nThe ENV instruction sets the environment variable to the value . \n\nWe also need to include an ENV statement because the CMD will be executed after the build is complete, and the ARG will not be available. \nFROM busybox\n\nARG ENVIRONMENT\nENV ENVIRONMENT $ENVIRONMENT\nCMD echo $ENVIRONMENT\n\nwill cause an environment variable to be set in the image, so that it is available during a docker run command.\ndocker build -t test --build-arg ENVIRONMENT=awesome_environment .\ndocker run -it test\n\nThis will echo awesome_environment.\n\nA: Try changing your RUN command do this:\nRUN npm run ng build --configuration=$ENVIRONMENT\n\nThis should work. Check here\nThanks."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":311,"cells":{"_id":{"kind":"string","value":"d312"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You declare i within the for loop without initialising it. This is the reason you get 'weird values'. In order to rectify, you need to write:\nfor(int i=0; i<5; i++)\nHope this helps!\n\nA: Just copy the bytes:\nmemcpy(newID, chID, 4);\n\n\nA: One more note that it seems some people have overlooked here: if chId is length 4 then the loop bounds are i=0;i<4. That way you get i=0,1,2,3. (General programming tip, unroll loops in your head when possible. At least until you are satisfied that the program really is doing what you meant it to.)\nNB: You're not copying chId into a string. You're copying it into a char array. That may seem like semantics, but \"string\" names a data type in C++ which is distinct from an array of characters. Got it right in the title, wrong in the question description."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":312,"cells":{"_id":{"kind":"string","value":"d313"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"No such thing is built in, because it doesn't need to be. Unlike destructuring, which is fairly involved, constructing maps is very simple in Clojure, and so fancy ways of doing it are left for ordinary libraries. For example, I long ago wrote flatland.useful.map/keyed, which mirrors the three modes of map destructuring:\n(let [transforms {:keys keyword\n :strs str\n :syms identity}]\n (defmacro keyed\n \"Create a map in which, for each symbol S in vars, (keyword S) is a\n key mapping to the value of S in the current scope. If passed an optional\n :strs or :syms first argument, use strings or symbols as the keys instead.\"\n ([vars] `(keyed :keys ~vars))\n ([key-type vars]\n (let [transform (comp (partial list `quote)\n (transforms key-type))]\n (into {} (map (juxt transform identity) vars))))))\n\nBut if you only care about keywords, and don't demand a docstring, it could be much shorter:\n(defmacro keyed [names]\n (into {}\n (for [n names]\n [(keyword n) n])))\n\n\nA: I find that I quite frequently want to either construct a map from individual values or destructure a map to retrieve individual values. In the Tupelo Library I have a handy pair of functions for this purpose that I use all the time:\n(ns tst.demo.core\n (:use demo.core tupelo.core tupelo.test))\n\n(dotest\n (let [m {:a 1 :b 2 :c 3}]\n (with-map-vals m [a b c]\n (spyx a)\n (spyx b)\n (spyx c)\n (spyx (vals->map a b c)))))\n\nwith result\n; destructure a map into values\na => 1\nb => 2\nc => 3\n\n; construct a map\n(vals->map a b c) => {:a 1, :b 2, :c 3}\n\n\nP.S. Of course I know you can destructure with the :keys syntax, but it always seemed a bit non-intuitive to me."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":313,"cells":{"_id":{"kind":"string","value":"d314"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"As @Louwki said, you can use a Trait to do that, in my case I did something like this:\ntrait SaveToUpper\n{\n /**\n * Default params that will be saved on lowercase\n * @var array No Uppercase keys\n */\n protected $no_uppercase = [\n 'password',\n 'username',\n 'email',\n 'remember_token',\n 'slug',\n ];\n\n public function setAttribute($key, $value)\n {\n parent::setAttribute($key, $value);\n if (is_string($value)) {\n if($this->no_upper !== null){\n if (!in_array($key, $this->no_uppercase)) {\n if(!in_array($key, $this->no_upper)){\n $this->attributes[$key] = trim(strtoupper($value));\n }\n }\n }else{\n if (!in_array($key, $this->no_uppercase)) {\n $this->attributes[$key] = trim(strtoupper($value));\n }\n }\n }\n }\n}\n\nAnd in your model, you can specify other keys using the 'no_upper' variable. Like this:\n// YouModel.php\nprotected $no_upper = ['your','keys','here'];\n\n\nA: Was a lot easier than I through. Solution that is working for me using traits, posting it if anyone also run into something like this.\nattributes[$key] = trim(strtoupper($value));\n }\n }\n}\n\nUPDATE:\nFor Getting values as upper case you can add this to the trait or just add it as a function in the model:\npublic function __get($key)\n{\n if (is_string($this->getAttribute($key))) {\n return strtoupper( $this->getAttribute($key) );\n } else {\n return $this->getAttribute($key);\n }\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":314,"cells":{"_id":{"kind":"string","value":"d315"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"So you want each group ordered internally, and the groups order by the latest value, right? Okay, I think we can do that...\nvar query = from action in actions\n group action by action.Uid into g\n orderby g.Max(action => action.Created) descending\n select new { Uid = g.Key,\n Actions = g.OrderByDescending(action => action.Created) };\n\nforeach (var group in query)\n{\n Console.WriteLine(\"Uid: {0}\", group.Uid);\n foreach (var action in group.Actions)\n {\n Console.WriteLine(\" {0}: {1}\", action.Created, action.ActionId);\n }\n}\n\n\nA: For the SQL, get the sort column in the SELECT statement\nSELECT *, (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) AS MaxCreated\nFROM actions a\nORDER BY MaxCreated desc, a.created desc\n\nor\nSELECT *\nFROM actions a\nORDER BY (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) desc, a.created desc\n\n(just fixed an error in the first query)\nHere's my linq:\nvar actions = (from a in actions \n orderby ((from a2 in actions\n where a2.UserID == a.UserID\n select a2.created).Max ()) descending, a.created descending\n select a);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":315,"cells":{"_id":{"kind":"string","value":"d316"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"As it turns out, with the default OpenSSL (which is bundled with node, but if you've built your own, it is possible to configure different engines), the algorithm to generate random data is exactly the same for both randomBytes (RAND_bytes) and pseudoRandomBytes (RAND_pseudo_bytes).\nThe one and only difference between the two calls depends on the version of node you're using:\n\n\n*\n\n*In node v0.12 and prior, randomBytes returns an error if the entropy pool has not yet been seeded with enough data. pseudoRandomBytes will always return bytes, even if the entropy pool has not been properly seeded.\n\n*In node v4 and later, randomBytes does not return until the entropy pool has enough data. This should take only a few milliseconds (unless the system has just booted).\n\n\nOnce the the entropy pool has been seeded with enough data, it will never \"run out,\" so there is absolutely no effective difference between randomBytes and pseudoRandomBytes once the entropy pool is full.\nBecause the exact same algorithm is used to generate randrom data, there is no difference in performance between the two calls (one-time entropy pool seeding notwithstanding).\n\nA: Just a clarification, both have the same performance:\nvar crypto = require (\"crypto\")\nvar speedy = require (\"speedy\");\n\nspeedy.run ({\n randomBytes: function (cb){\n crypto.randomBytes (256, cb);\n },\n pseudoRandomBytes: function (cb){\n crypto.pseudoRandomBytes (256, cb);\n }\n});\n\n/*\nFile: t.js\n\nNode v0.10.25\nV8 v3.14.5.9\nSpeedy v0.1.1\n\nTests: 2\nTimeout: 1000ms (1s 0ms)\nSamples: 3\nTotal time per test: ~3000ms (3s 0ms)\nTotal time: ~6000ms (6s 0ms)\n\nHigher is better (ops/sec)\n\nrandomBytes\n 58,836 ± 0.4%\npseudoRandomBytes\n 58,533 ± 0.8%\n\nElapsed time: 6318ms (6s 318ms)\n*/\n\n\nA: If it's anything like the standard PRNG implementations in other languages, it is probably either not seeded by default or it is seeded by a simple value, like a timestamp. Regardless, the seed is possibly very easily guessable."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":316,"cells":{"_id":{"kind":"string","value":"d317"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"EntityManager.executeQueryLocally is a synchronous function and you can use its result immediately. i.e.\nvar myEntities = myEntityManager.executeQueryLocally(myQuery);\n\nWhereas EntityManager.executeQuery is an asynchonous function ( even if the query has a 'using' call that specifies that this is a local query). So you need to call it like this:\nvar q2 = myQuery.using(breeze.FetchStrategy.FromLocalCache);\nmyEntityManager.executeQuery(q2).then(function(data) {\n var myEntities = data.results;\n});\n\nThe idea behind this is that with executeQuery you treat all queries in exactly the same fashion, i.e. asynchronously, regardless of whether they are actually asynchronous under the hood. \nIf you want to create an EntityManager that does not go to the server for metadata you can do the following: \n var ds = new breeze.DataService({\n serviceName: \"none\",\n hasServerMetadata: false\n });\n\n var manager = new breeze.EntityManager({\n dataService: ds\n });"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":317,"cells":{"_id":{"kind":"string","value":"d318"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I'm assuming that you have started with the following as it looks similar to the URL that you have created\nhttp://docs.aws.amazon.com/AWSECommerceService/latest/GSG/SubmittingYourFirstRequest.html\nDouble check the timestamp as the page mentions it can't be more than 15 minutes old\nBut I'm afraid I don't know that API well enough to know how to get the signature setup correctly but have you considered using a library\nThis seems like a nice example of what can be achieved with the library http://exeu.github.io/apai-io/"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":318,"cells":{"_id":{"kind":"string","value":"d319"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You'll have discovered that your compiler doesn't like the line\nREAL :: y(0:n+1) = (/(k, k=a,b,h)/)\n\nChange it to \nREAL :: y(0:n+1) = [(k, k=INT(a),INT(b),2)] \n\nthat is, make the lower and upper bounds for k into integers. I doubt that you will ever be able to measure any increase in efficiency, but this change might appeal to your notions of nice-looking and convenient code.\nYou might also want to tweak the way you initialise M. I'd have written your two loops as\nM = 0.0\nDO i = 1,n\n M(i,i) = y(i)**2\nEND DO\n\nOverall, though, your question is a bit vague so I'm not sure how satisfactory this answer will be. If not enough, clarify your question some more."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":319,"cells":{"_id":{"kind":"string","value":"d320"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can try using Text Component Line Number."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":320,"cells":{"_id":{"kind":"string","value":"d321"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Try to add , after \"userAccountResource\" like this\n .factory(\"userAccountResource\", //, here was missing\n [\"$resource\",\n userAccountResource]);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":321,"cells":{"_id":{"kind":"string","value":"d322"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You have to put list of data in a scope\ntry something like this:\npublic List getMyList() {\n myList.clear();\n List list = (List) AdfFacesContext.getCurrentInstance().getProcessScope().get(\"myList\");\n if (list != null) {\n for (String var : list) {\n myList.add(var);\n }\n }\n return myList;\n }\n\nYou can also see this question and answer : \nHow to refresh table within a popup in dialog window in ADF Oracle 11gR1\n\nA: The problem is that I define the setNameList() in managedbean and have to invoke setNameList() in another method in Class B. \nI new a fresh managedBean to call this method and the nameList in this instance is not the one bonded to the page.\nSolution:\nIn class B, get the right instance as:\nManagedBean managedBean = (ManagedBean)ADFUtil.evaluateEL(\"#{pageFlowScope.ManagedBean}\");\n\nThe issue is gone."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":322,"cells":{"_id":{"kind":"string","value":"d323"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"In Python, do the following where alwayssep is the expression and line is the passed string:\nline = re.sub(alwayssep, r' \\g<0> ', line)\n\n\nA: My Pythonizer converts that to this:\nline = re.sub(re.compile(alwayssep),r' \\g<0> ',line,count=0)"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":323,"cells":{"_id":{"kind":"string","value":"d324"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"This document addresses issues on what you can, or rather, cannot do as Instance Administrators. You are permitted to change what you have access to the web UI and SMTP parameters using the APEX_INSTANCE_ADMIN package."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":324,"cells":{"_id":{"kind":"string","value":"d325"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"you can try something like this.\n\n \n \n {% for key in groups.keys() %}\n \n {% endfor %}\n \n \n \n \n {% for key in groups.keys() %}\n \n {% endfor %}\n \n \n
{{ key|title }}
{{ groups[key]}}
"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":325,"cells":{"_id":{"kind":"string","value":"d326"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I diff'ed the project against an earlier version I'd kept that worked properly and came up with this fix:\nIn Xcode, under your Phonegap or Cordova project, select\nTarget -> Build Phases -> Compile Sources\n\nAdd your plugin into the list there, in this case CVLogger.m located in your file structure under \"Plugins\".\nAfter this, the project compiles without error and the console plugin works. No need to reinstall and reconfigure your entire project for this..."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":326,"cells":{"_id":{"kind":"string","value":"d327"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Your superclass PointF is not serialisable. That means that the following applies:\n\nTo allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.\nDuring deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.\n\nSee: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html\nYou will need to look at readObject and writeObject:\n\nClasses that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:\n private void writeObject(java.io.ObjectOutputStream out)\n throws IOException\n private void readObject(java.io.ObjectInputStream in)\n throws IOException, ClassNotFoundException;\n\n\nSee also here: Java Serialization with non serializable parts for more tips and tricks.\n\nA: I finally found the solution. Thanx @Greg and the other comment that has now been deleted. The solution is that instead of extending these objects we can make stub objects. As i was calling super from constructor the x and y fields were inherited from base class that is not serializable. so they were not serialized and there values were not sent.\nso i mofidfied my class as per your suggestions\npublic class MyPointF implements Serializable {\n\n/**\n * \n */\nprivate static final long serialVersionUID = -455530706921004893L;\n\npublic float x;\npublic float y;\n\npublic MyPointF(float x, float y) {\n this.x = x;\n this.y = y;\n}\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":327,"cells":{"_id":{"kind":"string","value":"d328"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You could do this:\npublic override string DoSomething()\n{\n //does something...\n base.DoSomething();\n\n return GetName().Result;\n}\n\nWarning: this can cause a deadlock\nSee Don't block on async code"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":328,"cells":{"_id":{"kind":"string","value":"d329"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"This has nothing to do with React Native, one of your resource files references an nonexisting value (dialogCornerRadius). Locate the reference (Android Studio to the rescue) and fix it."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":329,"cells":{"_id":{"kind":"string","value":"d330"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"These following guidelines may help you with initializing a Jenkins freestyle job for building a subproject rather than building all projects included in a git repo.\n\n\n*\n\n*Install git-plugin for Jenkins\n\n*Create a freestyle job and add your git hub repository's link on SCM repository field\n\n\n*\n\n*New Item --> \n\n*Name the item and OK --> \n\n*Select Git in SCM --> \n\n*Add repository URL --> \n\n*Add invoke top-level maven targets as Build steps -->\n\n*In Goals install -pl ChildProjectD\n\n*(optional) Add post-build and other configurations\n\n\n\nIt will build the Child project as you want instead of full project.\nYou can refer Jenkins GitHub Java Application Project Build Configuration Maven to get more help. Check also mvn install -pl --help for more info.\nFeel free to ask questions."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":330,"cells":{"_id":{"kind":"string","value":"d331"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Not over the internet, as that would be very dangerous, the user would have to have special software. Otherwise web programs could (very) easily be used for malicious purposes."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":331,"cells":{"_id":{"kind":"string","value":"d332"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Brutally:\nfunction formatValue(value) {\n var tempVal = Math.trunc(value * 1000);\n var lastValue = (tempVal % 10);\n\n if (lastValue > 0 && lastValue <= 5) lastValue = 5;\n else if (lastValue > 5 && lastValue <= 9) lastValue = 10;\n else lastValue = 0;\n\n return parseFloat((Math.trunc(tempVal / 10) * 10 + lastValue) / 1000).toFixed(3);\n}\n\nformatValue(3.656); // -> \"3.660\"\nformatValue(3.659); // -> \"3.660\"\nformatValue(3.660); // -> \"3.660\"\nformatValue(3.661); // -> \"3.665\"\nformatValue(3.664); // -> \"3.665\"\nformatValue(3.665); // -> \"3.665\"\n\nPay attention: function returns a string (.toFixed returns a string).. (but however a fixed decimal length doesn't have any sense in a number)\n\nA: Rounding to a certain number of decimals is done by multiplying the value to bring the desired amount of decimals into the integer range, then getting rid of the remaining decimals, then dividing by the same multiplier to make it decimal again.\nRounding to a \"half-decimal\" as you want is accomplished by doubling the multiplier (2X instead of 1X).\nThe + 0.005 is to make it round up as desired, otherwise it would always round down.\ntoFixed() is used to make the string representation of the value have the decimal part padded with zeros as needed.\n\n\nfunction formatValue(value) { \r\n return (Math.floor((value + 0.005) * 200) / 200).toFixed(3);\r\n}\r\n\r\nconsole.log(formatValue(1.950));\r\nconsole.log(formatValue(1.954));\r\nconsole.log(formatValue(1.956));\r\nconsole.log(formatValue(1.003));\r\nconsole.log(formatValue(1.007));"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":332,"cells":{"_id":{"kind":"string","value":"d333"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"The typical purpose for this style is in use for object construction.\nPerson* pPerson = &(new Person())->setAge(34).setId(55).setName(\"Jack\");\n\ninstead of\nPerson* pPerson = new Person( 34, 55, \"Jack\" );\n\nUsing the second more traditional style one might forget if the first value passed to the constructor was the age or the id? This may also lead to multiple constructors based on the validity of some properties.\nUsing the first style one might forget to set some of the object properties and and may lead bugs where objects are not 'fully' constructed. (A class property is added at a later point but not all the construction locations got updated to call the required setter.)\nAs code evolves I really like the fact that I can use the compiler to help me find all the places where an object is created when changing the signature of a constructor. So for that reason I prefer using regular C++ constructors over this style.\nThis pattern might work well in applications that maintain their datamodel over time according to rules similar to those used in many database applications:\n\n\n*\n\n*You can add a field/attribute to a table/class that is NULL by default. (So upgrading existing data requires just a new NULL column in the database.)\n\n*Code that is not changes should still work the same with this NULL field added.\n\n\nA: Not all the setters, but some of them could return reference to object to be useful.\nkind of\na.SetValues(object)(2)(3)(5)(\"Hello\")(1.4);\n\nI used this once long time ago to build SQL expression builder which handles all the Escapes problems and other things.\nSqlBuilder builder;\n\nbuilder.select( column1 )( column2 )( column3 ).\n where( \"=\" )( column1, value1 )\n ( column2, value2 ).\n where( \">\" )( column3, 100 ).\n from( table1 )( \"table2\" )( \"table3\" );\n\nI wasn't able to reproduce sources in 10 minutes. So implementation is behind the curtains. \n\nA: If your motivation is related to chaining (e.g. Brian Ensink's suggestion), I would offer two comments:\n1.\nIf you find yourself frequently settings many things at once, that may mean you should produce a struct or class which holds all of these settings so that they can all be passed at once. The next step might be to use this struct or class in the object itself...but since you're using getters and setters the decision of how to represent it internally will be transparent to the users of the class anyways, so this decision will relate more to how complex the class is than anything.\n2.\nOne alternative to a setter is creating a new object, changing it, and returning it. This is both inefficient and inappropriate in most types, especially mutable types. However, it's an option that people sometimes forget, despite it's use in the string class of many languages.\n\nA: This technique is used in the Named parameter Idiom.\n\nA: IMO setters are a code smell that usually indicate one of two things:\nMaking A Mountian Out Of A Molehill \nIf you have a class like this:\nclass Gizmo\n{\npublic:\n void setA(int a) { a_ = a; }\n int getA() const { return a_; }\n\n void setB(const std::string & b) { v_ = b; }\n std::string getB() const { return b_; }\nprivate:\n std::string b_;\n int a_;\n};\n\n... and the values really are just that simple, then why not just make the data members public?:\nclass Gizmo\n{\npublic:\n std::string b_;\n int a_;\n};\n\n...Much simpler and, if the data is that simple you lose nothing.\nAnother possibility is that you could be\nMaking A Molehill Out Of A Mountian\nLots of times the data is not that simple: maybe you have to change multiple values, do some computation, notify some other object; who knows what. But if the data is non-trivial enough that you really do need setters & getters, then it is non-trivial enough to need error handling as well. So in those cases your getters & setters should be returning some kind of error code or doing something else to indicate something bad has happened.\nIf you are chaining calls together like this:\nA.doA().doB().doC();\n\n... and doA() fails, do you really want to be calling doB() and doC() anyway? I doubt it.\n\nA: It's a usable enough pattern if there's a lot of things that need to be set on an object.\n class Foo\n {\n int x, y, z;\n public:\n Foo &SetX(int x_) { x = x_; return *this; }\n Foo &SetY(int y_) { y = y_; return *this; }\n Foo &SetZ(int z_) { z = z_; return *this; }\n };\n\n int main()\n {\n Foo foo;\n foo.SetX(1).SetY(2).SetZ(3);\n }\n\nThis pattern replaces a constructor that takes three ints:\n int main()\n {\n Foo foo(1, 2, 3); // Less self-explanatory than the above version.\n }\n\nIt's useful if you have a number of values that don't always need to be set.\nFor reference, a more complete example of this sort of technique is refered to as the \"Named Parameter Idiom\" in the C++ FAQ Lite.\nOf course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not...\n\nA: You can return a reference to this if you want to chain setter function calls together like this:\nobj.SetCount(10).SetName(\"Bob\").SetColor(0x223344).SetWidth(35);\n\nPersonally I think that code is harder to read than the alternative:\nobj.SetCount(10);\nobj.SetName(\"Bob\");\nobj.SetColor(0x223344);\nobj.SetWidth(35);\n\n\nA: I would not think so. Typically, you think of 'setter' object as doing just that.\nBesides, if you just set the object, dont you have a pointer to it anyway?"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":333,"cells":{"_id":{"kind":"string","value":"d334"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I think this is what you are looking for. I added some inline comments to explain what each step is doing. The end result should be all the contacts that can be read by a specified user in your org.\n// add a set with all the contact ids in your org\nList contacts = new List([Select id from Contact]);\nSet contactids = new Set();\nfor(Contact c : contacts)\n contactids.add(c.id);\n\n// using the user record access you can query all the recordsids and the level of access for a specified user\nList ura = new List([SELECT RecordId, HasReadAccess, HasTransferAccess, MaxAccessLevel\n FROM UserRecordAccess\n WHERE UserId = 'theuserid'\n AND RecordId in: contactids\n ] ); \n\n// unfortunatelly you cannot agregate your query on hasReadAccess=true so you'd need to add this step\nSet readaccessID = new Set();\nfor(UserRecordAccess ur : ura)\n{\n if(ur.HasReadAccess==true)\n {\n readaccessID.add(ur.RecordID);\n }\n}\n\n// This is the list of all the Contacts that can be read by the specified user\nList readAccessContact = new List([Select id, name from contact where id in: readaccessID]);\n\n// show the results\nsystem.debug( readAccessContact);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":334,"cells":{"_id":{"kind":"string","value":"d335"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can try to light-weight load in main thread by\nDispatchQueue.global().async {\n UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)\n}\n\nAnd instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":335,"cells":{"_id":{"kind":"string","value":"d336"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"@Wiktor Stribizew is right.\nreplace\n[(\\d)]\n\nwith\n\\(\\d+\\)\n\ntest it here: https://regex101.com/\n\nA: I solve this problem, correct regexp is [ ][(][\\d]*[)]"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":336,"cells":{"_id":{"kind":"string","value":"d337"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"It is because the execution is stuck in the second infinite loop. The condition (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation tags after running it through htmlspecialchars.\nPDF\nThere is no native way for PHP to turn a PDF document into HTML and images. Your best bet is probably ImageMagick, a common image manipulation program. You can basically call convert file.pdf file.png and it will convert the PDF file into a PNG image that you can then serve to the user. ImageMagick is installed on many Linux servers. If it's not available on your host's machine, please ask them to install it, most quality hosts shouldn't have a problem with this.\nDOC & DOCX\nWe're getting a bit more tricky. Again, there's no way to do this in pure PHP. The Docvert extension looks like a possible choice, though it requires OpenOffice be installed as well. I was actually going to recommend plain vanilla OpenOffice/LibreOffice as well, because it can do the job directly from the command line. It's very unlikely that a shared host will want to install this. You'll probably need your own dedicated or virtual private server.\nIn the end, while these options can be made to work, the output quality is not guaranteeable. Overall, this is kind of a bad idea that you should not seriously consider implementing.\n\nA: I am sure libraries and such exist that can do this. Google could probably help you there more than I can.\nFor txt files I would suggest breaking lines after a certain number of characters and putting them inside pre tags.\nI know people will not be happy about this response, but if you are on a Linux environment and have pdf2html installed you could use shell_exec and call pdf2html.\nNote: If you use shell_exec be wary of what you pass to it since it will be executed on the server outside of PHP.\n\nA: I thought I'd just add that pdfs generally view well in a simple embed tag.\nOr use an object so you can have fall backs if it cannot be displayed on the client."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":338,"cells":{"_id":{"kind":"string","value":"d339"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"This part of the code doesn't do anything:\nrapidjson::StringBuffer strbuf;\nrapidjson::Writer writer(strbuf);\nmd_FilesJsonDocument.Accept(writer);\n\nstrbuf contains the json string but it is discarded. I would move this into a separate function and print the conents with std::cout << strbuf;.\nTo write directly to a file:\nstd::ofstream ofs(\"out.json\", std::ios::out);\nif (ofs.is_open()) {\n rapidjson::OStreamWrapper osw(ofs);\n rapidjson::Writer writer(osw);\n md_FilesJsonDocument.Accept(writer);\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":339,"cells":{"_id":{"kind":"string","value":"d340"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I dont see any code for adding the like buttons in your loop. So there is nothing to render.\nFirstly you should configure your Javascript SDK and link it to your Facebook page / application.\nTo configure the Javascript SDK you will need to add something like \n\n\nThis code is detailed here but links your website to your application and configures the SDK to look for Facebook social plugins on the page.\nThen you need to add placeholder elements for the Javscript SDK to parse and render, like the below:\nforeach ($sortedArray as &$filename) {\n #echo '
' . $filename;\n echo '';\n echo '';\n?>\n
\" data-layout=\"button\" data-action=\"like\" data-show-faces=\"true\" data-share=\"false\">
\n';\n}\n\nThese divs have special attributes that the SDK will recognise and use to render the like buttons in the correct place.\nYou should read the documentation here."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":340,"cells":{"_id":{"kind":"string","value":"d341"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"This version of your script should return the entire contents of the page:\nvar page = require('webpage').create();\npage.settings.userAgent = 'SpecialAgent';\npage.open('http://www.httpuseragent.org', function (status) {\n if (status !== 'success') {\n console.log('Unable to access network');\n } else {\n var ua = page.evaluate(function () {\n return document.getElementsByTagName('html')[0].outerHTML;\n });\n console.log(ua);\n }\n phantom.exit();\n});\n\n\nA: There are multiple ways to retrieve the page content as a string:\n\n\n*\n\n*page.content gives the complete source including the markup () and doctype (),\n\n*document.documentElement.outerHTML (via page.evaluate) gives the complete source including the markup (), but without doctype,\n\n*document.documentElement.textContent (via page.evaluate) gives the cumulative text content of the complete document including inline CSS & JavaScript, but without markup,\n\n*document.documentElement.innerText (via page.evaluate) gives the cumulative text content of the complete document excluding inline CSS & JavaScript and without markup.\ndocument.documentElement can be exchanged by an element or query of your choice.\n\nA: To extract the text content of the page, you can try thisreturn document.body.textContent; but I'm not sure the result will be usable.\n\nA: Having encountered this question while trying to solve a similar problem, I ended up adapting a solution from this question like so:\nvar fs = require('fs');\nvar file_h = fs.open('header.html', 'r');\nvar line = file_h.readLine();\nvar header = \"\";\n\nwhile(!file_h.atEnd()) {\n\n line = file_h.readLine(); \n header += line;\n\n}\nconsole.log(header);\n\nfile_h.close();\nphantom.exit();\n\nThis gave me a string with the read-in HTML file that was sufficient for my purposes, and hopefully may help others who came across this. \nThe question seemed ambiguous (was it the entire content of the file required, or just the \"text\" aka Strings?) so this is one possible solution."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":341,"cells":{"_id":{"kind":"string","value":"d342"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Well the obvious answer is that in some situations requests would take longer than 90 seconds for the worker process to return. If you can't imagine a situation where this would be appropriate, then feel free to lower it.\nI wouldn't recommend going too much lower than 30 seconds. I can see situations where you get in recycle loops. However you can do testing and see what makes sense in your situation. I would recommend Siege for load testing to see how your application behaves."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":342,"cells":{"_id":{"kind":"string","value":"d343"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You could try:\n System.out.printf(\"Input an integer: \");\n int a = in.nextInt();\n int k = 0;\n String str_a = \"\";\n \n System.out.print(a);\n while(a > 1)\n {\n if(a % 2 == 0)\n a = a / 2;\n else\n a = 3 * a + 1;\n str_a += \", \" + String.valueOf(a);\n k++;\n }\n System.out.println(\"k = \" + k);\n System.out.println(\"a = \" + str_a);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":343,"cells":{"_id":{"kind":"string","value":"d344"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You're never calling the scalarMultiply method.\n\nA: You're never calling scalarMultiply and the number of the brackets is incorrect.\npublic class warm4{\n\n public static void main(String[] args){\n double[] array1 = {1,2,3,4};\n double scale1 = 3; \n scalarMultiply(array1, scale1);\n }\n\n public static void scalarMultiply(double[] array, double scale){\n for( int i=0; i {\nif (window.ethereum) {\n try {\n await window.ethereum.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: Web3.utils.toHex(chainId) }],\n });\n });\n } catch (error) {\n console.error(error);\n }\n}\nchangeNetwork()\n\n\nA: What if the user doesn't have the required network added? Here is an expanded version which tries to switch, otherwise add the network to MetaMask:\nconst chainId = 137 // Polygon Mainnet\n\nif (window.ethereum.networkVersion !== chainId) {\n try {\n await window.ethereum.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: web3.utils.toHex(chainId) }]\n });\n } catch (err) {\n // This error code indicates that the chain has not been added to MetaMask\n if (err.code === 4902) {\n await window.ethereum.request({\n method: 'wallet_addEthereumChain',\n params: [\n {\n chainName: 'Polygon Mainnet',\n chainId: web3.utils.toHex(chainId),\n nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' },\n rpcUrls: ['https://polygon-rpc.com/']\n }\n ]\n });\n }\n }\n }\n\n\nA: export async function switchToNetwork({\nlibrary,\nchainId,\n}: SwitchNetworkArguments): Promise {\nif (!library?.provider?.request) {\nreturn\n}\nconst formattedChainId = hexStripZeros(\nBigNumber.from(chainId).toHexString(),\n)\ntry {\nawait library.provider.request({\nmethod: 'wallet_switchEthereumChain',\nparams: [{ chainId: formattedChainId }],\n})\n} catch (error) {\n// 4902 is the error code for attempting to switch to an unrecognized chainId\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nif ((error as any).code === 4902) {\nconst info = CHAIN_INFO[chainId]\n await library.provider.request({\n method: 'wallet_addEthereumChain',\n params: [\n {\n chainId: formattedChainId,\n chainName: info.label,\n rpcUrls: [info.addNetworkInfo.rpcUrl],\n nativeCurrency: info.addNetworkInfo.nativeCurrency,\n blockExplorerUrls: [info.explorer],\n },\n ],\n })\n // metamask (only known implementer) automatically switches after a network is added\n // the second call is done here because that behavior is not a part of the spec and cannot be relied upon in the future\n // metamask's behavior when switching to the current network is just to return null (a no-op)\n try {\n await library.provider.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: formattedChainId }],\n })\n } catch (error) {\n console.debug(\n 'Added network but could not switch chains',\n error,\n )\n }\n } else {\n throw error\n }\n}\n\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":345,"cells":{"_id":{"kind":"string","value":"d346"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Think this answer seems to be similar to your question.Hope it provides some insight.\nTime Binding issue in Bootstrap timepicker"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":346,"cells":{"_id":{"kind":"string","value":"d347"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"If the registration is succesful you can simply push the email and password variables to firebase. See code below.\nfunction createUser(email, password, username) {\n ref.createUser({\n email: email,\n password: password\n }, function(error) {\n if (error === null) {\n ... Registration successful\n $activityIndicator.stopAnimating();\n $scope.padding_error = null;\n $scope.error = null;\n ##NEWCODE HERE##\n emailRef = new Firebase(\"/accounts/\"+username+\"/email\")\n passRef = new Firebase(\"/accounts/\"+username+\"/password\")\n emailRef.set(email)\n passRef.set(password)\n logUserIn(email, password);\n } else {\n ... Something went wrong at registration\n }\n }\n });\n }"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":347,"cells":{"_id":{"kind":"string","value":"d348"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can .map over all array entries and then use .reduce on the Object.values of each array entry to sum the values:\n\n\nlet data = [\n {\n \"cost one\": \"118\",\n \"cost two\": \"118\",\n \"cost three\": \"118\"\n },\n {\n \"cost one\": \"118\",\n \"cost two\": \"111\",\n \"cost three\": \"118\"\n },\n {\n \"cost one\": \"120\",\n \"cost two\": \"118\",\n \"cost three\": \"118\"\n }\n];\n\nfunction sumValues(objArr) {\n return objArr.map(curr => {\n return Object.values(curr).reduce((prev, val) => prev += Number(val), 0)\n });\n}\n\nconsole.log(sumValues(data));"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":348,"cells":{"_id":{"kind":"string","value":"d349"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"IDEA is using its own method of instrumenting bytecode to add such validations. For command line builds we provide javac2 Ant task that does the instrumentation (extends standard javac task). If you generate Ant build from IDEA, you will have an option to use javac2.\nWe don't provide similar Maven plug-in yet, but there is third-party version which may work for you (though, it seems to be a bit old).\n\nA: I'd go the AOP way:\nFirst of all you need a javax.validation compatible validator (Hibernate Validator is the reference implementation).\nNow create an aspectj aspect that has a Validator instance and checks all method parameters for validation errors. Here is a quick version to get you started:\npublic aspect ValidationAspect {\n\n private final Validator validator;\n\n {\n final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();\n validator = factory.getValidator();\n\n }\n\n pointcut serviceMethod() : execution(public * com.yourcompany**.*(..));\n\n before() : serviceMethod(){\n final Method method = (Method) thisJoinPoint.getTarget();\n for(final Object arg : thisJoinPoint.getArgs()){\n if(arg!=null) validateArg(arg,method);\n }\n }\n\n private void validateArg(final Object arg, final Method method) {\n final Set> validationErrors = validator.validate(arg);\n if(!validationErrors.isEmpty()){\n final StringBuilder sb = new StringBuilder();\n sb.append(\"Validation Errors in method \").append(method).append(\":\\n\");\n for (final ConstraintViolation constraintViolation : validationErrors) {\n sb.append(\" - \").append(constraintViolation.getMessage()).append(\"\\n\");\n }\n throw new RuntimeException(sb.toString());\n }\n }\n\n}\n\nUse the aspectj-maven-plugin to weave that aspect into your test and / or production code.\nIf you only want this functionality for testing, you might put the aspectj-plugin execution in a profile.\n\nA: There is a maven plugin closely affiliated with the IntelliJ functionality, currently at https://github.com/osundblad/intellij-annotations-instrumenter-maven-plugin. It is discussed under the IDEA-31368 ticket first mentioned in CrazyCoder's answer.\n\nA: You can do annotation validation in your JUnit tests.\nimport java.util.Set;\n\nimport javax.validation.ConstraintViolation;\n\nimport junit.framework.Assert;\n\nimport org.hibernate.validator.HibernateValidator;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;\n\npublic class Temp {\n private LocalValidatorFactoryBean localValidatorFactory;\n\n @Before\n public void setup() {\n localValidatorFactory = new LocalValidatorFactoryBean();\n localValidatorFactory.setProviderClass(HibernateValidator.class);\n localValidatorFactory.afterPropertiesSet();\n }\n @Test\n public void testLongNameWithInvalidCharCausesValidationError() {\n final ProductModel productModel = new ProductModel();\n productModel.setLongName(\"A long name with\\t a Tab character\");\n Set> constraintViolations = localValidatorFactory.validate(productModel);\n Assert.assertTrue(\"Expected validation error not found\", constraintViolations.size() == 1);\n }\n}\n\nIf your poison is Spring, take a look at these Spring Unit Tests"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":349,"cells":{"_id":{"kind":"string","value":"d350"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can use Uncorelated sub queries in $lookup\n\n*\n\n*$match to get the \"notifications.sms\": true\n\n*$lookupto join two collections. We are assigning uId = _id from USER collection. Inside the pipeline, we use $match to find the active :true, and _id=uId\nhere is the script\ndb.USER.aggregate([\n {\n \"$match\": {\n \"notifications.sms\": true\n }\n },\n {\n \"$lookup\": {\n \"from\": \"ALERT\",\n \"let\": {\n uId: \"$_id\"\n },\n \"pipeline\": [\n {\n $match: {\n $and: [\n {\n active: true\n },\n {\n $expr: {\n $eq: [\n \"$user_id\",\n \"$$uId\"\n ]\n }\n }\n ]\n }\n }\n ],\n \"as\": \"joinAlert\"\n }\n }\n])\n\nWorking Mongo playground"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":350,"cells":{"_id":{"kind":"string","value":"d351"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I've done the first half of this before, so we'll start there (convenient, no?). Without knowing to much about your needs I'd recommend the following as a base (you can adjust the column widths as needed):\nCREATE TABLE tree (\n id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n parent_id INT UNSIGNED NOT NULL DEFAULT 0,\n type VARCHAR(20) NOT NULL,\n name VARCHAR(32) NOT NULL,\n PRIMARY KEY (id),\n UNIQUE KEY (parent_id, type, name),\n KEY (parent_id)\n);\n\nWhy did I do it this way? Well, let's go through each field. id is a globally unique value that we can use to identify this element and all the elements that directly depend on it. parent_id lets us go back up through the tree until we reach parent_id == 0, which is the top of the tree. type would be your \"car\" or \"vent\" descriptions. name would let you qualify type, so things like \"Camry\" and \"Driver Left\" (for \"vent\" obviously).\nThe data would be stored with values like these:\nINSERT INTO tree (parent_id, type, name) VALUES\n (0, 'car', 'Camry'),\n (1, 'hvac', 'HVAC'),\n (2, 'vent', 'Driver Front Footwell'),\n (2, 'vent', 'Passenger Front Footwell'),\n (2, 'vent', 'Driver Rear Footwell'),\n (2, 'vent', 'Passenger Rear Footwell'),\n (1, 'glass', 'Glass'),\n (7, 'window', 'Windshield'),\n (7, 'window', 'Rear Window'),\n (7, 'window', 'Driver Front Window'),\n (7, 'window', 'Passenger Front Window'),\n (7, 'window', 'Driver Rear Window'),\n (7, 'window', 'Passenger Rear Window'),\n (1, 'mirrors', 'Mirrors'),\n (14, 'mirror', 'Rearview Mirror'),\n (14, 'mirror', 'Driver Mirror'),\n (14, 'mirror', 'Passenger Mirror');\n\nI could keep going, but I think you get the idea. Just to be sure though... All those values would result in a tree that looked like this:\n(1, 0, 'car', 'Camry')\n | (2, 1, 'hvac', 'HVAC')\n | +- (3, 2, 'vent', 'Driver Front Footwell')\n | +- (4, 2, 'vent', 'Passenger Front Footwell')\n | +- (5, 2, 'vent', 'Driver Rear Footwell')\n | +- (6, 2, 'vent', 'Passenger Rear Footwell')\n +- (7, 1, 'glass', 'Glass')\n | +- (8, 7, 'window', 'Windshield')\n | +- (9, 7, 'window', 'Rear Window')\n | +- (10, 7, 'window', 'Driver Front Window')\n | +- (11, 7, 'window', 'Passenger Front Window')\n | +- (12, 7, 'window', 'Driver Rear Window')\n | +- (13, 7, 'window', 'Passenger Rear Window')\n +- (14, 1, 'mirrors', 'Mirrors')\n +- (15, 14, 'mirror', 'Rearview Mirror')\n +- (16, 14, 'mirror', 'Driver Mirror')\n +- (17, 14, 'mirror', 'Passenger Mirror')\n\nNow then, the hard part: copying the tree. Because of the parent_id references we can't do something like an INSERT INTO ... SELECT; we're reduced to having to use a recursive function. I know, we're entering The Dirty place. I'm going to pseudo-code this since you didn't note which language you're working with.\nFUNCTION copyTreeByID (INTEGER id, INTEGER max_depth = 10, INTEGER parent_id = 0)\n row = MYSQL_QUERY_ROW (\"SELECT * FROM tree WHERE id=?\", id)\n IF NOT row\n THEN\n RETURN NULL\n END IF\n\n IF ! MYSQL_QUERY (\"INSERT INTO trees (parent_id, type, name) VALUES (?, ?, ?)\", parent_id, row[\"type\"], row[\"name\"])\n THEN\n RETURN NULL\n END IF\n parent_id = MYSQL_LAST_INSERT_ID ()\n\n IF max_depth LESSTHAN 0\n THEN\n RETURN\n END IF\n\n rows = MYSQL_QUERY_ROWS (\"SELECT id FROM trees WHERE parent_id=?\", id)\n FOR rows AS row\n copyTreeByID (row[\"id\"], max_depth - 1, parent_id)\n END FOR\n\n RETURN parent_id\nEND FUNCTION\n\nFUNCTION copyTreeByTypeName (STRING type, STRING name)\n row = MYSQL_QUERY_ROW (\"SELECT id FROM tree WHERE parent_id=0 AND type=? AND name=?\", type, name)\n IF NOT ARRAY_LENGTH (row)\n THEN\n RETURN\n END IF\n RETURN copyTreeByID (row[\"id\"])\nEND FUNCTION\n\ncopyTreeByTypeName looks up the tree ID for the matching type and name and passes it to copyTreeByID. This is mostly a utility function to help you copy stuff by type/name.\ncopyTreeByID is the real beast. Fear it because it is recursive and evil. Why is it recursive? Because your trees are not predictable and can be any depth. But it's okay, we've got a variable to track depth and limit it (max_depth). So let's walk through it.\nStart by grabbing all the data for the element. If we didn't get any data, just return. Re-insert the data with the element's type and name, and the passed parent_id. If the query fails, return. Set the parent_id to the last insert ID so we can pass it along later. Check for max_depth being less than zero, which indicates we've reached max depth; if we have return. Grab all the elements from the tree that have a parent of id. Then for each of those elements recurse into copyTreeByID passing the element's id, max_depth minus 1, and the new parent_id. At the end return parent_id so you can access the new copy of the elements.\nMake sense? (I read it back and it made sense, not that that means anything)."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":351,"cells":{"_id":{"kind":"string","value":"d352"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Trying to modify the standard keyboard requires taking a dangerous path into private APIs and a broken app in future iOS versions.\nI think the best solution for you would be to implement the textField:shouldChangeCharactersInRange:replacementString: method of UITextFieldDelegate and replace whitespace characters with the empty string.\nOnce this is implemented, hitting the space bar will simply do nothing."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":352,"cells":{"_id":{"kind":"string","value":"d353"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"autoit may work. i'd use python PIL. i can specify font, convert it to a layer and overlay on top of preexisting image.\nEDIT \nactually imagemagick can be easier than PIL http://www.imagemagick.org/Usage/text/\n\nA: Should not be much of a problem if you have Python and the Python Imaging Library (PIL) installed:\nfrom PIL import Image, ImageFont, ImageDraw\n\nBACKGROUND = '/path/to/background.png'\nOUTPUT = '/path/to/mypicture_{0:04d}.png'\nSTART = 0\nSTOP = 9999\n\n# Create a font object from a True-Type font file and specify the font size.\nfontobj = ImageFont.truetype('/path/to/font/arial.ttf', 24)\n\nfor i in range(START, STOP + 1):\n img = Image.open(BACKGROUND)\n draw = ImageDraw.Draw(img)\n # Write a text over the background image.\n # Parameters: location(x, y), text, textcolor(R, G, B), fontobject\n draw.text((0, 0), '{0:04d}'.format(i), (255, 0, 0), font=fontobj)\n img.save(OUTPUT.format(i))\n\nprint 'Script done!'\n\nPlease consult the PIL manual for other ways of creating font objects for other font formats"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":353,"cells":{"_id":{"kind":"string","value":"d354"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Saw this in the source and something clicked in my head.\nChanging the filter method above to the following gave me the desired results.\n def filter(keys)\n if (scope == object) or scope.has_role?(:super)\n keys\n else\n keys - [:auth_token]\n end\n end\n\nHope this helps anyone else using version 0.9.x"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":354,"cells":{"_id":{"kind":"string","value":"d355"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Put the valid names into a text file (i.e. \"ValidNames.txt\") and use findstr with the /G option. \n02-TestFile.xlsx\n05-TestFile.xlsx\n10-TestFile.xlsx\n...\n\n\n@echo off\n\nfor /f \"delims=\" %%a in ('\n dir /b *.xlsx ^| findstr /vxlg:\"ValidNames.txt\"\n') do move \"%%a\" \"C:\\Temp\\Archive\\Error\""},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":355,"cells":{"_id":{"kind":"string","value":"d356"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"The process.stdout and process.stderr pipes are independent of whatever actual code you're running using Node, so if you want their output sent to files, then make your main entry point script capture stdout/stderr output and that's simply what it'll do for as long as Node.js runs that script.\nYou can add log writing yourself by tapping into process.stdout.on(`data`, data => ...) (and stderr equivalent), or you can pipe their output to a file, or (because why reinvent the wheel?) you can find a logging solution that does that for you, but then that's on you to find, asking others to recommend you one is off topic on Stackoverflow.\nAlso note that stdout/stderr have some sync/async quirks, so give https://nodejs.org/api/process.html#process_a_note_on_process_i_o a read because that has important information for you to be aware of.\n\nA: The example from winston basically solved the issue."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":356,"cells":{"_id":{"kind":"string","value":"d357"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can use this template to get required counts.\n\n \n \n \n \n \n \n \n \n \n \n \n "},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":357,"cells":{"_id":{"kind":"string","value":"d358"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"It turns out the 'table' I was pulling from was in fact a database view, a sort of pseudo-table, which is composed of sql joining together other tables.\nThe error actually lay in the view, rather than in my SQL, which is where the subquery referred to in the error was. Thanks for the help in the comments!"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":358,"cells":{"_id":{"kind":"string","value":"d359"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"The simplest way would be to create a function with the code you want to execute after the execution of the request, and pass this function in parameter of the getfile function :\ngetFile : function( fileName, success ) {\n\n var me = this;\n\n me.db.transaction( function( tx ) {\n tx.executeSql( \"SELECT * FROM content WHERE fileName = '\" + fileName + \"'\", [ ], me.onSuccess, me.onError );\n },\n success\n );\n\n // somehow return results as empty array or array with object\n // I know results need to be transformed \n});\n\nvar r = getFile(\n name,\n function() {\n var r = getFile( name );\n if ( r.length > 0 ) {\n // use it\n }\n else {\n // make AJAX call and store it\n }\n }\n);\n\nOtherwise, the best way to perform is to use Promises to resolve asynchronous issues but you'll have to use a library like JQuery.\nhttp://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":359,"cells":{"_id":{"kind":"string","value":"d360"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You're doing\nSELECT pram = (…) FROM dbo.ClassRelationship a …;\n\nwhere (…) is an expression that is evaluated and then compared to the current value of pram (which was initialised to an empty string). The query does nothing else, there is no destination for this boolean value (comparison result) it computes, you're getting an error.\nYou most likely meant to either perform an assignment\npram = SELECT (…) FROM dbo.ClassRelationship a …;\n\nor use an INTO clause:\nSELECT (…) INTO pram FROM dbo.ClassRelationship a …;\n\n\nNotice that you don't even need pl/pgsql to do this. A plain sql function would do as well:\nCREATE OR REPLACE FUNCTION dbo.fnRepID(pram_ID BIGINT) RETURNS varchar\nLANGUAGE sql\nSTABLE\nRETURN (\n SELECT\n '' ||\n (CASE COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END) ||\n (CASE COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END) ||\n f.NAME ||\n ';'\n FROM dbo.ClassRelationship a\n LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID AND b.Type = 2 AND a.Type = 1\n);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":360,"cells":{"_id":{"kind":"string","value":"d361"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"If you want to use your url params in your state everytime, you can use the resolve function:\n.state('edit', {\n url: '/editItem/:id/:userId',\n templateUrl: 'app/items/edit.html',\n controller: 'editController',\n controllerAs: 'vm',\n resolve: {\n testObject: function($stateParams) {\n return {\n id: $stateParams.id,\n userId: $stateParams.userId\n }\n }\n }\n\n })\n\nNow, you can pass testObject as a dependency to your editController and every time this route is resolved, the values will be available within your controller as testObject.id and testObject.userId\nIf you want to pass an object from one state to the next, use $state.go programatically:\n$state.go('myState', {myParam: {some: 'thing'}})\n\n$stateProvider.state('myState', {\n url: '/myState',\n params: {myParam: null}, ...\n\nThe only other option is to cache, trough Localstorage or cookies"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":361,"cells":{"_id":{"kind":"string","value":"d362"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I wouldn't know what could be going wrong, but I do know an easy solution could be creating a global array and then setting the property to the global array.\nCode:\n\n var array = [ your array] ;\n var cc_cd = {\n List : array,\n Other properties\n };\n\nPlease mark answered or vote to let me know if this helped!"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":362,"cells":{"_id":{"kind":"string","value":"d363"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Try this:\nobject.visible = false; //Invisible\nobject.visible = true; //Visible\n\n\nA: simply use the object traverse method to hide the mesh in three.js.\nIn my code hide the object based on its name\nobject.traverse ( function (child) {\n if (child instanceof THREE.Mesh) {\n child.visible = true;\n }\n});\n\nHere is the working sample for Object show/hide option\nhttp://jsfiddle.net/ddbTy/287/\nI think it should be helpful,.."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":363,"cells":{"_id":{"kind":"string","value":"d364"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Not directly, no. Unless it's in the browser's UA, there's no way of detecting it without some kind of plugin.\n\nA: If you can use VBSCRIPT you can get what you are looking for.\nThe WMI class Win32_OperatingSystem has the properties ServicePackMajorVersion, ServicePackMinorVersion, Name and Version.\nTry samples here: WMI Tasks\nHope this can help"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":364,"cells":{"_id":{"kind":"string","value":"d365"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"how come I can still add content to the file such as shown here Android saving Bitmap to SD card. \n\nThat code creates a new file after deleting the old one.\n\nSo how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there? \n\nCall delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":365,"cells":{"_id":{"kind":"string","value":"d366"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Apparently the source code is correct, but there seem to be problems with the database:\nThe table, corresponding with Class1, contains a column voa_class. The content of that column should be .Class1. In case there's something else, like . or .Class1 (like in my case), the mentioned exception gets generated."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":366,"cells":{"_id":{"kind":"string","value":"d367"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing.\nYou might want to try\n$item_info_tmp=array();\nforeach ($item_info as $ii) {\n if (!isset($item_info_tmp[$ii['folder_id']]))\n $item_info_tmp[$ii['folder_id']]=array();\n $item_info_tmp[$ii['folder_id']][]=$ii;\n}\n$item_info=array_values($item_info_tmp);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":367,"cells":{"_id":{"kind":"string","value":"d368"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Try this simply\n.HTMLBody = \"
\"\n\n\nA: To use a stylesheet instead:\nJust create one using a string and include it in your HTMLBody \nDim sStyleSheet as String\nsStyleSheet = \"\" \n\nor to include your variable\nsStyleSheet = \"\" \n\nSee how you are just building a string?\nThen include it in the HTML:\nsHTML = \"
Hello World
\"\nsStyleSheet = \"\" \n.HTMLBody = sStyleSheet & sHTML\n\nMake sense?"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":368,"cells":{"_id":{"kind":"string","value":"d369"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"That's because (as listed in the documentation) the VALUE() function has not yet been implemented in the PHPExcel calculation engine"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":369,"cells":{"_id":{"kind":"string","value":"d370"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Error: startTime contains string values but got a date (Code: 102,\n Version: 1.2.21)\n\nThe error clearly indicates that you are comparing two different objects one is string and second one is date. So there are two things you can either convert any one into date or string. So to implement the same in a easy way, you can write one category with function which will convert either into date or string and use that method to perform the comparison.\n\nA: You've converted leftDate and arrivedDate to leftDateString and arrivedDateString, but you're still using leftDate and arrivedDate in your query. I think you meant to write:\nPFQuery *query = [PFQuery queryWithClassName:@\"PassData\"];\n[query whereKey:@\"startTime\" greaterThan:leftDateString];\n[query whereKey:@\"timeArrived\" lessThan:arrivedDateString];\n\nin which case you'd no longer get the error since you'd be comparing string to string.\nAlthough I generally recommend that you store and sort your dates with NSDate objects, in this case where your format is in the same descending order of importance as a typical NSDate sort of month, day, hour, then minute, i.e. \"MM-dd hh:mm\", as long as year or seconds don't matter to you and as long as the queried time format matches the database time format, this query should work since greaterThan and lessThan will compare the string objects alphabetically/numerically.\n\nA: I guess for that to work you have to have Date fields in database, then you pass NSDate to whereKey: on iOS."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":370,"cells":{"_id":{"kind":"string","value":"d371"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Grant usage/select to a single table\nIf you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so:\nGRANT CONNECT ON DATABASE mydb TO xxx;\n-- This assumes you're actually connected to mydb..\nGRANT USAGE ON SCHEMA public TO xxx;\nGRANT SELECT ON mytable TO xxx;\n\nMultiple tables/views (PostgreSQL 9.0+)\nIn the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one:\nGRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx;\n\nThis only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future:\nALTER DEFAULT PRIVILEGES IN SCHEMA public\n GRANT SELECT ON TABLES TO xxx;\n\nNote that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow.\nMultiple tables/views (PostgreSQL versions before 9.0)\nTo avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view:\nSELECT 'GRANT SELECT ON ' || relname || ' TO xxx;'\nFROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace\nWHERE nspname = 'public' AND relkind IN ('r', 'v', 'S');\n\nThis should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created.\n\nA: From PostgreSQL v14 on, you can do that simply by granting the predefined pg_read_all_data role:\nGRANT pg_read_all_data TO xxx;\n\n\nA: Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:\ntest=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;\n\n\nA: If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser)\ndb=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser;\nGRANT\ndb=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser;\nGRANT\ndb=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser;\nGRANT\n\nIf your database is using customschema, execute the above but add one more command:\ndb=> ALTER USER readonlyuser SET search_path=customschema, public;\nALTER ROLE\n\n\nA: The not straightforward way of doing it would be granting select on each table of the database:\npostgres=# grant select on db_name.table_name to read_only_user;\n\nYou could automate that by generating your grant statements from the database metadata.\n\nA: Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):\n$ sudo -upostgres psql postgres\npostgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD ' 0.0.0.0/0 md5\" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf\n$ sudo service postgresql reload\n\n\nA: By default new users will have permission to create tables. If you are planning to create a read-only user, this is probably not what you want.\nTo create a true read-only user with PostgreSQL 9.0+, run the following steps:\n# This will prevent default users from creating tables\nREVOKE CREATE ON SCHEMA public FROM public;\n\n# If you want to grant a write user permission to create tables\n# note that superusers will always be able to create tables anyway\nGRANT CREATE ON SCHEMA public to writeuser;\n\n# Now create the read-only user\nCREATE ROLE readonlyuser WITH LOGIN ENCRYPTED PASSWORD 'strongpassword';\nGRANT SELECT ON ALL TABLES IN SCHEMA public TO readonlyuser;\n\nIf your read-only user doesn't have permission to list tables (i.e. \\d returns no results), it's probably because you don't have USAGE permissions for the schema. USAGE is a permission that allows users to actually use the permissions they have been assigned. What's the point of this? I'm not sure. To fix:\n# You can either grant USAGE to everyone\nGRANT USAGE ON SCHEMA public TO public;\n\n# Or grant it just to your read only user\nGRANT USAGE ON SCHEMA public TO readonlyuser;\n\n\nA: Reference taken from this blog:\nScript to Create Read-Only user:\nCREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234' \nNOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';\n\\connect YourDatabaseName;\n\nAssign permission to this read-only user:\nGRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User;\nGRANT USAGE ON SCHEMA public TO Read_Only_User;\nGRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User;\nGRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User;\nREVOKE CREATE ON SCHEMA public FROM PUBLIC;\n\nAssign permissions to read all newly tables created in the future\nALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User;\n\n\nA: I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.\n\nA: I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!\nuser@server:~$ sudo su - postgres\n\ncreate psql user:\npostgres@server:~$ createuser --interactive \nEnter name of role to add: readonly\nShall the new role be a superuser? (y/n) n\nShall the new role be allowed to create databases? (y/n) n\nShall the new role be allowed to create more new roles? (y/n) n\n\nstart psql cli and set a password for the created user:\npostgres@server:~$ psql\npsql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)\nType \"help\" for help.\n\npostgres=# alter user readonly with password 'readonly';\nALTER ROLE\n\nconnect to the target database:\npostgres=# \\c target_database \npsql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)\nYou are now connected to database \"target_database\" as user \"postgres\".\n\ngrant all the needed privileges:\ntarget_database=# GRANT CONNECT ON DATABASE target_database TO readonly;\nGRANT\n\ntarget_database=# GRANT USAGE ON SCHEMA public TO readonly ;\nGRANT\n\ntarget_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;\nGRANT\n\nalter default privileges for targets db public shema:\ntarget_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;\nALTER DEFAULT PRIVILEGES\n\n\nA: Taken from a link posted in response to despesz' link.\nPostgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of:\nhttp://www.postgresql.org/docs/current/interactive/sql-grant.html\nWhere it says: \"There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables).\"\nThis page also discusses use of ROLEs and a PRIVILEGE called \"ALL PRIVILEGES\".\nAlso present is information about how GRANT functionalities compare to SQL standards.\n\nA: CREATE USER username SUPERUSER password 'userpass';\nALTER USER username set default_transaction_read_only = on;"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":371,"cells":{"_id":{"kind":"string","value":"d372"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You could debug the action, then look what exception gets thrown.\nThen you can easily try-catch this line of code and if if fails, you give something different then 500 back.\ntry\n{\n return //...;\n}\ncatch (//your Exception)\n{\n return //... As Example BadRequest or something different\n}\n\nHope it helps."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":372,"cells":{"_id":{"kind":"string","value":"d373"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I would probably write the threshold function the following way, taking advantage of the Timestamp combinator.\n public static IObservable TimeLimitedThreshold\n \n ( this IObservable source\n , int count\n , TimeSpan timeSpan\n , Func,U> selector\n , IScheduler scheduler = null\n )\n {\n var tmp = scheduler == null\n ? source.Timestamp()\n : source.Timestamp(scheduler);\n\n return tmp\n .Buffer(count, 1).Where(b=>b.Count==count)\n .Select(b => new { b, span = b.Last().Timestamp - b.First().Timestamp })\n .Where(o => o.span <= timeSpan)\n .Select(o => selector(o.b.Select(ts=>ts.Value).ToList()));\n }\n\nAs an added convenience when the trigger is fired the complete buffer that satisfies the trigger is provided to your selector function. \nFor example\n var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount();\n IObservable fastKeySequences = keys.TimeLimitedThreshHold\n ( 3\n , TimeSpan.FromSeconds(5)\n , keys => String.Join(\"\", keys)\n );\n\nThe extra IScheduler parameter is given as the Timestamp method has an extra overload which takes one. This might be useful if you want to have a custom scheduler which doesn't track time according to the internal clock. For testing purposes using an historical scheduler can be useful and then you would need the extra overload.\nand here is a fully working test showing the use of a schedular. ( using XUnit and FluentAssertions for the Should().Be(..) )\npublic class TimeLimitedThresholdSpec : ReactiveTest\n{\n\n TestScheduler _Scheduler = new TestScheduler();\n [Fact]\n public void ShouldWork()\n {\n var o = _Scheduler.CreateColdObservable\n ( OnNext(100, \"A\")\n , OnNext(200, \"B\")\n , OnNext(250, \"C\")\n , OnNext(255, \"D\")\n , OnNext(258, \"E\")\n , OnNext(600, \"F\")\n );\n\n var fixture = o\n .TimeLimitedThreshold\n (3\n , TimeSpan.FromTicks(20)\n , b => String.Join(\"\", b)\n , _Scheduler\n );\n\n var actual = _Scheduler\n .Start(()=>fixture, created:0, subscribed:1, disposed:1000);\n actual.Messages.Count.Should().Be(1);\n actual.Messages[0].Value.Value.Should().Be(\"CDE\");\n\n\n }\n\n}\n\nSubscribing and is the following way\nIDisposable subscription = fastKeySequences.Subscribe(s=>Console.WriteLine(s));\n\nand when you want to cancel the subscription ( clean up memory and resources ) you dispose of the subscription. Simply.\nsubscription.Dispose()\n\n\nA: Here's an alternative approach that uses a single delay in favour of buffers and timers. It doesn't give you the events - it just signals when there is a violation - but it uses less memory as it doesn't hold on to too much.\npublic static class ObservableExtensions\n{\n public static IObservable TimeLimitedThreshold(\n this IObservable source,\n long threshold,\n TimeSpan timeLimit,\n IScheduler s)\n {\n var events = source.Publish().RefCount();\n var count = events.Select(_ => 1)\n .Merge(events.Select(_ => -1)\n .Delay(timeLimit, s)); \n return count.Scan((x,y) => x + y) \n .Where(c => c == threshold)\n .Select(_ => Unit.Default); \n }\n}\n\nThe Publish().RefCount() is used to avoid subscribing to the source more than one. The query projects all events to 1, and a delayed stream of events to -1, then produces a running total. If the running total reaches the threshold, we emit a signal (Unit.Default is the Rx type to represent an event without a payload). Here's a test (just runs in LINQPad with nuget rx-testing):\nvoid Main()\n{ \n var s = new TestScheduler();\n var source = s.CreateColdObservable(\n new Recorded>(100, Notification.CreateOnNext(1)),\n new Recorded>(200, Notification.CreateOnNext(2)),\n new Recorded>(300, Notification.CreateOnNext(3)),\n new Recorded>(330, Notification.CreateOnNext(4)));\n\n var results = s.CreateObserver();\n\n source.TimeLimitedThreshold(\n 2,\n TimeSpan.FromTicks(30),\n s).Subscribe(results);\n\n s.Start();\n\n ReactiveAssert.AssertEqual(\n results.Messages,\n new List>> {\n new Recorded>(\n 330, Notification.CreateOnNext(Unit.Default))\n });\n}\n\nEdit\nAfter Matthew Finlay's observation that the above would also fire as the threshold is passed \"on the way down\", I added this version that checks only for threshold crossing in the positive direction:\npublic static class ObservableExtensions\n{\n public static IObservable TimeLimitedThreshold(\n this IObservable source,\n long threshold,\n TimeSpan timeLimit,\n IScheduler s)\n {\n var events = source.Publish().RefCount();\n var count = events.Select(_ => 1)\n .Merge(events.Select(_ => -1)\n .Delay(timeLimit, s)); \n\n return count.Scan((x,y) => x + y) \n .Scan(new { Current = 0, Last = 0},\n (x,y) => new { Current = y, Last = x.Current }) \n .Where(c => c.Current == threshold && c.Last < threshold)\n .Select(_ => Unit.Default); \n }\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":373,"cells":{"_id":{"kind":"string","value":"d374"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"$(document).ready(function(){\n if (location.hash) {\n $('a[href=' + location.hash + ']').tab('show');\n }\n});\n\nthis is the solution i found it here \nhere"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":374,"cells":{"_id":{"kind":"string","value":"d375"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"It looks like you init your manifest on the incorrect version of AOSP. See Downloading the Source for a good explanation of what you need to do to setup AOSP.\nThe main part from there that you want though, is: \nrepo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1\n\nWhich would init your repository on AOSP version 4.0.1_r1. If you want to init on the l-preview branch, it would be:\nrepo init -u https://android.googlesource.com/platform/manifest -b l-preview\n\nJust keep in mind this isn't actually android l's source code, its a GPL update. I am not sure if they have moved it over to using java version 1.7 yet, as I have not personally tried."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":375,"cells":{"_id":{"kind":"string","value":"d376"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Try running the library(caret) again, if the package is loaded, createDataPartition is there. If you still face the issue, check for Caret updates."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":376,"cells":{"_id":{"kind":"string","value":"d377"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"you should fecth a row (at least)\nif (mysqli_connect_errno()) {\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n}\n\n\n$result = mysqli_query($conn, \n \"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value \n FROM `meed` \n WHERE Countries = '$countries'\");\n\nwhile( $row=mysqli_fetch_array($result,MYSQLI_ASSOC);) {\n echo json_encode([ $row['sum_projects'], $row['sum_value'] ] );\n exit;\n}\n\nfor the multiple countries \nAsuming you $_POST['countries'] contains \"'Egypt','Algerie'\" \nthen you could use a query as \n\"SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value \n FROM `meed` \n WHERE Countries IN (\" . $_POST['countries'] . \");\""},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":377,"cells":{"_id":{"kind":"string","value":"d378"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Live Demo\nstd::string line;\n\n// get input from cin stream \nif (std::getline(cin, line)) // check for success\n{\n std::vector words;\n std::string word;\n\n // The simplest way to split our line with a ' ' delimiter is using istreamstring + getline\n std::istringstream stream;\n stream.str(line);\n\n // Split line into words and insert them into our vector \"words\"\n while (std::getline(stream, word, ' '))\n words.push_back(word);\n\n if (words.size() % 2 != 0) // if word count is not even, print error.\n std::cout << \"Word count not even \" << words.size() << \" for string: \" << line;\n else\n {\n //Remove the last word from the vector to make it odd\n words.pop_back();\n\n std::cout << \"Original: \" << line << endl;\n std::cout << \"New:\";\n\n for (std::string& w : words)\n cout << \" \" << w;\n }\n}\n\n\nA: You could write something like this\nint count = -1;\nfor (auto it =input.begin();it!=input.end();){\nif(*it==' '){\n count++;it++;\n if (count%2==0){\n while (it != input.end()){\n if (*it==' ')break;\n it=input.erase (it);\n }\n }else it++;\n }else it++;\n}`"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":378,"cells":{"_id":{"kind":"string","value":"d379"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can encode these as you would encode a binary number, by assigning increasing powers of two for each column. You want to multiply each row by c(1,2,4) and then take the sum.\n# The multiplier, powers of two\nx <- 2^(seq(ncol(df))-1)\nx\n## [1] 1 2 4\n\n# The values\napply(df, 1, function(row) sum(row*x))\n## row1 row2 row3 \n## 4 1 2 \n\nTo add this as a new column:\ndf$new <- apply(df, 1, function(row) sum(row*x))\ndf\n## X1 X2 X3 new\n## row1 0 0 1 4\n## row2 1 0 0 1\n## row3 0 1 0 2\n\n\nA: Try:\n> df\n X1 X2 X3\nrow1 0 0 1\nrow2 1 0 0\nrow3 0 1 0\n> \n> \n> mm = melt(df)\nNo id variables; using all as measure variables\n> \n> mm$new = paste(mm$variable,mm$value,sep='_')\n> \n> mm\n variable value new\n1 X1 0 X1_0\n2 X1 1 X1_1\n3 X1 0 X1_0\n4 X2 0 X2_0\n5 X2 0 X2_0\n6 X2 1 X2_1\n7 X3 1 X3_1\n8 X3 0 X3_0\n9 X3 0 X3_0\n\nmm$new is the column you want. \n\nA: Maybe this is what you want:\n> df$X1 = ifelse(df$X1==0,'green','yellow')\n> df$X2 = ifelse(df$X2==0,'red','blue')\n> df$X3 = ifelse(df$X3==0,'black','white')\n> \n> df\n X1 X2 X3\nrow1 green red white\nrow2 yellow red black\nrow3 green blue black\n> \n> unlist(df)\n X11 X12 X13 X21 X22 X23 X31 X32 X33 \n \"green\" \"yellow\" \"green\" \"red\" \"red\" \"blue\" \"white\" \"black\" \"black\""},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":379,"cells":{"_id":{"kind":"string","value":"d380"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You have quote issues as mentioned, but the main issue is you have inline event handlers in the generated html. That is not a good idea.\nIf you need to add actions to generated elements, use the \ndata-nameinlowercase=\"value\" \n\non the elements, then assign the event handlers using \n$(\"#container\").on(\"event name\",\"element selector\",function() {\n someFunction($(this).data(\"nameinlowercase\"));\n});\n\nwhich will handle future elements too\nIn your case\n'
' \n\nand \n$(\"#caretParentContainerId\").on(\"click\",\".caret\",function() {\n $($(this).data(\"togglename\")).toggle();\n});\n\nwhere caretParentContainerId is the ID of the container that wraps the .caret elements\n\nA: The problem is in the double quotes inside others double quotes, like this\n
  • \n\nIf you want keep your code structure try this:\nmenu += '
  • ' + optStr + '
  • ';\n\nbut I think it's better you do something like this:\nmenu += '
  • ' + optStr + '
  • ';\n\nand create a function like this:\nfunction myFunction(selectName, optStr, optVal) {\n $(\"#\" + selectName + \"-text\").text(optStr);\n $(\"#\" + selectName + \"-menu\").hide();\n $(\"input[name='\" + selectName + \"']\").prop(\"value\", optVal);\n }\n\nWith this is easier to debug and simplifly your code."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":380,"cells":{"_id":{"kind":"string","value":"d381"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can't nest your execute() like that.\nThe best solution is to toss that list of members into an array() once, close your connection, and THEN iterate that array and update each record.\nIt should look like this:\n$select_members_info_stmt->bind_param('ssss', $leader, $member_1, $member_2, $member_3);\n$select_members_info_stmt->execute();\n$select_members_info_stmt->bind_result($selected_username, $level, $experience, $playergold, $required_experience);\n\n$members = array();\nwhile($select_members_info_stmt->fetch())\n{\n // tossing into the array\n $members[] = array(\n 'selected_username' =>$selected_username, \n 'level' => $level, \n 'experience' => $experience, \n 'playergold' => $playergold, \n 'required_experience' => $required_experience\n );\n}\n$select_members_info_stmt->close();\n\n// Now iterate through the array and update the user stats\nforeach ($members as $m) {\n if($update_user_stats_stmt = $mysqli->prepare(\"UPDATE members SET level = ?, experience = ?, playergold = ? WHERE username = ?\"))\n {\n // Note that you need to use $m['selected_username'] here. \n $update_user_stats_stmt->bind_param('iiiiis', $new_level, $new_experience, $new_gold, $now, $cooldown, $m['selected_username']);\n $update_user_stats_stmt->execute();\n if($update_user_stats_stmt->affected_rows == 0)\n {\n echo '
    Because of a system error it is impossible to perform a task, we apologize for this inconvience. Try again later.
    ';\n }\n $update_user_stats_stmt->close();\n }\n else \n {\n printf(\"Update user stats error: %s
    \", $mysqli->error);\n }\n\n}\n\n\nA: You cannot nest actively running prepared statements on the same connection to mysql. Once you call execute() on any statement you cannot run another one on the same connection until that prepared statement is closed. Any fetches on the first prepared statement will fail once you start executing on the second one.\nOnly one 'live' statement can be prepared and running on the mysql server per connection\nIf you really need to nest your prepared statements, you could establish 2 separate mysqli connections."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":381,"cells":{"_id":{"kind":"string","value":"d382"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I assume the delivery_confirmation method in reality returns a Mail object. The problem is that ActionMailer will call the deliver method of the mail object. You've set an expectation stubbing out the delivery_confirmation method but you haven't specified what should be the return value. Try this\nmail_mock = double(deliver: true)\n# or mail_mock = double(deliver_now: true)\nexpect(mail_mock).to receive(:deliver)\n# or expect(mail_mock).to receive(:deliver_now)\nallow(OrderMailer).to receive(:delivery_confirmation).with(order).and_return(mail_mock)\n# the rest of your test code\n\n\nA: If I got you right,\nexpect_any_instance_of(OrderMailer).to receive(:delivery_confirmation).with(order)\n\nwill test the mailer instance that will receive the call.\nFor more precision you may want to set up your test with the particular instance of OrderMailer (let's say order_mailer) and write your expectation the following way\nexpect(order_mailer).to receive(:delivery_confirmation).with(order)"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":382,"cells":{"_id":{"kind":"string","value":"d383"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"When you are in the app on another screen and press back button that time you go to the back screen. and when your screen is home or login, and that time within two seconds you press twice the time back button app is closed.\npublic astTimeBackPress = 0;\npublic timePeriodToExit = 2000;\n\nconstructor(\n public toastController: ToastController,\n private platform: Platform,\n private nav: NavController,\n private router: Router,\n ) { }\n\nhandleBackButton() {\n this.platform.backButton.subscribe(() => {\n if (this.loaderOff) {\n document.addEventListener(\n 'backbutton',\n () => {},\n false);\n } else {\n if (\n this.router.url === '/tabs/home' ||\n this.router.url === '/signin'\n ) {\n if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {\n navigator['app'].exitApp();\n } else {\n this.presentToast('Press again to exit');\n this.lastTimeBackPress = new Date().getTime();\n }\n } else {\n this.nav.back();\n }\n }\n });\n}\n\nasync presentToast(msg, color = 'dark') {\n const toast = await this.toastController.create({\n color,\n message: msg,\n duration: 3000,\n showCloseButton: true,\n closeButtonText: 'Close',\n });\n toast.present();\n }\n\n\nA: public void callAlert(){\n AlertDialog.Builder builder1 = new AlertDialog.Builder(appCompatActivity);\n builder1.setMessage(\"Do you want to close.\");\n builder1.setCancelable(true);\n\n builder1.setPositiveButton(\n \"Yes\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.cancel();\n finish();\n }\n });\n\n builder1.setNegativeButton(\n \"No\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.cancel();\n }\n });\n\n AlertDialog alert11 = builder1.create();\n alert11.show();\n}\n\n@Override\npublic boolean onKeyDown(int keyCode, KeyEvent event) {\n\n if (keyCode == KeyEvent.KEYCODE_BACK) {\n callAlert();\n return true;\n }\n return super.onKeyDown(keyCode, event);\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":383,"cells":{"_id":{"kind":"string","value":"d384"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You have following solution may be any one help you.\n1) Add in .css and meta tags as follow.\nhtml {\n -webkit-text-size-adjust: none; /* Never autoresize text */\n}\n\nand meta tags as follow\n\n\n2) You can also inject both into an existing website, using this javascript code as follow.\nvar style = document.createElement(\\\"style\\\"); \ndocument.head.appendChild(style); \nstyle.innerHTML = \"html{-webkit-text-size-adjust: none;}\";\nvar viewPortTag=document.createElement('meta');\nviewPortTag.id=\"viewport\";\nviewPortTag.name = \"viewport\";\nviewPortTag.content = \"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\";\ndocument.getElementsByTagName('head')[0].appendChild(viewPortTag);\n\nand Use UIWebViewDelegate (webViewDidFinishLoad) method\n- (void)webViewDidFinishLoad:(UIWebView *)webView{\n\n NSString *javascript = @\"var style = document.createElement(\\\"style\\\"); document.head.appendChild(style); style.innerHTML = \\\"html{-webkit-text-size-adjust: none;}\\\";var viewPortTag=document.createElement('meta');viewPortTag.id=\\\"viewport\\\";viewPortTag.name = \\\"viewport\\\";viewPortTag.content = \\\"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\\\";document.getElementsByTagName('head')[0].appendChild(viewPortTag);\";\n [webView stringByEvaluatingJavaScriptFromString:javascript];\n\n}\n\n\nA: you can implement webView delegate and change font when load webView.\nfunc webViewDidStartLoad(webView : UIWebView) {\n //your code \n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":384,"cells":{"_id":{"kind":"string","value":"d385"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You declared the generic type bound in the wrong place.\nIt should be declared within the declaration of the generic type parameter:\npublic final T getObject(Class myObjectClass)\n{\n //...\n}"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":385,"cells":{"_id":{"kind":"string","value":"d386"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"After many things, I could figure out the solution. In fact, there is no problem to make a window 100 x 50 px or even smaller. The problem is that I had to close the window of the simulator before run again. In my case, such a small window had no Title bar and no close button. So I had to publish with the Title bar, close it, stop the running and then I could run again with the new size and position I give to the window. \nSo, without closing the window in the simulator it is not possible to see the results of a new size."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":386,"cells":{"_id":{"kind":"string","value":"d387"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"I think inheritance is a good approach to this problem.\nI can think of two down sides:\n\n\n*\n\n*It is possible to create additional columns to the inheritance children. If you control DDL, you can probably prevent that.\n\n*You still have to create and modify indexes on all inheritance children individually.\nIf you are using PostgreSQL v11 or later, you could prevent both problems by using partitioning. The individual tables would then be partitions of the “template” table. This way, you can create indexes centrally by creating a partitioned index on the template table. The disadvantage (that may make this solution impossible) is that you need a partitioning key column in the table."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":387,"cells":{"_id":{"kind":"string","value":"d388"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You first need to get a list of the user friends calling /me?fields=friends. Then, you can only add their id to the picture urls just like you did with the user:\n"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":388,"cells":{"_id":{"kind":"string","value":"d389"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene.\n// Update is called once per frame\nvoid Update()\n{\n Vector3 newpos = Playerposition.position + cameraoffset;\n transform.position = newpos;\n}\n\nIf this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update()."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":389,"cells":{"_id":{"kind":"string","value":"d390"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You likely have overridden get_api_root_view without providing the api_url argument since it's already part of DRF: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L292\n\nA: I had the same error. I found I had an older version of drf-extensions. I have a feeling drf-extensions overrides the get_api_root_view method, and when it's not in sync with your version of Django Rest Framework, this can cause a problem (ie. drf-extensions is passing a parameter that DRF no longer expects, but in previous versions was acceptable).\nIf it's not drf-extensions specifically, it's probably something else that's overriding get_api_root_view as Linovia suggested."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":390,"cells":{"_id":{"kind":"string","value":"d391"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You probably have register_globals turned on so $classes gets mixed with $_SESSION['classes'] at some point.\nYou should turn them off. (Here's why.)\nOr, if turning them off is not possible due to whatever reason, change variable names.\n\nA: Got it!\nHere's my new code:\n\".$classBeingTaught.\"\";\n }\n?>"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":391,"cells":{"_id":{"kind":"string","value":"d392"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Your code uses the old and deprecated not/1 predicate, which apparently is not supported in the Prolog system you're using, hence the existence error. Use instead the standard \\+/1 predicate/prefix operator:\nis_not_immune_to(Pkmn, AtkType) :- \n is_type(Pkmn, Type), \\+ immune(Type, AtkType).\n\nWith this change, you get for your sample call:\n| ?- is_not_immune_to(charizard, ground).\n\ntrue ? ;\n\nno"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":392,"cells":{"_id":{"kind":"string","value":"d393"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"Your code is sound. You just need to include this in the beginning of your ui:\nui <- fluidPage(\n\n useShinyjs(), # add this\n\n# rest of your ui code\n)"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":393,"cells":{"_id":{"kind":"string","value":"d394"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"use this \n$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);\n\ninstead of\n$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);\n\ni think it is better to use CURL instead of socket"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":394,"cells":{"_id":{"kind":"string","value":"d395"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"If you want the Edit control to be different than the standard control, you should use the \"EditItemTemplate\". This will allow the edit row to have different controls, values, etc... when the row's mode changes.\nExample:\n \n \n \n \n \n \n \n \n \n \n\n\nA: I guess you could loop through all the rows of the GridView and enable the checkboxes something like below:\n protected void grd_Bookcode_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n if (e.CommandName == \"Edit\")\n {\n for (int index = 0; index < GridView1.Rows.Count; index++)\n {\n CheckBox chk = grd_Bookcode.Rows[index].FindControl(\"CheckBox\" + index + 1) as CheckBox;\n chk.Enabled = true;\n }\n }\n }\n\nHope this helps!!"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":395,"cells":{"_id":{"kind":"string","value":"d396"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"To correct this problem I had to\n\n*\n\n*uninstall app on Android phone (important step)\n\n*Unload Android Project from solution explorer\n\n*This brings up the project file code now search code for\nfalse\n\n*Change false to true save\n\n*reload project problem solved.\n\nNote leave fast deploy checked.\n\nA: Go to >> Solution Properties>> Android Options>> Uncheck \"Use Fast Deployment(debug mode only)\"\n\nA: I had the same issue recently after adding images to my project found out that I had upper case letters as a name SomePicture.png renaming all images to lower case solved it.\n\nA: @AlwinBrabu, I think you meant \"Project Properties\" -> Android Options -> Uncheck Fast Deployment(debug mode only).\nThis worked for me, although this is a workaround. I do not consider it a solution.\n\nA: To solve this, I had to right-click on the Android project in the Solution Explorer, then in Options -> Android Build uncheck the Fast Assembly Deployment option.\nThen deploy the project on the Android emulator.\nBut after deploying it once, I went back to the settings and checked (i.e. ticked) the Fast Assembly Deployment option, and subsequent deploys worked fine.\nI'm running Visual Studio for Mac 2022 version 17.0.1 (build 72)."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":396,"cells":{"_id":{"kind":"string","value":"d397"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"It is possible but your type must be global \ncreate type array_t is varray(2) of int;\n\nThen use array as a table (open p for only for compiling)\n declare\n array_test array_t := array_t(10,11);\np sys_refcursor;\n begin\nopen p for\n select * from STATISTIK where abschluss1 in (select column_value from table(array_test ));\n end;"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":397,"cells":{"_id":{"kind":"string","value":"d398"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You can try via pd.to_numeric() and then fill NaN's:\ndf['Feature2']=pd.to_numeric(df['Feature2'], errors=\"coerce\").fillna(df['Feature2'])\n\nOR\ngo with the where() condition by filling those NaN's with fillna() in your condition ~df.Feature2.str.isnumeric():\ndf['Feature2']=df['Feature2'].where(~df.Feature2.str.isnumeric().fillna(True),\n pd.to_numeric(df.Feature2, errors=\"coerce\").astype(\"Int64\")\n )"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":398,"cells":{"_id":{"kind":"string","value":"d399"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"You seem to be saying that you want your function to take a variable number of separate arrays as arguments, and then find the maximum number within any of those arrays.\nIf so, you can say [].concat(...arguments) to create a single new array with all of the values from the individual arrays that were arguments, then use the spread operator to pass that new array to Math.max(). (You don't need a loop.)\n\n\nvar firstArr = [1,2,3,4,5];\r\nvar secondArr = [6,7,8,9];\r\n\r\nfunction myFun() {\r\n var resl = Math.max(...[].concat(...arguments));\r\n console.log(\"The maximum value is \" + resl);\r\n}\r\n\r\nmyFun(firstArr, secondArr);\n\n\n\nA: It sounds like what you are trying to do is\nfunction myFun(...arrays) {\n const allValues = [].concat(...arrays);\n return Math.max(...allValues);\n}\nconsole.log(\"The maximum value is \" + myFun([1,2,3,4,5], [6,7,8,9]));\n\nHowever I would recommend to avoid spread syntax with potentially large data, and go for\nfunction myFun(...arrays) {\n return Math.max(...arrays.map(arr => Math.max(...arr)));\n}\n\nor even better\nfunction myFun(...arrays) {\n return arrays.map(arr => arr.reduce(Math.max)).reduce(Math.max);\n}\n\n\nA: You can use rest element at function declaration, pass an array of arrays each preceded by spread element to function parameters and spread element within function\nfunction myFun(...arr) {\n return Math.max.apply(Math, ...arr)\n}\n\nmyFun([...firstArr, ...secondArr /*, ...nArr*/ ]);"},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}},{"rowIdx":399,"cells":{"_id":{"kind":"string","value":"d400"},"partition":{"kind":"string","value":"train"},"text":{"kind":"string","value":"The web service does not enable the type-based optimizations by default. So to get the equivalent functionality:\njava -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS\n --use_types_for_optimization=false\n --js /code/built.js --js_output_file compiledCode.js\n\nThe web service also assumes any undefined symbol is an external library. For this reason it is not recommended for production use."},"language":{"kind":"string","value":"unknown"},"title":{"kind":"string","value":""}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":3,"numItemsPerPage":100,"numTotalItems":19931,"offset":300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjI2Njk1Niwic3ViIjoiL2RhdGFzZXRzL0NvSVItUmV0cmlldmFsL3N0YWNrb3ZlcmZsb3ctcWEtcXVlcmllcy1jb3JwdXMiLCJleHAiOjE3NTYyNzA1NTYsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.HLBuGOKkpW_FFi4SRBixZ4MATsWiCrDmuVnZZHttHwBqJkpARsNewLn-vVBO39sN36ob4FM8Lf7XfnYHW6RNCA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    _id
    stringlengths
    2
    6
    partition
    stringclasses
    3 values
    text
    stringlengths
    4
    46k
    language
    stringclasses
    1 value
    title
    stringclasses
    1 value
    d301
    train
    The trick was to put the start character symbol '^' before the value being searched on and end character symbol '$' after the value. Without giving these two symbols the regex will always return nothing. Fixed portion: var table = null; $(document).ready(function(){ table = $('#searchTable').DataTable( { "sPaginationType": "full_numbers", "iDisplayLength": 5 } ); table.columns(0).search('^0$',true,false).draw(); } ); A: In case somebody else face this problem. In my case the problem was related to searching for string characters that have special meaning in a regular expression (eg. "AC (JLHA2) - GB/T1179-2008" will give nothing even if the data exists in the table). I was able to fix this by using $.fn.dataTable.util.escapeRegex() to escape all special characters. Here is the fix: var table = null; $(document).ready(function(){ table = $('#searchTable').DataTable( { "sPaginationType": "full_numbers", "iDisplayLength": 5 } ); // Escape the expression so we can perform a regex match var val = $.fn.dataTable.util.escapeRegex('AC (JLHA2) - GB/T1179-2008'); table.columns(0).search(val ? '^' + val + '$' ; '', true, false).draw(); } );
    unknown
    d302
    train
    Try Regex: (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>[\S]+,(?: [\S]+,?)*){0,4} Demo Regex in the question had a capturing group (Group 2) for (\d{4,10}\s). it is changed to a non capturing group now (?:\d{4,10}\s) A: See regex in use here. (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}(?:\.\d{0,3}){3}).*\((?P<peer_rid>\d{0,3}(?:\.\d{0,3}){3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2}) * *You were getting group 2 because your as_path group contained a group. I changed that to a non-capturing group. *I changed attribs to \S+(?:,\s+\S+){2} * *This will match any non-space character one or more times \S+, followed by the following exactly twice: * *,\s+\S+ the comma character, followed by the space character one or more times, followed by any non-space character one or more times *I changed peer_addr and peer_rid to \d{0,3}(?:\.\d{0,3}){3} instead of \d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}. This is a preference, but shortens the expression. Without that last modification, you can use the following regex (it performs slightly better anyway (as seen here): (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2}) You can also improve the performance by using more specific tokens as the following suggests (notice I also added the x modifier to make it more legible) and as seen here: (?P<as_path>\d{4,10}(?:\s\d{4,10}){0,19})\s+ (?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})[^)]* \((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+ .*localpref\s(?P<local_pref>\d+),\s+ (?P<attribs>\w+(?:,\s+\w+){2}) A: You get that separate group because your are repeating a capturing group were the last iteration will be the capturing group, in this case 88945 You could make it non capturing instead (?: For the second part you could use an alternation to exactly match one of the options (?:valid|external|best) Your pattern might look like: (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>(?:valid|external|best)(?:,\s{0,4}(?:valid|external|best))+) regex101 demo
    unknown
    d303
    train
    Modern PC's use floating point numbers to calculate non-integral values. These come in two standardized variants: float and double, where the latter is twice the size of the former. Matlab, by default uses (complex) doubles for all its calculations. You can force it to use float (or as Matlab calls them, single) by specifiying the type: a = single([20, 25.0540913632159, 16.2750000000000, 3.08852992798468]); This should use half the memory, and you lose some precision that may or may not be important in your application. Make sure the optimization is worth it before doing this, as execution speed may even be slower (due to builtin functions only operating on double, hence requiring two conversions extra).
    unknown
    d304
    train
    After inspection of Laravel's Http Request and Route classes, I found the route() and setAction() methods could be useful. So I created a middleware to handle this: <?php namespace App\Http\Middleware; class Ajax { public function handle($request, Closure $next) { // Looks for the value of request parameter called "ajax" // to determine controller's method call if ($request->ajax()) { $routeAction = $request->route()->getAction(); $ajaxValue = studly_case($request->input("ajax")); $routeAction['uses'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['uses']); $routeAction['controller'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['controller']); $request->route()->setAction($routeAction); } return $next($request); } } Now my route looks like: Route::any('some/page/', ['as' => 'some-page', 'middleware'=>'ajax', 'uses' => 'SomePageController@index']); And correctly hits my controller methods (without disturbing Laravel's normal flow): <?php namespace App\Http\Controllers; class SomePageController extends Controller { public function index() { return view('some.page.index'); } public function ajaxMyAction(Requests\SomeFormRequest $request){ die('Do my action here!'); } public function ajaxMyOtherAction(Requests\SomeFormRequest $request){ die('Do my other action here!'); } ... I think this is a fairly clean solution. A: You can't make this dispatch in the routing layer if you keep the same URL. You have two options : * *Use different routes for your AJAX calls. For example, you can prefix all your ajax calls by /api. This is a common way : Route::group(['prefix' => 'api'], function() { Route::get('items', function() { // }); }); *If the only different thing is your response format. You can use a condition in your controller. Laravel provides methods for that, for example : public function index() { $items = ...; if (Request::ajax()) { return Response::json($items); } else { return View::make('items.index'); } } You can read this http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax and this http://laravel.com/docs/5.0/routing#route-groups if you want more details.
    unknown
    d305
    train
    Your var = xmlhttp; is outside of switchText scope and so it's undefined and throws an error. Try this <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function switchText() {loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> A: I think the issue you have is that you have not validated your code, even down to whether you have matching curly braces or not (hint, you do not!) moving the open and send commands back into the first function and removing the extra curly brace shoudl work. the below should work : <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } function switchText() { loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> hope that helps Olly A: I think the problem is with the following line in ajax_object.html file: if (xmlhttp.readyState==4 && xmlhttp.status==200) If you run the file with the above line and look at the 'Show Page Source', it will be apparent that the 'Request & Response' header has its -- Status and Code --- set to nothing So, delete the line and you will get: <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script--> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html> If you run this code it will output the ajax_info.txt file.
    unknown
    d306
    train
    From your images it seems like that you don't set the top constraint of the top view to top safeAreaLayoutGuide instead you set it to superView here , also you can't set the top of the button to safeArea , as it's only appears for direct subviews of thw main vc's view not to nested subviews
    unknown
    d307
    train
    yum -y remove php* to remove all php packages then you can install the 5.6 ones. A: Subscribing to the IUS Community Project Repository cd ~ curl 'https://setup.ius.io/' -o setup-ius.sh Run the script: sudo bash setup-ius.sh Upgrading mod_php with Apache This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section. Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted. sudo yum remove php-cli mod_php php-common Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted. sudo yum install mod_php70u php70u-cli php70u-mysqlnd Finally, restart Apache to load the new version of mod_php: sudo apachectl restart You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl: systemctl status httpd
    unknown
    d308
    train
    Try <tr ng-repeat="pelanggan in t.pelangganArr"> A: In your controller declare pelangganArr as $scope.pelangganArr. Only scope variables are recognised by angular in the DOM and provide 2 way binding.
    unknown
    d309
    train
    I suppose com.fasterxml.jackson's @JsonIgnore annotation should help. public class Entity { private String name; @JsonIgnore private String entityType; @JsonIgnore private Entity rootEntity; } A: In Json-lib you have a JsonConfig to specify the allowed fields: JsonConfig jsonConfig=new JsonConfig(); jsonConfig.registerPropertyExclusion(Entity.class,"rootEntity"); jsonConfig.registerPropertyExclusion(Entity.class,"entityType"); JSON json = JSONSerializer.toJSON(objectToWrite,jsonConfig);
    unknown
    d310
    train
    While the Dropbox API was designed with the intention that each user would link their own Dropbox account, in order to interact with their own files, it is technically possible to connect to just one account. We generally don't recommend doing so, for various technical and security reasons, but those won't apply if you're the only user anyway. So, there are two ways to go about this: 1) Implement the normal app authorization flow as documented, and log in and authorize the app once per app installation. The SwiftyDropbox SDK will store the resulting access token for you, which you can programmatically re-use after that point each time using authorizedClient. 2) Manually retrieve an access token for your account and hard code it in to the app, using the DropboxClient constructor shown here under "Initialize with manually retrieved auth token".
    unknown
    d311
    train
    Per the Dockerfile ARG docs, The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg = flag. in order to accept an argument as part of the build, we use --build-arg. Dockerfile ENV docs: The ENV instruction sets the environment variable to the value . We also need to include an ENV statement because the CMD will be executed after the build is complete, and the ARG will not be available. FROM busybox ARG ENVIRONMENT ENV ENVIRONMENT $ENVIRONMENT CMD echo $ENVIRONMENT will cause an environment variable to be set in the image, so that it is available during a docker run command. docker build -t test --build-arg ENVIRONMENT=awesome_environment . docker run -it test This will echo awesome_environment. A: Try changing your RUN command do this: RUN npm run ng build --configuration=$ENVIRONMENT This should work. Check here Thanks.
    unknown
    d312
    train
    You declare i within the for loop without initialising it. This is the reason you get 'weird values'. In order to rectify, you need to write: for(int i=0; i<5; i++) Hope this helps! A: Just copy the bytes: memcpy(newID, chID, 4); A: One more note that it seems some people have overlooked here: if chId is length 4 then the loop bounds are i=0;i<4. That way you get i=0,1,2,3. (General programming tip, unroll loops in your head when possible. At least until you are satisfied that the program really is doing what you meant it to.) NB: You're not copying chId into a string. You're copying it into a char array. That may seem like semantics, but "string" names a data type in C++ which is distinct from an array of characters. Got it right in the title, wrong in the question description.
    unknown
    d313
    train
    No such thing is built in, because it doesn't need to be. Unlike destructuring, which is fairly involved, constructing maps is very simple in Clojure, and so fancy ways of doing it are left for ordinary libraries. For example, I long ago wrote flatland.useful.map/keyed, which mirrors the three modes of map destructuring: (let [transforms {:keys keyword :strs str :syms identity}] (defmacro keyed "Create a map in which, for each symbol S in vars, (keyword S) is a key mapping to the value of S in the current scope. If passed an optional :strs or :syms first argument, use strings or symbols as the keys instead." ([vars] `(keyed :keys ~vars)) ([key-type vars] (let [transform (comp (partial list `quote) (transforms key-type))] (into {} (map (juxt transform identity) vars)))))) But if you only care about keywords, and don't demand a docstring, it could be much shorter: (defmacro keyed [names] (into {} (for [n names] [(keyword n) n]))) A: I find that I quite frequently want to either construct a map from individual values or destructure a map to retrieve individual values. In the Tupelo Library I have a handy pair of functions for this purpose that I use all the time: (ns tst.demo.core (:use demo.core tupelo.core tupelo.test)) (dotest (let [m {:a 1 :b 2 :c 3}] (with-map-vals m [a b c] (spyx a) (spyx b) (spyx c) (spyx (vals->map a b c))))) with result ; destructure a map into values a => 1 b => 2 c => 3 ; construct a map (vals->map a b c) => {:a 1, :b 2, :c 3} P.S. Of course I know you can destructure with the :keys syntax, but it always seemed a bit non-intuitive to me.
    unknown
    d314
    train
    As @Louwki said, you can use a Trait to do that, in my case I did something like this: trait SaveToUpper { /** * Default params that will be saved on lowercase * @var array No Uppercase keys */ protected $no_uppercase = [ 'password', 'username', 'email', 'remember_token', 'slug', ]; public function setAttribute($key, $value) { parent::setAttribute($key, $value); if (is_string($value)) { if($this->no_upper !== null){ if (!in_array($key, $this->no_uppercase)) { if(!in_array($key, $this->no_upper)){ $this->attributes[$key] = trim(strtoupper($value)); } } }else{ if (!in_array($key, $this->no_uppercase)) { $this->attributes[$key] = trim(strtoupper($value)); } } } } } And in your model, you can specify other keys using the 'no_upper' variable. Like this: // YouModel.php protected $no_upper = ['your','keys','here']; A: Was a lot easier than I through. Solution that is working for me using traits, posting it if anyone also run into something like this. <?php namespace App\Traits; trait SaveToUpper { public function setAttribute($key, $value) { parent::setAttribute($key, $value); if (is_string($value)) $this->attributes[$key] = trim(strtoupper($value)); } } } UPDATE: For Getting values as upper case you can add this to the trait or just add it as a function in the model: public function __get($key) { if (is_string($this->getAttribute($key))) { return strtoupper( $this->getAttribute($key) ); } else { return $this->getAttribute($key); } }
    unknown
    d315
    train
    So you want each group ordered internally, and the groups order by the latest value, right? Okay, I think we can do that... var query = from action in actions group action by action.Uid into g orderby g.Max(action => action.Created) descending select new { Uid = g.Key, Actions = g.OrderByDescending(action => action.Created) }; foreach (var group in query) { Console.WriteLine("Uid: {0}", group.Uid); foreach (var action in group.Actions) { Console.WriteLine(" {0}: {1}", action.Created, action.ActionId); } } A: For the SQL, get the sort column in the SELECT statement SELECT *, (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) AS MaxCreated FROM actions a ORDER BY MaxCreated desc, a.created desc or SELECT * FROM actions a ORDER BY (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) desc, a.created desc (just fixed an error in the first query) Here's my linq: var actions = (from a in actions orderby ((from a2 in actions where a2.UserID == a.UserID select a2.created).Max ()) descending, a.created descending select a);
    unknown
    d316
    train
    As it turns out, with the default OpenSSL (which is bundled with node, but if you've built your own, it is possible to configure different engines), the algorithm to generate random data is exactly the same for both randomBytes (RAND_bytes) and pseudoRandomBytes (RAND_pseudo_bytes). The one and only difference between the two calls depends on the version of node you're using: * *In node v0.12 and prior, randomBytes returns an error if the entropy pool has not yet been seeded with enough data. pseudoRandomBytes will always return bytes, even if the entropy pool has not been properly seeded. *In node v4 and later, randomBytes does not return until the entropy pool has enough data. This should take only a few milliseconds (unless the system has just booted). Once the the entropy pool has been seeded with enough data, it will never "run out," so there is absolutely no effective difference between randomBytes and pseudoRandomBytes once the entropy pool is full. Because the exact same algorithm is used to generate randrom data, there is no difference in performance between the two calls (one-time entropy pool seeding notwithstanding). A: Just a clarification, both have the same performance: var crypto = require ("crypto") var speedy = require ("speedy"); speedy.run ({ randomBytes: function (cb){ crypto.randomBytes (256, cb); }, pseudoRandomBytes: function (cb){ crypto.pseudoRandomBytes (256, cb); } }); /* File: t.js Node v0.10.25 V8 v3.14.5.9 Speedy v0.1.1 Tests: 2 Timeout: 1000ms (1s 0ms) Samples: 3 Total time per test: ~3000ms (3s 0ms) Total time: ~6000ms (6s 0ms) Higher is better (ops/sec) randomBytes 58,836 ± 0.4% pseudoRandomBytes 58,533 ± 0.8% Elapsed time: 6318ms (6s 318ms) */ A: If it's anything like the standard PRNG implementations in other languages, it is probably either not seeded by default or it is seeded by a simple value, like a timestamp. Regardless, the seed is possibly very easily guessable.
    unknown
    d317
    train
    EntityManager.executeQueryLocally is a synchronous function and you can use its result immediately. i.e. var myEntities = myEntityManager.executeQueryLocally(myQuery); Whereas EntityManager.executeQuery is an asynchonous function ( even if the query has a 'using' call that specifies that this is a local query). So you need to call it like this: var q2 = myQuery.using(breeze.FetchStrategy.FromLocalCache); myEntityManager.executeQuery(q2).then(function(data) { var myEntities = data.results; }); The idea behind this is that with executeQuery you treat all queries in exactly the same fashion, i.e. asynchronously, regardless of whether they are actually asynchronous under the hood. If you want to create an EntityManager that does not go to the server for metadata you can do the following: var ds = new breeze.DataService({ serviceName: "none", hasServerMetadata: false }); var manager = new breeze.EntityManager({ dataService: ds });
    unknown
    d318
    train
    I'm assuming that you have started with the following as it looks similar to the URL that you have created http://docs.aws.amazon.com/AWSECommerceService/latest/GSG/SubmittingYourFirstRequest.html Double check the timestamp as the page mentions it can't be more than 15 minutes old But I'm afraid I don't know that API well enough to know how to get the signature setup correctly but have you considered using a library This seems like a nice example of what can be achieved with the library http://exeu.github.io/apai-io/
    unknown
    d319
    train
    You'll have discovered that your compiler doesn't like the line REAL :: y(0:n+1) = (/(k, k=a,b,h)/) Change it to REAL :: y(0:n+1) = [(k, k=INT(a),INT(b),2)] that is, make the lower and upper bounds for k into integers. I doubt that you will ever be able to measure any increase in efficiency, but this change might appeal to your notions of nice-looking and convenient code. You might also want to tweak the way you initialise M. I'd have written your two loops as M = 0.0 DO i = 1,n M(i,i) = y(i)**2 END DO Overall, though, your question is a bit vague so I'm not sure how satisfactory this answer will be. If not enough, clarify your question some more.
    unknown
    d320
    train
    You can try using Text Component Line Number.
    unknown
    d321
    train
    Try to add , after "userAccountResource" like this .factory("userAccountResource", //, here was missing ["$resource", userAccountResource]);
    unknown
    d322
    train
    You have to put list of data in a scope try something like this: public List<String> getMyList() { myList.clear(); List<String> list = (List<String>) AdfFacesContext.getCurrentInstance().getProcessScope().get("myList"); if (list != null) { for (String var : list) { myList.add(var); } } return myList; } You can also see this question and answer : How to refresh table within a popup in dialog window in ADF Oracle 11gR1 A: The problem is that I define the setNameList() in managedbean and have to invoke setNameList() in another method in Class B. I new a fresh managedBean to call this method and the nameList in this instance is not the one bonded to the page. Solution: In class B, get the right instance as: ManagedBean managedBean = (ManagedBean)ADFUtil.evaluateEL("#{pageFlowScope.ManagedBean}"); The issue is gone.
    unknown
    d323
    train
    In Python, do the following where alwayssep is the expression and line is the passed string: line = re.sub(alwayssep, r' \g<0> ', line) A: My Pythonizer converts that to this: line = re.sub(re.compile(alwayssep),r' \g<0> ',line,count=0)
    unknown
    d324
    train
    This document addresses issues on what you can, or rather, cannot do as Instance Administrators. You are permitted to change what you have access to the web UI and SMTP parameters using the APEX_INSTANCE_ADMIN package.
    unknown
    d325
    train
    you can try something like this. <table> <thead> <tr> {% for key in groups.keys() %} <th>{{ key|title }}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for key in groups.keys() %} <td>{{ groups[key]}}</td> {% endfor %} </tr> </tbody> </table>
    unknown
    d326
    train
    I diff'ed the project against an earlier version I'd kept that worked properly and came up with this fix: In Xcode, under your Phonegap or Cordova project, select Target -> Build Phases -> Compile Sources Add your plugin into the list there, in this case CVLogger.m located in your file structure under "Plugins". After this, the project compiles without error and the console plugin works. No need to reinstall and reconfigure your entire project for this...
    unknown
    d327
    train
    Your superclass PointF is not serialisable. That means that the following applies: To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream. See: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html You will need to look at readObject and writeObject: Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; See also here: Java Serialization with non serializable parts for more tips and tricks. A: I finally found the solution. Thanx @Greg and the other comment that has now been deleted. The solution is that instead of extending these objects we can make stub objects. As i was calling super from constructor the x and y fields were inherited from base class that is not serializable. so they were not serialized and there values were not sent. so i mofidfied my class as per your suggestions public class MyPointF implements Serializable { /** * */ private static final long serialVersionUID = -455530706921004893L; public float x; public float y; public MyPointF(float x, float y) { this.x = x; this.y = y; } }
    unknown
    d328
    train
    You could do this: public override string DoSomething() { //does something... base.DoSomething(); return GetName().Result; } Warning: this can cause a deadlock See Don't block on async code
    unknown
    d329
    train
    This has nothing to do with React Native, one of your resource files references an nonexisting value (dialogCornerRadius). Locate the reference (Android Studio to the rescue) and fix it.
    unknown
    d330
    train
    These following guidelines may help you with initializing a Jenkins freestyle job for building a subproject rather than building all projects included in a git repo. * *Install git-plugin for Jenkins *Create a freestyle job and add your git hub repository's link on SCM repository field * *New Item --> *Name the item and OK --> *Select Git in SCM --> *Add repository URL --> *Add invoke top-level maven targets as Build steps --> *In Goals install -pl ChildProjectD *(optional) Add post-build and other configurations It will build the Child project as you want instead of full project. You can refer Jenkins GitHub Java Application Project Build Configuration Maven to get more help. Check also mvn install -pl --help for more info. Feel free to ask questions.
    unknown
    d331
    train
    Not over the internet, as that would be very dangerous, the user would have to have special software. Otherwise web programs could (very) easily be used for malicious purposes.
    unknown
    d332
    train
    Brutally: function formatValue(value) { var tempVal = Math.trunc(value * 1000); var lastValue = (tempVal % 10); if (lastValue > 0 && lastValue <= 5) lastValue = 5; else if (lastValue > 5 && lastValue <= 9) lastValue = 10; else lastValue = 0; return parseFloat((Math.trunc(tempVal / 10) * 10 + lastValue) / 1000).toFixed(3); } formatValue(3.656); // -> "3.660" formatValue(3.659); // -> "3.660" formatValue(3.660); // -> "3.660" formatValue(3.661); // -> "3.665" formatValue(3.664); // -> "3.665" formatValue(3.665); // -> "3.665" Pay attention: function returns a string (.toFixed returns a string).. (but however a fixed decimal length doesn't have any sense in a number) A: Rounding to a certain number of decimals is done by multiplying the value to bring the desired amount of decimals into the integer range, then getting rid of the remaining decimals, then dividing by the same multiplier to make it decimal again. Rounding to a "half-decimal" as you want is accomplished by doubling the multiplier (2X instead of 1X). The + 0.005 is to make it round up as desired, otherwise it would always round down. toFixed() is used to make the string representation of the value have the decimal part padded with zeros as needed. function formatValue(value) { return (Math.floor((value + 0.005) * 200) / 200).toFixed(3); } console.log(formatValue(1.950)); console.log(formatValue(1.954)); console.log(formatValue(1.956)); console.log(formatValue(1.003)); console.log(formatValue(1.007));
    unknown
    d333
    train
    The typical purpose for this style is in use for object construction. Person* pPerson = &(new Person())->setAge(34).setId(55).setName("Jack"); instead of Person* pPerson = new Person( 34, 55, "Jack" ); Using the second more traditional style one might forget if the first value passed to the constructor was the age or the id? This may also lead to multiple constructors based on the validity of some properties. Using the first style one might forget to set some of the object properties and and may lead bugs where objects are not 'fully' constructed. (A class property is added at a later point but not all the construction locations got updated to call the required setter.) As code evolves I really like the fact that I can use the compiler to help me find all the places where an object is created when changing the signature of a constructor. So for that reason I prefer using regular C++ constructors over this style. This pattern might work well in applications that maintain their datamodel over time according to rules similar to those used in many database applications: * *You can add a field/attribute to a table/class that is NULL by default. (So upgrading existing data requires just a new NULL column in the database.) *Code that is not changes should still work the same with this NULL field added. A: Not all the setters, but some of them could return reference to object to be useful. kind of a.SetValues(object)(2)(3)(5)("Hello")(1.4); I used this once long time ago to build SQL expression builder which handles all the Escapes problems and other things. SqlBuilder builder; builder.select( column1 )( column2 )( column3 ). where( "=" )( column1, value1 ) ( column2, value2 ). where( ">" )( column3, 100 ). from( table1 )( "table2" )( "table3" ); I wasn't able to reproduce sources in 10 minutes. So implementation is behind the curtains. A: If your motivation is related to chaining (e.g. Brian Ensink's suggestion), I would offer two comments: 1. If you find yourself frequently settings many things at once, that may mean you should produce a struct or class which holds all of these settings so that they can all be passed at once. The next step might be to use this struct or class in the object itself...but since you're using getters and setters the decision of how to represent it internally will be transparent to the users of the class anyways, so this decision will relate more to how complex the class is than anything. 2. One alternative to a setter is creating a new object, changing it, and returning it. This is both inefficient and inappropriate in most types, especially mutable types. However, it's an option that people sometimes forget, despite it's use in the string class of many languages. A: This technique is used in the Named parameter Idiom. A: IMO setters are a code smell that usually indicate one of two things: Making A Mountian Out Of A Molehill If you have a class like this: class Gizmo { public: void setA(int a) { a_ = a; } int getA() const { return a_; } void setB(const std::string & b) { v_ = b; } std::string getB() const { return b_; } private: std::string b_; int a_; }; ... and the values really are just that simple, then why not just make the data members public?: class Gizmo { public: std::string b_; int a_; }; ...Much simpler and, if the data is that simple you lose nothing. Another possibility is that you could be Making A Molehill Out Of A Mountian Lots of times the data is not that simple: maybe you have to change multiple values, do some computation, notify some other object; who knows what. But if the data is non-trivial enough that you really do need setters & getters, then it is non-trivial enough to need error handling as well. So in those cases your getters & setters should be returning some kind of error code or doing something else to indicate something bad has happened. If you are chaining calls together like this: A.doA().doB().doC(); ... and doA() fails, do you really want to be calling doB() and doC() anyway? I doubt it. A: It's a usable enough pattern if there's a lot of things that need to be set on an object. class Foo { int x, y, z; public: Foo &SetX(int x_) { x = x_; return *this; } Foo &SetY(int y_) { y = y_; return *this; } Foo &SetZ(int z_) { z = z_; return *this; } }; int main() { Foo foo; foo.SetX(1).SetY(2).SetZ(3); } This pattern replaces a constructor that takes three ints: int main() { Foo foo(1, 2, 3); // Less self-explanatory than the above version. } It's useful if you have a number of values that don't always need to be set. For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite. Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not... A: You can return a reference to this if you want to chain setter function calls together like this: obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35); Personally I think that code is harder to read than the alternative: obj.SetCount(10); obj.SetName("Bob"); obj.SetColor(0x223344); obj.SetWidth(35); A: I would not think so. Typically, you think of 'setter' object as doing just that. Besides, if you just set the object, dont you have a pointer to it anyway?
    unknown
    d334
    train
    I think this is what you are looking for. I added some inline comments to explain what each step is doing. The end result should be all the contacts that can be read by a specified user in your org. // add a set with all the contact ids in your org List<contact> contacts = new List<contact>([Select id from Contact]); Set<ID> contactids = new Set<ID>(); for(Contact c : contacts) contactids.add(c.id); // using the user record access you can query all the recordsids and the level of access for a specified user List<UserRecordAccess> ura = new List<UserRecordAccess>([SELECT RecordId, HasReadAccess, HasTransferAccess, MaxAccessLevel FROM UserRecordAccess WHERE UserId = 'theuserid' AND RecordId in: contactids ] ); // unfortunatelly you cannot agregate your query on hasReadAccess=true so you'd need to add this step Set<id> readaccessID = new Set<ID>(); for(UserRecordAccess ur : ura) { if(ur.HasReadAccess==true) { readaccessID.add(ur.RecordID); } } // This is the list of all the Contacts that can be read by the specified user List<Contact> readAccessContact = new List<Contact>([Select id, name from contact where id in: readaccessID]); // show the results system.debug( readAccessContact);
    unknown
    d335
    train
    You can try to light-weight load in main thread by DispatchQueue.global().async { UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList) } And instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line
    unknown
    d336
    train
    @Wiktor Stribizew is right. replace [(\d)] with \(\d+\) test it here: https://regex101.com/ A: I solve this problem, correct regexp is [ ][(][\d]*[)]
    unknown
    d337
    train
    It is because the execution is stuck in the second infinite loop. The condition (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)) is met every time after the first execution so the if statement is never evaluated to True and the while loop is never exited. Also, note that your break statements only exist the for loop and not the while loop so statements after the second break are never executed.
    unknown
    d338
    train
    Some of these are doable. Some, not so much. Let's tackle the low-hanging fruit first. Text files You can just wrap the content in <pre> tags after running it through htmlspecialchars. PDF There is no native way for PHP to turn a PDF document into HTML and images. Your best bet is probably ImageMagick, a common image manipulation program. You can basically call convert file.pdf file.png and it will convert the PDF file into a PNG image that you can then serve to the user. ImageMagick is installed on many Linux servers. If it's not available on your host's machine, please ask them to install it, most quality hosts shouldn't have a problem with this. DOC & DOCX We're getting a bit more tricky. Again, there's no way to do this in pure PHP. The Docvert extension looks like a possible choice, though it requires OpenOffice be installed as well. I was actually going to recommend plain vanilla OpenOffice/LibreOffice as well, because it can do the job directly from the command line. It's very unlikely that a shared host will want to install this. You'll probably need your own dedicated or virtual private server. In the end, while these options can be made to work, the output quality is not guaranteeable. Overall, this is kind of a bad idea that you should not seriously consider implementing. A: I am sure libraries and such exist that can do this. Google could probably help you there more than I can. For txt files I would suggest breaking lines after a certain number of characters and putting them inside pre tags. I know people will not be happy about this response, but if you are on a Linux environment and have pdf2html installed you could use shell_exec and call pdf2html. Note: If you use shell_exec be wary of what you pass to it since it will be executed on the server outside of PHP. A: I thought I'd just add that pdfs generally view well in a simple embed tag. Or use an object so you can have fall backs if it cannot be displayed on the client.
    unknown
    d339
    train
    This part of the code doesn't do anything: rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); md_FilesJsonDocument.Accept(writer); strbuf contains the json string but it is discarded. I would move this into a separate function and print the conents with std::cout << strbuf;. To write directly to a file: std::ofstream ofs("out.json", std::ios::out); if (ofs.is_open()) { rapidjson::OStreamWrapper osw(ofs); rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw); md_FilesJsonDocument.Accept(writer); }
    unknown
    d340
    train
    I dont see any code for adding the like buttons in your loop. So there is nothing to render. Firstly you should configure your Javascript SDK and link it to your Facebook page / application. To configure the Javascript SDK you will need to add something like <script> window.fbAsyncInit = function() { FB.init({ appId : 'your-app-id', xfbml : true, version : 'v2.1' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> This code is detailed here but links your website to your application and configures the SDK to look for Facebook social plugins on the page. Then you need to add placeholder elements for the Javscript SDK to parse and render, like the below: foreach ($sortedArray as &$filename) { #echo '<br>' . $filename; echo '<tr><td>'; echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>'; ?> <div class="fb-like" data-href="<?php echo $imageUrl; ?>" data-layout="button" data-action="like" data-show-faces="true" data-share="false"></div> <?php echo substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder)); echo '</td></tr>'; } These divs have special attributes that the SDK will recognise and use to render the like buttons in the correct place. You should read the documentation here.
    unknown
    d341
    train
    This version of your script should return the entire contents of the page: var page = require('webpage').create(); page.settings.userAgent = 'SpecialAgent'; page.open('http://www.httpuseragent.org', function (status) { if (status !== 'success') { console.log('Unable to access network'); } else { var ua = page.evaluate(function () { return document.getElementsByTagName('html')[0].outerHTML; }); console.log(ua); } phantom.exit(); }); A: There are multiple ways to retrieve the page content as a string: * *page.content gives the complete source including the markup (<html>) and doctype (<!DOCTYPE html>), *document.documentElement.outerHTML (via page.evaluate) gives the complete source including the markup (<html>), but without doctype, *document.documentElement.textContent (via page.evaluate) gives the cumulative text content of the complete document including inline CSS & JavaScript, but without markup, *document.documentElement.innerText (via page.evaluate) gives the cumulative text content of the complete document excluding inline CSS & JavaScript and without markup. document.documentElement can be exchanged by an element or query of your choice. A: To extract the text content of the page, you can try thisreturn document.body.textContent; but I'm not sure the result will be usable. A: Having encountered this question while trying to solve a similar problem, I ended up adapting a solution from this question like so: var fs = require('fs'); var file_h = fs.open('header.html', 'r'); var line = file_h.readLine(); var header = ""; while(!file_h.atEnd()) { line = file_h.readLine(); header += line; } console.log(header); file_h.close(); phantom.exit(); This gave me a string with the read-in HTML file that was sufficient for my purposes, and hopefully may help others who came across this. The question seemed ambiguous (was it the entire content of the file required, or just the "text" aka Strings?) so this is one possible solution.
    unknown
    d342
    train
    Well the obvious answer is that in some situations requests would take longer than 90 seconds for the worker process to return. If you can't imagine a situation where this would be appropriate, then feel free to lower it. I wouldn't recommend going too much lower than 30 seconds. I can see situations where you get in recycle loops. However you can do testing and see what makes sense in your situation. I would recommend Siege for load testing to see how your application behaves.
    unknown
    d343
    train
    You could try: System.out.printf("Input an integer: "); int a = in.nextInt(); int k = 0; String str_a = ""; System.out.print(a); while(a > 1) { if(a % 2 == 0) a = a / 2; else a = 3 * a + 1; str_a += ", " + String.valueOf(a); k++; } System.out.println("k = " + k); System.out.println("a = " + str_a);
    unknown
    d344
    train
    You're never calling the scalarMultiply method. A: You're never calling scalarMultiply and the number of the brackets is incorrect. public class warm4{ public static void main(String[] args){ double[] array1 = {1,2,3,4}; double scale1 = 3; scalarMultiply(array1, scale1); } public static void scalarMultiply(double[] array, double scale){ for( int i=0; i<array.length; i++){ array[i] = (array[i]) * scale; System.out.print(array[i] + " "); } } } A: Your method is OK. But you must call it from your main: public static void main(String[] args){ double[] array1 = {1,2,3,4}; double scale1 = 3; scalarMultiply(array1, scale1); for (int i = 0; i < array1.length; i++) { System.out.println(array1[i]); } }
    unknown
    d345
    train
    You can use wallet_switchEthereumChain method of RPC API of Metamask Visit: https://docs.metamask.io/guide/rpc-api.html#wallet-switchethereumchain A: const changeNetwork = async () => { if (window.ethereum) { try { await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: Web3.utils.toHex(chainId) }], }); }); } catch (error) { console.error(error); } } changeNetwork() A: What if the user doesn't have the required network added? Here is an expanded version which tries to switch, otherwise add the network to MetaMask: const chainId = 137 // Polygon Mainnet if (window.ethereum.networkVersion !== chainId) { try { await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: web3.utils.toHex(chainId) }] }); } catch (err) { // This error code indicates that the chain has not been added to MetaMask if (err.code === 4902) { await window.ethereum.request({ method: 'wallet_addEthereumChain', params: [ { chainName: 'Polygon Mainnet', chainId: web3.utils.toHex(chainId), nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' }, rpcUrls: ['https://polygon-rpc.com/'] } ] }); } } } A: export async function switchToNetwork({ library, chainId, }: SwitchNetworkArguments): Promise<null | void> { if (!library?.provider?.request) { return } const formattedChainId = hexStripZeros( BigNumber.from(chainId).toHexString(), ) try { await library.provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: formattedChainId }], }) } catch (error) { // 4902 is the error code for attempting to switch to an unrecognized chainId // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((error as any).code === 4902) { const info = CHAIN_INFO[chainId] await library.provider.request({ method: 'wallet_addEthereumChain', params: [ { chainId: formattedChainId, chainName: info.label, rpcUrls: [info.addNetworkInfo.rpcUrl], nativeCurrency: info.addNetworkInfo.nativeCurrency, blockExplorerUrls: [info.explorer], }, ], }) // metamask (only known implementer) automatically switches after a network is added // the second call is done here because that behavior is not a part of the spec and cannot be relied upon in the future // metamask's behavior when switching to the current network is just to return null (a no-op) try { await library.provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: formattedChainId }], }) } catch (error) { console.debug( 'Added network but could not switch chains', error, ) } } else { throw error } } }
    unknown
    d346
    train
    Think this answer seems to be similar to your question.Hope it provides some insight. Time Binding issue in Bootstrap timepicker
    unknown
    d347
    train
    If the registration is succesful you can simply push the email and password variables to firebase. See code below. function createUser(email, password, username) { ref.createUser({ email: email, password: password }, function(error) { if (error === null) { ... Registration successful $activityIndicator.stopAnimating(); $scope.padding_error = null; $scope.error = null; ##NEWCODE HERE## emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email") passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password") emailRef.set(email) passRef.set(password) logUserIn(email, password); } else { ... Something went wrong at registration } } }); }
    unknown
    d348
    train
    You can .map over all array entries and then use .reduce on the Object.values of each array entry to sum the values: let data = [ { "cost one": "118", "cost two": "118", "cost three": "118" }, { "cost one": "118", "cost two": "111", "cost three": "118" }, { "cost one": "120", "cost two": "118", "cost three": "118" } ]; function sumValues(objArr) { return objArr.map(curr => { return Object.values(curr).reduce((prev, val) => prev += Number(val), 0) }); } console.log(sumValues(data));
    unknown
    d349
    train
    IDEA is using its own method of instrumenting bytecode to add such validations. For command line builds we provide javac2 Ant task that does the instrumentation (extends standard javac task). If you generate Ant build from IDEA, you will have an option to use javac2. We don't provide similar Maven plug-in yet, but there is third-party version which may work for you (though, it seems to be a bit old). A: I'd go the AOP way: First of all you need a javax.validation compatible validator (Hibernate Validator is the reference implementation). Now create an aspectj aspect that has a Validator instance and checks all method parameters for validation errors. Here is a quick version to get you started: public aspect ValidationAspect { private final Validator validator; { final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } pointcut serviceMethod() : execution(public * com.yourcompany**.*(..)); before() : serviceMethod(){ final Method method = (Method) thisJoinPoint.getTarget(); for(final Object arg : thisJoinPoint.getArgs()){ if(arg!=null) validateArg(arg,method); } } private void validateArg(final Object arg, final Method method) { final Set<ConstraintViolation<Object>> validationErrors = validator.validate(arg); if(!validationErrors.isEmpty()){ final StringBuilder sb = new StringBuilder(); sb.append("Validation Errors in method ").append(method).append(":\n"); for (final ConstraintViolation<Object> constraintViolation : validationErrors) { sb.append(" - ").append(constraintViolation.getMessage()).append("\n"); } throw new RuntimeException(sb.toString()); } } } Use the aspectj-maven-plugin to weave that aspect into your test and / or production code. If you only want this functionality for testing, you might put the aspectj-plugin execution in a profile. A: There is a maven plugin closely affiliated with the IntelliJ functionality, currently at https://github.com/osundblad/intellij-annotations-instrumenter-maven-plugin. It is discussed under the IDEA-31368 ticket first mentioned in CrazyCoder's answer. A: You can do annotation validation in your JUnit tests. import java.util.Set; import javax.validation.ConstraintViolation; import junit.framework.Assert; import org.hibernate.validator.HibernateValidator; import org.junit.Before; import org.junit.Test; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; public class Temp { private LocalValidatorFactoryBean localValidatorFactory; @Before public void setup() { localValidatorFactory = new LocalValidatorFactoryBean(); localValidatorFactory.setProviderClass(HibernateValidator.class); localValidatorFactory.afterPropertiesSet(); } @Test public void testLongNameWithInvalidCharCausesValidationError() { final ProductModel productModel = new ProductModel(); productModel.setLongName("A long name with\t a Tab character"); Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel); Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1); } } If your poison is Spring, take a look at these Spring Unit Tests
    unknown
    d350
    train
    You can use Uncorelated sub queries in $lookup * *$match to get the "notifications.sms": true *$lookupto join two collections. We are assigning uId = _id from USER collection. Inside the pipeline, we use $match to find the active :true, and _id=uId here is the script db.USER.aggregate([ { "$match": { "notifications.sms": true } }, { "$lookup": { "from": "ALERT", "let": { uId: "$_id" }, "pipeline": [ { $match: { $and: [ { active: true }, { $expr: { $eq: [ "$user_id", "$$uId" ] } } ] } } ], "as": "joinAlert" } } ]) Working Mongo playground
    unknown
    d351
    train
    I've done the first half of this before, so we'll start there (convenient, no?). Without knowing to much about your needs I'd recommend the following as a base (you can adjust the column widths as needed): CREATE TABLE tree ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INT UNSIGNED NOT NULL DEFAULT 0, type VARCHAR(20) NOT NULL, name VARCHAR(32) NOT NULL, PRIMARY KEY (id), UNIQUE KEY (parent_id, type, name), KEY (parent_id) ); Why did I do it this way? Well, let's go through each field. id is a globally unique value that we can use to identify this element and all the elements that directly depend on it. parent_id lets us go back up through the tree until we reach parent_id == 0, which is the top of the tree. type would be your "car" or "vent" descriptions. name would let you qualify type, so things like "Camry" and "Driver Left" (for "vent" obviously). The data would be stored with values like these: INSERT INTO tree (parent_id, type, name) VALUES (0, 'car', 'Camry'), (1, 'hvac', 'HVAC'), (2, 'vent', 'Driver Front Footwell'), (2, 'vent', 'Passenger Front Footwell'), (2, 'vent', 'Driver Rear Footwell'), (2, 'vent', 'Passenger Rear Footwell'), (1, 'glass', 'Glass'), (7, 'window', 'Windshield'), (7, 'window', 'Rear Window'), (7, 'window', 'Driver Front Window'), (7, 'window', 'Passenger Front Window'), (7, 'window', 'Driver Rear Window'), (7, 'window', 'Passenger Rear Window'), (1, 'mirrors', 'Mirrors'), (14, 'mirror', 'Rearview Mirror'), (14, 'mirror', 'Driver Mirror'), (14, 'mirror', 'Passenger Mirror'); I could keep going, but I think you get the idea. Just to be sure though... All those values would result in a tree that looked like this: (1, 0, 'car', 'Camry') | (2, 1, 'hvac', 'HVAC') | +- (3, 2, 'vent', 'Driver Front Footwell') | +- (4, 2, 'vent', 'Passenger Front Footwell') | +- (5, 2, 'vent', 'Driver Rear Footwell') | +- (6, 2, 'vent', 'Passenger Rear Footwell') +- (7, 1, 'glass', 'Glass') | +- (8, 7, 'window', 'Windshield') | +- (9, 7, 'window', 'Rear Window') | +- (10, 7, 'window', 'Driver Front Window') | +- (11, 7, 'window', 'Passenger Front Window') | +- (12, 7, 'window', 'Driver Rear Window') | +- (13, 7, 'window', 'Passenger Rear Window') +- (14, 1, 'mirrors', 'Mirrors') +- (15, 14, 'mirror', 'Rearview Mirror') +- (16, 14, 'mirror', 'Driver Mirror') +- (17, 14, 'mirror', 'Passenger Mirror') Now then, the hard part: copying the tree. Because of the parent_id references we can't do something like an INSERT INTO ... SELECT; we're reduced to having to use a recursive function. I know, we're entering The Dirty place. I'm going to pseudo-code this since you didn't note which language you're working with. FUNCTION copyTreeByID (INTEGER id, INTEGER max_depth = 10, INTEGER parent_id = 0) row = MYSQL_QUERY_ROW ("SELECT * FROM tree WHERE id=?", id) IF NOT row THEN RETURN NULL END IF IF ! MYSQL_QUERY ("INSERT INTO trees (parent_id, type, name) VALUES (?, ?, ?)", parent_id, row["type"], row["name"]) THEN RETURN NULL END IF parent_id = MYSQL_LAST_INSERT_ID () IF max_depth LESSTHAN 0 THEN RETURN END IF rows = MYSQL_QUERY_ROWS ("SELECT id FROM trees WHERE parent_id=?", id) FOR rows AS row copyTreeByID (row["id"], max_depth - 1, parent_id) END FOR RETURN parent_id END FUNCTION FUNCTION copyTreeByTypeName (STRING type, STRING name) row = MYSQL_QUERY_ROW ("SELECT id FROM tree WHERE parent_id=0 AND type=? AND name=?", type, name) IF NOT ARRAY_LENGTH (row) THEN RETURN END IF RETURN copyTreeByID (row["id"]) END FUNCTION copyTreeByTypeName looks up the tree ID for the matching type and name and passes it to copyTreeByID. This is mostly a utility function to help you copy stuff by type/name. copyTreeByID is the real beast. Fear it because it is recursive and evil. Why is it recursive? Because your trees are not predictable and can be any depth. But it's okay, we've got a variable to track depth and limit it (max_depth). So let's walk through it. Start by grabbing all the data for the element. If we didn't get any data, just return. Re-insert the data with the element's type and name, and the passed parent_id. If the query fails, return. Set the parent_id to the last insert ID so we can pass it along later. Check for max_depth being less than zero, which indicates we've reached max depth; if we have return. Grab all the elements from the tree that have a parent of id. Then for each of those elements recurse into copyTreeByID passing the element's id, max_depth minus 1, and the new parent_id. At the end return parent_id so you can access the new copy of the elements. Make sense? (I read it back and it made sense, not that that means anything).
    unknown
    d352
    train
    Trying to modify the standard keyboard requires taking a dangerous path into private APIs and a broken app in future iOS versions. I think the best solution for you would be to implement the textField:shouldChangeCharactersInRange:replacementString: method of UITextFieldDelegate and replace whitespace characters with the empty string. Once this is implemented, hitting the space bar will simply do nothing.
    unknown
    d353
    train
    autoit may work. i'd use python PIL. i can specify font, convert it to a layer and overlay on top of preexisting image. EDIT actually imagemagick can be easier than PIL http://www.imagemagick.org/Usage/text/ A: Should not be much of a problem if you have Python and the Python Imaging Library (PIL) installed: from PIL import Image, ImageFont, ImageDraw BACKGROUND = '/path/to/background.png' OUTPUT = '/path/to/mypicture_{0:04d}.png' START = 0 STOP = 9999 # Create a font object from a True-Type font file and specify the font size. fontobj = ImageFont.truetype('/path/to/font/arial.ttf', 24) for i in range(START, STOP + 1): img = Image.open(BACKGROUND) draw = ImageDraw.Draw(img) # Write a text over the background image. # Parameters: location(x, y), text, textcolor(R, G, B), fontobject draw.text((0, 0), '{0:04d}'.format(i), (255, 0, 0), font=fontobj) img.save(OUTPUT.format(i)) print 'Script done!' Please consult the PIL manual for other ways of creating font objects for other font formats
    unknown
    d354
    train
    Saw this in the source and something clicked in my head. Changing the filter method above to the following gave me the desired results. def filter(keys) if (scope == object) or scope.has_role?(:super) keys else keys - [:auth_token] end end Hope this helps anyone else using version 0.9.x
    unknown
    d355
    train
    Put the valid names into a text file (i.e. "ValidNames.txt") and use findstr with the /G option. 02-TestFile.xlsx 05-TestFile.xlsx 10-TestFile.xlsx ... @echo off for /f "delims=" %%a in (' dir /b *.xlsx ^| findstr /vxlg:"ValidNames.txt" ') do move "%%a" "C:\Temp\Archive\Error"
    unknown
    d356
    train
    The process.stdout and process.stderr pipes are independent of whatever actual code you're running using Node, so if you want their output sent to files, then make your main entry point script capture stdout/stderr output and that's simply what it'll do for as long as Node.js runs that script. You can add log writing yourself by tapping into process.stdout.on(`data`, data => ...) (and stderr equivalent), or you can pipe their output to a file, or (because why reinvent the wheel?) you can find a logging solution that does that for you, but then that's on you to find, asking others to recommend you one is off topic on Stackoverflow. Also note that stdout/stderr have some sync/async quirks, so give https://nodejs.org/api/process.html#process_a_note_on_process_i_o a read because that has important information for you to be aware of. A: The example from winston basically solved the issue.
    unknown
    d357
    train
    You can use this template to get required counts. <xsl:template match="lst/arr/lst"> <ns:reply> <ns:party-name> <xsl:value-of select="str[@name='value']"/> </ns:party-name> <ns:shipments-count> <xsl:value-of select="int[@name='count']" /> </ns:shipments-count> <ns:no-entry-or-line-release-count> <xsl:value-of select ="count(arr[@name='pivot']/lst[count(str[@name='value'])=0]/arr[@name='pivot']/lst/int[@name='count'])"> </xsl:value-of> </ns:no-entry-or-line-release-count> </ns:reply> </xsl:template>
    unknown
    d358
    train
    It turns out the 'table' I was pulling from was in fact a database view, a sort of pseudo-table, which is composed of sql joining together other tables. The error actually lay in the view, rather than in my SQL, which is where the subquery referred to in the error was. Thanks for the help in the comments!
    unknown
    d359
    train
    The simplest way would be to create a function with the code you want to execute after the execution of the request, and pass this function in parameter of the getfile function : getFile : function( fileName, success ) { var me = this; me.db.transaction( function( tx ) { tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError ); }, success ); // somehow return results as empty array or array with object // I know results need to be transformed }); var r = getFile( name, function() { var r = getFile( name ); if ( r.length > 0 ) { // use it } else { // make AJAX call and store it } } ); Otherwise, the best way to perform is to use Promises to resolve asynchronous issues but you'll have to use a library like JQuery. http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
    unknown
    d360
    train
    You're doing SELECT pram = (…) FROM dbo.ClassRelationship a …; where (…) is an expression that is evaluated and then compared to the current value of pram (which was initialised to an empty string). The query does nothing else, there is no destination for this boolean value (comparison result) it computes, you're getting an error. You most likely meant to either perform an assignment pram = SELECT (…) FROM dbo.ClassRelationship a …; or use an INTO clause: SELECT (…) INTO pram FROM dbo.ClassRelationship a …; Notice that you don't even need pl/pgsql to do this. A plain sql function would do as well: CREATE OR REPLACE FUNCTION dbo.fnRepID(pram_ID BIGINT) RETURNS varchar LANGUAGE sql STABLE RETURN ( SELECT '' || (CASE COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END) || (CASE COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END) || f.NAME || ';' FROM dbo.ClassRelationship a LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID AND b.Type = 2 AND a.Type = 1 );
    unknown
    d361
    train
    If you want to use your url params in your state everytime, you can use the resolve function: .state('edit', { url: '/editItem/:id/:userId', templateUrl: 'app/items/edit.html', controller: 'editController', controllerAs: 'vm', resolve: { testObject: function($stateParams) { return { id: $stateParams.id, userId: $stateParams.userId } } } }) Now, you can pass testObject as a dependency to your editController and every time this route is resolved, the values will be available within your controller as testObject.id and testObject.userId If you want to pass an object from one state to the next, use $state.go programatically: $state.go('myState', {myParam: {some: 'thing'}}) $stateProvider.state('myState', { url: '/myState', params: {myParam: null}, ... The only other option is to cache, trough Localstorage or cookies
    unknown
    d362
    train
    I wouldn't know what could be going wrong, but I do know an easy solution could be creating a global array and then setting the property to the global array. Code: var array = [ your array] ; var cc_cd = { List : array, Other properties }; Please mark answered or vote to let me know if this helped!
    unknown
    d363
    train
    Try this: object.visible = false; //Invisible object.visible = true; //Visible A: simply use the object traverse method to hide the mesh in three.js. In my code hide the object based on its name object.traverse ( function (child) { if (child instanceof THREE.Mesh) { child.visible = true; } }); Here is the working sample for Object show/hide option http://jsfiddle.net/ddbTy/287/ I think it should be helpful,..
    unknown
    d364
    train
    Not directly, no. Unless it's in the browser's UA, there's no way of detecting it without some kind of plugin. A: If you can use VBSCRIPT you can get what you are looking for. The WMI class Win32_OperatingSystem has the properties ServicePackMajorVersion, ServicePackMinorVersion, Name and Version. Try samples here: WMI Tasks Hope this can help
    unknown
    d365
    train
    how come I can still add content to the file such as shown here Android saving Bitmap to SD card. That code creates a new file after deleting the old one. So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there? Call delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does.
    unknown
    d366
    train
    Apparently the source code is correct, but there seem to be problems with the database: The table, corresponding with Class1, contains a column voa_class. The content of that column should be <NameSpace_of_Class1>.Class1. In case there's something else, like <Whatever_NameSpace>.<AnotherClass> or <AnotherNameSpace>.Class1 (like in my case), the mentioned exception gets generated.
    unknown
    d367
    train
    Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing. You might want to try $item_info_tmp=array(); foreach ($item_info as $ii) { if (!isset($item_info_tmp[$ii['folder_id']])) $item_info_tmp[$ii['folder_id']]=array(); $item_info_tmp[$ii['folder_id']][]=$ii; } $item_info=array_values($item_info_tmp);
    unknown
    d368
    train
    Try this simply .HTMLBody = "<table><td style='width:" & tblWidth & "px; color:#4d4d4d; height=2px;'></td></table>" A: To use a stylesheet instead: Just create one using a string and include it in your HTMLBody Dim sStyleSheet as String sStyleSheet = "<style> td {width:500px;} </style>" or to include your variable sStyleSheet = "<style> td {width:" & tblWidth & "px;} </style>" See how you are just building a string? Then include it in the HTML: sHTML = "<table><tr><td> Hello World </td></tr></table>" sStyleSheet = "<style> td {width:" & tblWidth & "px;} </style>" .HTMLBody = sStyleSheet & sHTML Make sense?
    unknown
    d369
    train
    That's because (as listed in the documentation) the VALUE() function has not yet been implemented in the PHPExcel calculation engine
    unknown
    d370
    train
    Error: startTime contains string values but got a date (Code: 102, Version: 1.2.21) The error clearly indicates that you are comparing two different objects one is string and second one is date. So there are two things you can either convert any one into date or string. So to implement the same in a easy way, you can write one category with function which will convert either into date or string and use that method to perform the comparison. A: You've converted leftDate and arrivedDate to leftDateString and arrivedDateString, but you're still using leftDate and arrivedDate in your query. I think you meant to write: PFQuery *query = [PFQuery queryWithClassName:@"PassData"]; [query whereKey:@"startTime" greaterThan:leftDateString]; [query whereKey:@"timeArrived" lessThan:arrivedDateString]; in which case you'd no longer get the error since you'd be comparing string to string. Although I generally recommend that you store and sort your dates with NSDate objects, in this case where your format is in the same descending order of importance as a typical NSDate sort of month, day, hour, then minute, i.e. "MM-dd hh:mm", as long as year or seconds don't matter to you and as long as the queried time format matches the database time format, this query should work since greaterThan and lessThan will compare the string objects alphabetically/numerically. A: I guess for that to work you have to have Date fields in database, then you pass NSDate to whereKey: on iOS.
    unknown
    d371
    train
    Grant usage/select to a single table If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so: GRANT CONNECT ON DATABASE mydb TO xxx; -- This assumes you're actually connected to mydb.. GRANT USAGE ON SCHEMA public TO xxx; GRANT SELECT ON mytable TO xxx; Multiple tables/views (PostgreSQL 9.0+) In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one: GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx; This only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future: ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO xxx; Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow. Multiple tables/views (PostgreSQL versions before 9.0) To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view: SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;' FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace WHERE nspname = 'public' AND relkind IN ('r', 'v', 'S'); This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created. A: From PostgreSQL v14 on, you can do that simply by granting the predefined pg_read_all_data role: GRANT pg_read_all_data TO xxx; A: Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that: test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser; A: If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser) db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser; GRANT db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser; GRANT db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser; GRANT If your database is using customschema, execute the above but add one more command: db=> ALTER USER readonlyuser SET search_path=customschema, public; ALTER ROLE A: The not straightforward way of doing it would be granting select on each table of the database: postgres=# grant select on db_name.table_name to read_only_user; You could automate that by generating your grant statements from the database metadata. A: Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer): $ sudo -upostgres psql postgres postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE'; postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly; Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run: $ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf $ sudo service postgresql reload A: By default new users will have permission to create tables. If you are planning to create a read-only user, this is probably not what you want. To create a true read-only user with PostgreSQL 9.0+, run the following steps: # This will prevent default users from creating tables REVOKE CREATE ON SCHEMA public FROM public; # If you want to grant a write user permission to create tables # note that superusers will always be able to create tables anyway GRANT CREATE ON SCHEMA public to writeuser; # Now create the read-only user CREATE ROLE readonlyuser WITH LOGIN ENCRYPTED PASSWORD 'strongpassword'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonlyuser; If your read-only user doesn't have permission to list tables (i.e. \d returns no results), it's probably because you don't have USAGE permissions for the schema. USAGE is a permission that allows users to actually use the permissions they have been assigned. What's the point of this? I'm not sure. To fix: # You can either grant USAGE to everyone GRANT USAGE ON SCHEMA public TO public; # Or grant it just to your read only user GRANT USAGE ON SCHEMA public TO readonlyuser; A: Reference taken from this blog: Script to Create Read-Only user: CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234' NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity'; \connect YourDatabaseName; Assign permission to this read-only user: GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User; GRANT USAGE ON SCHEMA public TO Read_Only_User; GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User; REVOKE CREATE ON SCHEMA public FROM PUBLIC; Assign permissions to read all newly tables created in the future ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User; A: I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default. A: I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!! user@server:~$ sudo su - postgres create psql user: postgres@server:~$ createuser --interactive Enter name of role to add: readonly Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) n Shall the new role be allowed to create more new roles? (y/n) n start psql cli and set a password for the created user: postgres@server:~$ psql psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14) Type "help" for help. postgres=# alter user readonly with password 'readonly'; ALTER ROLE connect to the target database: postgres=# \c target_database psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14) You are now connected to database "target_database" as user "postgres". grant all the needed privileges: target_database=# GRANT CONNECT ON DATABASE target_database TO readonly; GRANT target_database=# GRANT USAGE ON SCHEMA public TO readonly ; GRANT target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ; GRANT alter default privileges for targets db public shema: target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; ALTER DEFAULT PRIVILEGES A: Taken from a link posted in response to despesz' link. Postgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of: http://www.postgresql.org/docs/current/interactive/sql-grant.html Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)." This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES". Also present is information about how GRANT functionalities compare to SQL standards. A: CREATE USER username SUPERUSER password 'userpass'; ALTER USER username set default_transaction_read_only = on;
    unknown
    d372
    train
    You could debug the action, then look what exception gets thrown. Then you can easily try-catch this line of code and if if fails, you give something different then 500 back. try { return //...; } catch (//your Exception) { return //... As Example BadRequest or something different } Hope it helps.
    unknown
    d373
    train
    I would probably write the threshold function the following way, taking advantage of the Timestamp combinator. public static IObservable<U> TimeLimitedThreshold <T,U> ( this IObservable<T> source , int count , TimeSpan timeSpan , Func<IList<T>,U> selector , IScheduler scheduler = null ) { var tmp = scheduler == null ? source.Timestamp() : source.Timestamp(scheduler); return tmp .Buffer(count, 1).Where(b=>b.Count==count) .Select(b => new { b, span = b.Last().Timestamp - b.First().Timestamp }) .Where(o => o.span <= timeSpan) .Select(o => selector(o.b.Select(ts=>ts.Value).ToList())); } As an added convenience when the trigger is fired the complete buffer that satisfies the trigger is provided to your selector function. For example var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount(); IObservable<string> fastKeySequences = keys.TimeLimitedThreshHold ( 3 , TimeSpan.FromSeconds(5) , keys => String.Join("", keys) ); The extra IScheduler parameter is given as the Timestamp method has an extra overload which takes one. This might be useful if you want to have a custom scheduler which doesn't track time according to the internal clock. For testing purposes using an historical scheduler can be useful and then you would need the extra overload. and here is a fully working test showing the use of a schedular. ( using XUnit and FluentAssertions for the Should().Be(..) ) public class TimeLimitedThresholdSpec : ReactiveTest { TestScheduler _Scheduler = new TestScheduler(); [Fact] public void ShouldWork() { var o = _Scheduler.CreateColdObservable ( OnNext(100, "A") , OnNext(200, "B") , OnNext(250, "C") , OnNext(255, "D") , OnNext(258, "E") , OnNext(600, "F") ); var fixture = o .TimeLimitedThreshold (3 , TimeSpan.FromTicks(20) , b => String.Join("", b) , _Scheduler ); var actual = _Scheduler .Start(()=>fixture, created:0, subscribed:1, disposed:1000); actual.Messages.Count.Should().Be(1); actual.Messages[0].Value.Value.Should().Be("CDE"); } } Subscribing and is the following way IDisposable subscription = fastKeySequences.Subscribe(s=>Console.WriteLine(s)); and when you want to cancel the subscription ( clean up memory and resources ) you dispose of the subscription. Simply. subscription.Dispose() A: Here's an alternative approach that uses a single delay in favour of buffers and timers. It doesn't give you the events - it just signals when there is a violation - but it uses less memory as it doesn't hold on to too much. public static class ObservableExtensions { public static IObservable<Unit> TimeLimitedThreshold<TSource>( this IObservable<TSource> source, long threshold, TimeSpan timeLimit, IScheduler s) { var events = source.Publish().RefCount(); var count = events.Select(_ => 1) .Merge(events.Select(_ => -1) .Delay(timeLimit, s)); return count.Scan((x,y) => x + y) .Where(c => c == threshold) .Select(_ => Unit.Default); } } The Publish().RefCount() is used to avoid subscribing to the source more than one. The query projects all events to 1, and a delayed stream of events to -1, then produces a running total. If the running total reaches the threshold, we emit a signal (Unit.Default is the Rx type to represent an event without a payload). Here's a test (just runs in LINQPad with nuget rx-testing): void Main() { var s = new TestScheduler(); var source = s.CreateColdObservable( new Recorded<Notification<int>>(100, Notification.CreateOnNext(1)), new Recorded<Notification<int>>(200, Notification.CreateOnNext(2)), new Recorded<Notification<int>>(300, Notification.CreateOnNext(3)), new Recorded<Notification<int>>(330, Notification.CreateOnNext(4))); var results = s.CreateObserver<Unit>(); source.TimeLimitedThreshold( 2, TimeSpan.FromTicks(30), s).Subscribe(results); s.Start(); ReactiveAssert.AssertEqual( results.Messages, new List<Recorded<Notification<Unit>>> { new Recorded<Notification<Unit>>( 330, Notification.CreateOnNext(Unit.Default)) }); } Edit After Matthew Finlay's observation that the above would also fire as the threshold is passed "on the way down", I added this version that checks only for threshold crossing in the positive direction: public static class ObservableExtensions { public static IObservable<Unit> TimeLimitedThreshold<TSource>( this IObservable<TSource> source, long threshold, TimeSpan timeLimit, IScheduler s) { var events = source.Publish().RefCount(); var count = events.Select(_ => 1) .Merge(events.Select(_ => -1) .Delay(timeLimit, s)); return count.Scan((x,y) => x + y) .Scan(new { Current = 0, Last = 0}, (x,y) => new { Current = y, Last = x.Current }) .Where(c => c.Current == threshold && c.Last < threshold) .Select(_ => Unit.Default); } }
    unknown
    d374
    train
    $(document).ready(function(){ if (location.hash) { $('a[href=' + location.hash + ']').tab('show'); } }); this is the solution i found it here here
    unknown
    d375
    train
    It looks like you init your manifest on the incorrect version of AOSP. See Downloading the Source for a good explanation of what you need to do to setup AOSP. The main part from there that you want though, is: repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1 Which would init your repository on AOSP version 4.0.1_r1. If you want to init on the l-preview branch, it would be: repo init -u https://android.googlesource.com/platform/manifest -b l-preview Just keep in mind this isn't actually android l's source code, its a GPL update. I am not sure if they have moved it over to using java version 1.7 yet, as I have not personally tried.
    unknown
    d376
    train
    Try running the library(caret) again, if the package is loaded, createDataPartition is there. If you still face the issue, check for Caret updates.
    unknown
    d377
    train
    you should fecth a row (at least) if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($conn, "SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value FROM `meed` WHERE Countries = '$countries'"); while( $row=mysqli_fetch_array($result,MYSQLI_ASSOC);) { echo json_encode([ $row['sum_projects'], $row['sum_value'] ] ); exit; } for the multiple countries Asuming you $_POST['countries'] contains "'Egypt','Algerie'" then you could use a query as "SELECT sum(SumofNoOfProjects) as sum_projects, sum(SumofTotalBudgetValue) as sum_value FROM `meed` WHERE Countries IN (" . $_POST['countries'] . ");"
    unknown
    d378
    train
    Live Demo std::string line; // get input from cin stream if (std::getline(cin, line)) // check for success { std::vector<std::string> words; std::string word; // The simplest way to split our line with a ' ' delimiter is using istreamstring + getline std::istringstream stream; stream.str(line); // Split line into words and insert them into our vector "words" while (std::getline(stream, word, ' ')) words.push_back(word); if (words.size() % 2 != 0) // if word count is not even, print error. std::cout << "Word count not even " << words.size() << " for string: " << line; else { //Remove the last word from the vector to make it odd words.pop_back(); std::cout << "Original: " << line << endl; std::cout << "New:"; for (std::string& w : words) cout << " " << w; } } A: You could write something like this int count = -1; for (auto it =input.begin();it!=input.end();){ if(*it==' '){ count++;it++; if (count%2==0){ while (it != input.end()){ if (*it==' ')break; it=input.erase (it); } }else it++; }else it++; }`
    unknown
    d379
    train
    You can encode these as you would encode a binary number, by assigning increasing powers of two for each column. You want to multiply each row by c(1,2,4) and then take the sum. # The multiplier, powers of two x <- 2^(seq(ncol(df))-1) x ## [1] 1 2 4 # The values apply(df, 1, function(row) sum(row*x)) ## row1 row2 row3 ## 4 1 2 To add this as a new column: df$new <- apply(df, 1, function(row) sum(row*x)) df ## X1 X2 X3 new ## row1 0 0 1 4 ## row2 1 0 0 1 ## row3 0 1 0 2 A: Try: > df X1 X2 X3 row1 0 0 1 row2 1 0 0 row3 0 1 0 > > > mm = melt(df) No id variables; using all as measure variables > > mm$new = paste(mm$variable,mm$value,sep='_') > > mm variable value new 1 X1 0 X1_0 2 X1 1 X1_1 3 X1 0 X1_0 4 X2 0 X2_0 5 X2 0 X2_0 6 X2 1 X2_1 7 X3 1 X3_1 8 X3 0 X3_0 9 X3 0 X3_0 mm$new is the column you want. A: Maybe this is what you want: > df$X1 = ifelse(df$X1==0,'green','yellow') > df$X2 = ifelse(df$X2==0,'red','blue') > df$X3 = ifelse(df$X3==0,'black','white') > > df X1 X2 X3 row1 green red white row2 yellow red black row3 green blue black > > unlist(df) X11 X12 X13 X21 X22 X23 X31 X32 X33 "green" "yellow" "green" "red" "red" "blue" "white" "black" "black"
    unknown
    d380
    train
    You have quote issues as mentioned, but the main issue is you have inline event handlers in the generated html. That is not a good idea. If you need to add actions to generated elements, use the data-nameinlowercase="value" on the elements, then assign the event handlers using $("#container").on("event name","element selector",function() { someFunction($(this).data("nameinlowercase")); }); which will handle future elements too In your case '<div class="caret" data-togglename="ul#'+selectName+'-menu"></div>' and $("#caretParentContainerId").on("click",".caret",function() { $($(this).data("togglename")).toggle(); }); where caretParentContainerId is the ID of the container that wraps the .caret elements A: The problem is in the double quotes inside others double quotes, like this <li onclick="something="something more" something else"></li> If you want keep your code structure try this: menu += '<li onclick="$(\'#' + selectName + '-text\').text(\'' + optStr + '\');$(\'#' + selectName + '-menu\').hide();$(\'input[name=' + selectName + ']\').prop(\'value\', \'' + optVal + '\');">' + optStr + '</li>'; but I think it's better you do something like this: menu += '<li onclick="myFunction(' + selectName + ", " + optStr + ", " + optVal + ')">' + optStr + '</li>'; and create a function like this: function myFunction(selectName, optStr, optVal) { $("#" + selectName + "-text").text(optStr); $("#" + selectName + "-menu").hide(); $("input[name='" + selectName + "']").prop("value", optVal); } With this is easier to debug and simplifly your code.
    unknown
    d381
    train
    You can't nest your execute() like that. The best solution is to toss that list of members into an array() once, close your connection, and THEN iterate that array and update each record. It should look like this: $select_members_info_stmt->bind_param('ssss', $leader, $member_1, $member_2, $member_3); $select_members_info_stmt->execute(); $select_members_info_stmt->bind_result($selected_username, $level, $experience, $playergold, $required_experience); $members = array(); while($select_members_info_stmt->fetch()) { // tossing into the array $members[] = array( 'selected_username' =>$selected_username, 'level' => $level, 'experience' => $experience, 'playergold' => $playergold, 'required_experience' => $required_experience ); } $select_members_info_stmt->close(); // Now iterate through the array and update the user stats foreach ($members as $m) { if($update_user_stats_stmt = $mysqli->prepare("UPDATE members SET level = ?, experience = ?, playergold = ? WHERE username = ?")) { // Note that you need to use $m['selected_username'] here. $update_user_stats_stmt->bind_param('iiiiis', $new_level, $new_experience, $new_gold, $now, $cooldown, $m['selected_username']); $update_user_stats_stmt->execute(); if($update_user_stats_stmt->affected_rows == 0) { echo '<div>Because of a system error it is impossible to perform a task, we apologize for this inconvience. Try again later.</div>'; } $update_user_stats_stmt->close(); } else { printf("Update user stats error: %s<br />", $mysqli->error); } } A: You cannot nest actively running prepared statements on the same connection to mysql. Once you call execute() on any statement you cannot run another one on the same connection until that prepared statement is closed. Any fetches on the first prepared statement will fail once you start executing on the second one. Only one 'live' statement can be prepared and running on the mysql server per connection If you really need to nest your prepared statements, you could establish 2 separate mysqli connections.
    unknown
    d382
    train
    I assume the delivery_confirmation method in reality returns a Mail object. The problem is that ActionMailer will call the deliver method of the mail object. You've set an expectation stubbing out the delivery_confirmation method but you haven't specified what should be the return value. Try this mail_mock = double(deliver: true) # or mail_mock = double(deliver_now: true) expect(mail_mock).to receive(:deliver) # or expect(mail_mock).to receive(:deliver_now) allow(OrderMailer).to receive(:delivery_confirmation).with(order).and_return(mail_mock) # the rest of your test code A: If I got you right, expect_any_instance_of(OrderMailer).to receive(:delivery_confirmation).with(order) will test the mailer instance that will receive the call. For more precision you may want to set up your test with the particular instance of OrderMailer (let's say order_mailer) and write your expectation the following way expect(order_mailer).to receive(:delivery_confirmation).with(order)
    unknown
    d383
    train
    When you are in the app on another screen and press back button that time you go to the back screen. and when your screen is home or login, and that time within two seconds you press twice the time back button app is closed. public astTimeBackPress = 0; public timePeriodToExit = 2000; constructor( public toastController: ToastController, private platform: Platform, private nav: NavController, private router: Router, ) { } handleBackButton() { this.platform.backButton.subscribe(() => { if (this.loaderOff) { document.addEventListener( 'backbutton', () => {}, false); } else { if ( this.router.url === '/tabs/home' || this.router.url === '/signin' ) { if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) { navigator['app'].exitApp(); } else { this.presentToast('Press again to exit'); this.lastTimeBackPress = new Date().getTime(); } } else { this.nav.back(); } } }); } async presentToast(msg, color = 'dark') { const toast = await this.toastController.create({ color, message: msg, duration: 3000, showCloseButton: true, closeButtonText: 'Close', }); toast.present(); } A: public void callAlert(){ AlertDialog.Builder builder1 = new AlertDialog.Builder(appCompatActivity); builder1.setMessage("Do you want to close."); builder1.setCancelable(true); builder1.setPositiveButton( "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); finish(); } }); builder1.setNegativeButton( "No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { callAlert(); return true; } return super.onKeyDown(keyCode, event); }
    unknown
    d384
    train
    You have following solution may be any one help you. 1) Add in .css and meta tags as follow. html { -webkit-text-size-adjust: none; /* Never autoresize text */ } and meta tags as follow <meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0;'> 2) You can also inject both into an existing website, using this javascript code as follow. var style = document.createElement(\"style\"); document.head.appendChild(style); style.innerHTML = "html{-webkit-text-size-adjust: none;}"; var viewPortTag=document.createElement('meta'); viewPortTag.id="viewport"; viewPortTag.name = "viewport"; viewPortTag.content = "width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"; document.getElementsByTagName('head')[0].appendChild(viewPortTag); and Use UIWebViewDelegate (webViewDidFinishLoad) method - (void)webViewDidFinishLoad:(UIWebView *)webView{ NSString *javascript = @"var style = document.createElement(\"style\"); document.head.appendChild(style); style.innerHTML = \"html{-webkit-text-size-adjust: none;}\";var viewPortTag=document.createElement('meta');viewPortTag.id=\"viewport\";viewPortTag.name = \"viewport\";viewPortTag.content = \"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\";document.getElementsByTagName('head')[0].appendChild(viewPortTag);"; [webView stringByEvaluatingJavaScriptFromString:javascript]; } A: you can implement webView delegate and change font when load webView. func webViewDidStartLoad(webView : UIWebView) { //your code }
    unknown
    d385
    train
    You declared the generic type bound in the wrong place. It should be declared within the declaration of the generic type parameter: public final <T extends MyObject> T getObject(Class<T> myObjectClass) { //... }
    unknown
    d386
    train
    After many things, I could figure out the solution. In fact, there is no problem to make a window 100 x 50 px or even smaller. The problem is that I had to close the window of the simulator before run again. In my case, such a small window had no Title bar and no close button. So I had to publish with the Title bar, close it, stop the running and then I could run again with the new size and position I give to the window. So, without closing the window in the simulator it is not possible to see the results of a new size.
    unknown
    d387
    train
    I think inheritance is a good approach to this problem. I can think of two down sides: * *It is possible to create additional columns to the inheritance children. If you control DDL, you can probably prevent that. *You still have to create and modify indexes on all inheritance children individually. If you are using PostgreSQL v11 or later, you could prevent both problems by using partitioning. The individual tables would then be partitions of the “template” table. This way, you can create indexes centrally by creating a partitioned index on the template table. The disadvantage (that may make this solution impossible) is that you need a partitioning key column in the table.
    unknown
    d388
    train
    You first need to get a list of the user friends calling /me?fields=friends. Then, you can only add their id to the picture urls just like you did with the user: <img src="https://graph.facebook.com/{{friend_id}}/picture">
    unknown
    d389
    train
    Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene. // Update is called once per frame void Update() { Vector3 newpos = Playerposition.position + cameraoffset; transform.position = newpos; } If this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update().
    unknown
    d390
    train
    You likely have overridden get_api_root_view without providing the api_url argument since it's already part of DRF: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L292 A: I had the same error. I found I had an older version of drf-extensions. I have a feeling drf-extensions overrides the get_api_root_view method, and when it's not in sync with your version of Django Rest Framework, this can cause a problem (ie. drf-extensions is passing a parameter that DRF no longer expects, but in previous versions was acceptable). If it's not drf-extensions specifically, it's probably something else that's overriding get_api_root_view as Linovia suggested.
    unknown
    d391
    train
    You probably have register_globals turned on so $classes gets mixed with $_SESSION['classes'] at some point. You should turn them off. (Here's why.) Or, if turning them off is not possible due to whatever reason, change variable names. A: Got it! Here's my new code: <?php $classesBeingTaught[] = explode(",", $_SESSION['classes']); foreach ($classesBeingTaught[0] as $classBeingTaught) { echo "<option>".$classBeingTaught."</option>"; } ?>
    unknown
    d392
    train
    Your code uses the old and deprecated not/1 predicate, which apparently is not supported in the Prolog system you're using, hence the existence error. Use instead the standard \+/1 predicate/prefix operator: is_not_immune_to(Pkmn, AtkType) :- is_type(Pkmn, Type), \+ immune(Type, AtkType). With this change, you get for your sample call: | ?- is_not_immune_to(charizard, ground). true ? ; no
    unknown
    d393
    train
    Your code is sound. You just need to include this in the beginning of your ui: ui <- fluidPage( useShinyjs(), # add this # rest of your ui code )
    unknown
    d394
    train
    use this $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); instead of $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); i think it is better to use CURL instead of socket
    unknown
    d395
    train
    If you want the Edit control to be different than the standard control, you should use the "EditItemTemplate". This will allow the edit row to have different controls, values, etc... when the row's mode changes. Example: <Columns> <asp:TemplateField HeaderText="PC"> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("82_PC").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked="true" Enabled="false" /> </EditItemTemplate> </asp:TemplateField> </Columns> A: I guess you could loop through all the rows of the GridView and enable the checkboxes something like below: protected void grd_Bookcode_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") { for (int index = 0; index < GridView1.Rows.Count; index++) { CheckBox chk = grd_Bookcode.Rows[index].FindControl("CheckBox" + index + 1) as CheckBox; chk.Enabled = true; } } } Hope this helps!!
    unknown
    d396
    train
    To correct this problem I had to * *uninstall app on Android phone (important step) *Unload Android Project from solution explorer *This brings up the project file code now search code for <EmbedAssembliesIntoApk>false</EmbedAssembliesIntoApk> *Change false to true save *reload project problem solved. Note leave fast deploy checked. A: Go to >> Solution Properties>> Android Options>> Uncheck "Use Fast Deployment(debug mode only)" A: I had the same issue recently after adding images to my project found out that I had upper case letters as a name SomePicture.png renaming all images to lower case solved it. A: @AlwinBrabu, I think you meant "Project Properties" -> Android Options -> Uncheck Fast Deployment(debug mode only). This worked for me, although this is a workaround. I do not consider it a solution. A: To solve this, I had to right-click on the Android project in the Solution Explorer, then in Options -> Android Build uncheck the Fast Assembly Deployment option. Then deploy the project on the Android emulator. But after deploying it once, I went back to the settings and checked (i.e. ticked) the Fast Assembly Deployment option, and subsequent deploys worked fine. I'm running Visual Studio for Mac 2022 version 17.0.1 (build 72).
    unknown
    d397
    train
    It is possible but your type must be global create type array_t is varray(2) of int; Then use array as a table (open p for only for compiling) declare array_test array_t := array_t(10,11); p sys_refcursor; begin open p for select * from STATISTIK where abschluss1 in (select column_value from table(array_test )); end;
    unknown
    d398
    train
    You can try via pd.to_numeric() and then fill NaN's: df['Feature2']=pd.to_numeric(df['Feature2'], errors="coerce").fillna(df['Feature2']) OR go with the where() condition by filling those NaN's with fillna() in your condition ~df.Feature2.str.isnumeric(): df['Feature2']=df['Feature2'].where(~df.Feature2.str.isnumeric().fillna(True), pd.to_numeric(df.Feature2, errors="coerce").astype("Int64") )
    unknown
    d399
    train
    You seem to be saying that you want your function to take a variable number of separate arrays as arguments, and then find the maximum number within any of those arrays. If so, you can say [].concat(...arguments) to create a single new array with all of the values from the individual arrays that were arguments, then use the spread operator to pass that new array to Math.max(). (You don't need a loop.) var firstArr = [1,2,3,4,5]; var secondArr = [6,7,8,9]; function myFun() { var resl = Math.max(...[].concat(...arguments)); console.log("The maximum value is " + resl); } myFun(firstArr, secondArr); A: It sounds like what you are trying to do is function myFun(...arrays) { const allValues = [].concat(...arrays); return Math.max(...allValues); } console.log("The maximum value is " + myFun([1,2,3,4,5], [6,7,8,9])); However I would recommend to avoid spread syntax with potentially large data, and go for function myFun(...arrays) { return Math.max(...arrays.map(arr => Math.max(...arr))); } or even better function myFun(...arrays) { return arrays.map(arr => arr.reduce(Math.max)).reduce(Math.max); } A: You can use rest element at function declaration, pass an array of arrays each preceded by spread element to function parameters and spread element within function function myFun(...arr) { return Math.max.apply(Math, ...arr) } myFun([...firstArr, ...secondArr /*, ...nArr*/ ]);
    unknown
    d400
    train
    The web service does not enable the type-based optimizations by default. So to get the equivalent functionality: java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --use_types_for_optimization=false --js /code/built.js --js_output_file compiledCode.js The web service also assumes any undefined symbol is an external library. For this reason it is not recommended for production use.
    unknown