{ // 获取包含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 !== 'GitHub加速' && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; 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 !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== 'VoxCPM' ) { link.textContent = 'VoxCPM'; link.href = 'https://voxcpm.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'IndexTTS2' ) { link.textContent = 'IndexTTS2'; link.href = 'https://vibevoice.info/indextts2'; 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, 'GitHub加速'); } 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\nA:\n\nI suggest you may need to consider people's feeling when you post such long codes with poor comments.\nYour problem is you are not awareness the coordinate system of SVG where the y points to bottom. The following is a little modification:\nsvg.selectAll(\"circle\")\n .data(inputData)\n .enter()\n .append(\"circle\")\n .attr(\"cx\", function(d){\n let thisDate = x(new Date(d.date[0], d.date[1], d.date[2]));\n return thisDate;\n })\n\n // this is the KEY part you should change:\n .attr(\"cy\", function(d, i){ return h - padding - y(d.value); })\n\n .attr(\"r\", 1)\n .attr(\"fill\", \"red\");\n\nSince you don't offer detail data, I can't check it. hope it will help!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28616,"cells":{"text":{"kind":"string","value":"Q:\n\nSequences with PL SQL\n\nI know how to create a sequence in pl sql. However, how would I set the values to all have say 3 digits? is there another sql statement to do this when I create a sequence?\nso an example would be:\n000\n001\n012\n003\n\nThanks guys!\n\nA:\n\nFirst, just to be clear, you do not create sequences in PL/SQL. You can only create sequences in SQL.\nSecond, if you want a column to store exactly three digits, you would need the data type to be VARCHAR2 (or some other string type) rather than the more common NUMBER since a NUMBER by definition does not store leading zeroes. You can, of course, do that, but it would be unusual.\nThat said, you can use the \"fm009\" format mask to generate a string with exactly 3 characters from a numeric sequence (the \"fm\" bit is required to ensure that you don't get additional spaces-- you could TRIM the result of the TO_CHAR call as well and dispense with the \"fm\" bit of the mask).\nSQL> create table t( col1 varchar2(3) );\n\nTable created.\n\nSQL> create sequence t_seq;\n\nSequence created.\n\nSQL> ed\nWrote file afiedt.buf\n\n 1 insert into t\n 2 select to_char( t_seq.nextval, 'fm009' )\n 3 from dual\n 4* connect by level <= 10\nSQL> /\n\n10 rows created.\n\nSQL> select * from t;\n\nCOL\n---\n004\n005\n006\n007\n008\n009\n010\n011\n012\n013\n\n10 rows selected.\n\nA:\n\nhaven't used plsql in a while, but here goes:\ngiven an integer sequence myseq, \nto_char(myseq.nextval, '009')\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28617,"cells":{"text":{"kind":"string","value":"Q:\n\nGet Previous item in a list\n\nI've a previous/next setup in the works, and the next functionality is working fine (although, that was created by someone else a while back). As for the previous button, that is giving me a few problems.\nHere is the code so far:\n private Item getPrevious()\n {\n Item CurrentItem = Sitecore.Context.Item;\n var blogHomeID = \"{751B0E3D-26C2-489A-8B8C-8D40E086A970}\";\n Item BlogItem =db.Items.GetItem(blogHomeID);\n Item[] EntryList= BlogItem.Axes.SelectItems(\"descendant::*[@@templatename='BlogEntry']\");\n\n Item prevEntry = null;\n\n for (int i = 0; i < EntryList.Length; i++)\n {\n if (EntryList[i] == CurrentItem)\n {\n return prevEntry;\n }\n\n prevEntry = EntryList[i];\n }\n }\n\nI get that you need to subtract 1 from the current item in the list to get the previous, but so far, all this seems to do is display the exact same entry for the previous button. It's always the latest entry in the list, not the previous one. I feel like this shouldn't be so difficult but it could be the old code I'm trying to work with. Not sure.\n\nA:\n\nYou can use the GetPreviousSibling() and GetNextSibling() methods:\nSitecore.Context.Item.Axes.GetPreviousSibling()\n\nSitecore.Context.Item.Axes.GetNextSibling()\n\nThese will return the previous and next sibling, or null if the current item is the first/last respectively.\nIf you want to restrict by template type then you can use the preceding and following xpath queries:\nItem previous = Sitecore.Context.Item.Axes.SelectItems(\"./preceding::*[@@templateid='{template-guid}']\").LastOrDefault();\n\nItem next = Sitecore.Context.Item.Axes.SelectSingleItem(\"./following::*[@@templateid='{template-guid}']\");\n\nNote the use of SelectItems and LastOrDefault() on the first query. Both queries give you a list of Items sorted by order.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28618,"cells":{"text":{"kind":"string","value":"Q:\n\nLet's kill all the [character]s\n\nDoes this site really need a character tag?\nNearly every question is about some character in one way or another. And character wouldn't work as the sole tag on a question, which makes it a meta tag and therefore undesirable, according to SE central policy.\nThe purpose of tags is supposed to be for experts in a given subject to find questions to answer on that subject, but there are obviously no experts on characters in general.\nI propose the burnination of the character tag.\nWho's with me?\n\nA:\n\nI think that this tag is useless. \nNo one is going to look for all of the questions about all characters in all movies or TV shows. \nMost questions with this tag are about a specific character in a specific film... Which means that the film tag should be more than sufficient. There's no need to further point out \"hey, this question is just about one character\"... and the spotty usage of it shows that it's not helpful.\nHere are a few questions that are about \"characters\", have fewer than five tags and yet, don't have the character tag.\n\nIs there any hint as to why Jerry needs the money?\nWhy was Ian's onset of Bipolar Disorder so fast?\nWhy did Major Hellstrom get suspicious?\nWhy did Apocalypse say this?\nWhy didn't Pietro Maximoff tell Magneto they were related?\nWhy was this specific character in Age Of Ultron killed off?\n\nAnd that's just from the front page and it's just the ones I absolutely know \"should\" have it.\nIf we're going to use it to classify questions but most of the questions that \"deserve\" it don't have it... then the tag is useless. Get rid of it.\n\nA:\n\nI don't think that this tag, character, is useless. \n\"Nearly every question is about some character\". It's good word choice: \"near\" ...it`s not the same than all. I've made questions about characters myself and I like them: one question with over 5 votes on Hodor, from Game of Thrones, and others less popular questions on Gilfoyle, from Silicon Valley, and even on God, in Supernatural. Maybe vote popularity has to do with show/movie popularity, so that might not be such a huge issue. Just my opinion.\nOn the other hand they're tons of tags not related to characters, just some to mention: film-techniques, production, animation, soundtrack, title, effects, props, among the most used tags on site.\nThe second point: that \"character wouldn't work as the sole tag on a question\" seems sound. However, keeping the tag even as a secondary one can help to do cross searches on a topic, such as different aspects of a movie. For example it's not the same between these two sets of tags:\n\nfight-club, props, ending, production\nfight-club, character, dialogue, analysis, plot-explanation \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28619,"cells":{"text":{"kind":"string","value":"Q:\n\nhow to get gradle embeded common value in build.gradle\n\nI am define a public dependencies in common.build like this(Gradle 6.0.1):\next {\n java = [\n compileSdkVersion: 1.8,\n minSdkVersion : 1.8,\n targetSdkVersion : 1.8,\n versionCode : 1.8,\n ]\n\n version = [\n mybatisGeneratorCoreVersion : '1.3.7',\n itfswMybatisGeneratorPluginVersion: '1.3.8'\n ]\n\n dependencies = [\n mybatisGeneratorCore : \"org.mybatis.generator:mybatis-generator-core:${version[\"mybatisGeneratorCoreVersion\"]}\",\n ]\n}\n\nand using in root project build.gradle like this:\nsubprojects {\n apply from: \"${rootProject.projectDir}/common.gradle\"\ndependencies {\n implementation rootProject.ext.dependencies.mybatisGeneratorCore\n }\n}\n\nand build the project like this:\n./gradlew clean :soa-illidan-mini:soa-illidan-mini-service:build -x test\n\nand give me this error:\n~/Library/Mobile Documents/com~apple~CloudDocs/Document/source/dabai/microservice/soa-illidan-mini on  master! ⌚ 10:59:03\n$ ./gradlew clean :soa-illidan-mini:soa-illidan-mini-service:build -x test\n\nFAILURE: Build failed with an exception.\n\n* Where:\nBuild file '/Users/dolphin/Library/Mobile Documents/com~apple~CloudDocs/Document/source/dabai/microservice/build.gradle' line: 99\n\n* What went wrong:\nA problem occurred evaluating root project 'microservice'.\n> Cannot get property 'dependencies' on extra properties extension as it does not exist\n\n* Try:\nRun with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.\n\n* Get more help at https://help.gradle.org\n\nBUILD FAILED in 12s\n\nI am followed by internet tutorals ,what should I do to fix this problem?\n\nA:\n\nmove your apply command to root of build.gradle like this:\napply from: \"${rootProject.projectDir}/common.gradle\"\n\njust put it to top level of your project config. It works!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28620,"cells":{"text":{"kind":"string","value":"Q:\n\n\"Can't find API database; API check was not performed\" in Android App SDK with Eclipse\n\nI'm starting a new Android App using the Android SDK on Eclipse, build tools 19.0.2, on a Windows 7 PC. At some point during my work, I started receiving the error \"Can't find API database; API check was not performed\". This error is not shown in the code but instead shows a red X in the project folder and a line one error in the Problems window. There is a previous question on this topic but that did not work for me. I have already tried adjusting the target and minimum SDK versions in the manifest and re-installed the SDK multiple times. This problem also occurs with the only other project in my work space and shows the same error. Thanks in advance for any help. \n\nA:\n\nFor me, Eclipse --> Project --> Clean... is enough set everything right again:\n\nA:\n\nFollowing works for me:\n\nMake sure you installed SDKs listed in your manifest.xml, i.e. mini version and target version.\nClick the icon with red x on the right hand side tool bar, which has tip of 'Problems(...)' if you move your cursor over it.\nRight click on your error, choose quick fix.\nChoose Disable Check in This Project\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28621,"cells":{"text":{"kind":"string","value":"Q:\n\nWhen to instantiate a struct explicitly?\n\ni'm coming from Java, and there you always do something like:\nHttp http = new Http(...);\n\nhttp.ListenAndServe();\n\nSo all information are stored in the local variable \"http\".\nIt's different in go. There most of the information is stored directly \"in another package\".\nYou do:\nimport \"net/http\"\n... \nhttp.ListenAndServe(...)\n\nSo you dont have to explicitly (well you could) instantiate a server struct. Just call a function from the package and all the structs will be created from there. (So compared to Java, it acts like static functions with static member variables to store all information ?)\nSo this is how you do it (everytime) in go ?\nComing from Java, this is a little bit hard to understand.\nEspecially when to use this method, when to use a factory pattern (like: NewHttpServer(...) ) and when to explicitly create a struct from another package ( like: var http http.Server = http.Server{...} )\nEverything might be possible, but what is the idiomatic golang code ?\nIs there any good document/tutorial which explains it ?\n\nA:\n\nI'd really suggest reading the Godoc for net/http. The package is very feature-rich and lets you do what you want.\nThe behaviour of http.ListenAndServe is to implicitly use a serve multiplexer known as DefaultServeMux, on which you can register handlers with http.Handle. So you can't deal with the server or multiplexer explicitly like this.\nIt sounds like what you want (a more Java-like solution) is to instantiate a server\ns := &http.Server{\n Addr: \":8080\",\n Handler: myHandler, // takes a path and a http.HandlerFunc\n ReadTimeout: 10 * time.Second, // optional config\n WriteTimeout: 10 * time.Second, // ...\n MaxHeaderBytes: 1 << 20,\n}\n\nand call ListenAndServe on that:\nlog.Fatal(s.ListenAndServe())\n\nBoth ways are totally idiomatic, I've seen them used quite frequently.\nBut seriously, don't take my word for it. Go look at the docs, they have lots of examples :)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28622,"cells":{"text":{"kind":"string","value":"Q:\n\nRails 5.1: refresh partial within partial with AJAX\n\nI have partial _navigation.html.erb where there is this piece of code:\n
\n \n \n \n
\n <%= render 'users/user', user: current_user %>\n \n
\n
\n
\n
\n
    \n
  • <%= link_to t('.profile'), edit_user_path(current_user), remote: true %>
  • \n
  • \n
  • <%= link_to t('.logout'), logout_path %>
  • \n
\n
\n\nI render User name in this _user.html.erb partial:\n<%= user.name %>\n\nWhen I login, I see my current_user name in navigation partial as expected. However when I try to Update my User name (modal window), I don't see my current_user value changes in _user.html.erb partial.\nMy users_controller.rb Update action looks like this:\n def update\n @user.update(user_params)\n respond_to do |format|\n format.json { update_flash }\n format.js { update_flash }\n end\n end\n\n private\n\n def user_params\n params.require(:user).permit(:name, :email, :password, :password_confirmation,\n :locale, :menu_role, :psw_change,\n {company_ids: []}, {user_group_ids: []})\n end\n\n def correct_user\n users = User.where(id: helpers.users_all)\n @user = User.find(params[:id])\n redirect_to(errors_path) unless users.include?(@user)\n end\n\n def update_flash\n flash[:notice] = \"#{@user.name.unicode_normalize(:nfkd)\n .encode('ASCII', replace: '')} \", t(:updated)\n end\n\nupdate.js.erb looks like this:\n$('#dialog').modal('toggle');\n$('#userprofile %>').replaceWith('<%= j render (@user) %>')\n\nI see clearly in my console Update action is done, my files are rendered, no errors:\n Rendering users/update.js.erb\n Rendered users/_user.html.erb (0.6ms)\n Rendered users/update.js.erb (8.5ms)\nCompleted 200 OK in 126ms (Views: 41.1ms | ActiveRecord: 16.0ms)\n\nWhat am I doing wrong here, please? It would be nice to be able to show updated current_user name in profile. I'll be happy for any hint, where should I be looking at. Thank you.\n\nA:\n\nIn update.js.erb, you have a typo. You should delete the %>. Try this:\n$('#userprofile').replaceWith('<%= j render (@user) %>')\n\nAlso, instead of replacing the entire #userprofile node, you may want to change the html inside of it instead:\n$('#userprofile').html('<%= j render (@user) %>')\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28623,"cells":{"text":{"kind":"string","value":"Q:\n\ngroup a list of triples into map with pair key\n\nI have a list of triples\nList> triplets; \n\nI want to group into a map like this\nMap, String> mapping;\n\nWhere value of the map is the third element of the triple. And in case of the same key it should override the remaining third value.\nFor example\ndef triples = [ {a, b, c} ; {a, d, e} ; {a, b, f } ]\n// grouping\ndef map = [ {a,b} : c ; {a, d} : e ]\n\nHow to do that using Java 8 and its grouping in streams?\n\nA:\n\nThis should do the trick:\nMap, String> result = triplets.stream()\n .collect(\n Collectors.toMap(\n t -> new Pair(t.getOne(), t.getTwo()),\n Triple::getThree,\n (v1, v2) -> v2\n )\n );\n\nExample of a partial pair class:\npublic class Pair {\n //...\n\n @Override\n public int hashCode() {\n return one.hashCode() + two.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Pair))\n return false;\n Pair p = (Pair) obj;\n return p.one.equals(one) && p.two.equals(two);\n }\n}\n\nThe HashMap class uses equals method to identify key objects uniquely. So you first need to override equals and hashcode methods to show the logical equality of the Pair objects for the Map class.\nThen come back to the streams and lambda. For each triplet use Collectors.toMap with the Pair object as the key and the other remaining value of the Triplet as the value. Then provide a mergeFunction to handle key conflicts. In your case, you need to keep the previous value while discarding new value. That's all you need to do.\nUpdate\nI have updated the merge function as per the below comments.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28624,"cells":{"text":{"kind":"string","value":"Q:\n\nGetting a French passport - born abroad to a French mother\n\nI was wondering if any of you have any experience with this:\nI am looking at getting a French passport. My mother is French and I was born in the UK. My birth was registered at the French Consulate in Liverpool.\nI understand that I am entitled to one. However, I am not sure which or what documents I must show them, and it isn't very clear online.\nWould I need to show them my birth certificate (which includes the names of my parents) and must it be legally translated into French?\nAnd would I also need to show a scanned copy of my mother's birth certificate, or must I provide them with the actual one?\nMoreover, do I have to show them a copy of my parent's marriage certificate?\nMany thanks in advance for any help or advice.\n\nA:\n\nWould I need to show them my birth certificate?\n\nThere is a page that discusses whether you need a birth certificate to apply for a passport. It says that one condition that relieves you of this requirement is:\n\nvous êtes né(e) à l’étranger et votre acte de naissance étranger a été transcrit dans les registres de l’état civil consulaire français.\n\nTranslation:\n\nyou were born abroad and your foreign birth certificate was transcribed in the French consular civil register.\n\nI presume that this second clause is what happened when your \"birth was registered at the French Consulate in Liverpool.\" If so, you don't need to show your birth certificate to apply for a passport. I suppose that you might in this case require a document recording or attesting to the transcription of your birth certificate, but I couldn't find anything saying that explicitly, so maybe you do not.\n\nAnd would I also need to show a scanned copy of my Mother's birth certificate, or must I provide them with the actual one?\n\nIt's not generally necessary to show your parents' birth certificates with a passport application, but if you are under 18 you'll need to show your mother's passport or identity card and livret de famille, the requirements for a first-time passport application for a minor being somewhat different from those for an adult.\nI assume here that the registration of your birth with the French consulate serves as your proof of French nationality. If it does not for some reason, you will need to have your French nationality certified as a separate step before you can apply for a passport. Doing that will of course require proving your mother's nationality, in which case her birth certificate may be of use.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28625,"cells":{"text":{"kind":"string","value":"Q:\n\nChart legend with row style cuts off\n\nI have a Chart in ASP.NET and C#. Whenever I have the chart legend style as row, it cuts off extra labels and displays three dots \"...\"\nIs there anyway to fix this or make the legend width larger without changing the chart width?\nHere is my code for the chart:\n\n \n \n \n\n \n \n \n\n \n \n \n\n \n \n \n\n\nAnd the code behind:\ncrtMain.Series[\"Default\"].ChartType = SeriesChartType.Pie;\n\ncrtMain.Series[\"Default\"].IsValueShownAsLabel = true;\n\ncrtMain.ChartAreas[\"crtArea\"].AxisY.LabelStyle.Format = \"c\";\ncrtMain.Series[\"Default\"].LabelFormat = \"c\";\n\ncrtMain.ChartAreas[\"crtArea\"].AxisX.LabelStyle.Font = new System.Drawing.Font(\"Arial\", 15F, System.Drawing.FontStyle.Bold);\ncrtMain.ChartAreas[\"crtArea\"].AxisY.LabelStyle.Font = new System.Drawing.Font(\"Trebuchet MS\", 15F, System.Drawing.FontStyle.Bold);\ncrtMain.Series[\"Default\"].Font = new System.Drawing.Font(\"Trebuchet MS\", 15F, System.Drawing.FontStyle.Bold);\ncrtMain.Legends[\"Default\"].Font = new System.Drawing.Font(\"Trebuchet MS\", 14F, System.Drawing.FontStyle.Bold);\n\n crtMain.Legends[0].Enabled = true;\n\nAnd picture of the issue:\n\nWhich is coming from the chart here:\n\nAny ideas at all?\nThanks in advance!\n\nA:\n\nUPDATE:\nSo I figured out how to do this.\nI simply put in the code behind:\ncrtMain.Legends[\"Default\"].IsTextAutoFit = true;\ncrtMain.Legends[\"Default\"].MaximumAutoSize = 100;\n\nThis expanded all the text so I could see every label.\nHopefully this will help someone in the future.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28626,"cells":{"text":{"kind":"string","value":"Q:\n\nExt Form with fileuploadfield (response after submit)\n\nCan`t really understand where is a mistake.. \nI have a form with fileuploadfield. Request is sended good, action on my controller gets all params, works with them, and sends response to browser. But in html page, after submiting the form, always fires FAILURE event, and never SUCCESS. \nClient Side Code\nExt.create('Ext.form.Panel', {\n renderTo: 'Container',\n bodyPadding: '10 10 0',\n items: [\n {\n xtype: 'form',\n width: 300,\n border: false,\n fileUpload: true,\n items: [\n {\n xtype: 'combobox',\n id: 'PayTypes',\n width: 215,\n store: PayTypesStore,\n valueField: 'id',\n displayField: 'Name',\n editable: false,\n name: 'id'\n }\n ,\n {\n xtype: 'filefield',\n id: 'form-file',\n name: 'file',\n buttonText: '',\n buttonConfig: {\n iconCls: 'upload-icon'\n }\n }\n ],\n buttons: [\n {\n text: 'Send',\n handler: function () {\n var form = this.up('form').getForm();\n if (form.isValid()) {\n form.submit({\n url: 'UploadFile',\n waitMsg: 'Uploading your photo...',\n success: function (fp, o) {\n console.log(\"success\");\n msg('Success', 'Processed file on the server');\n },\n failure: function (form, action) {\n console.log(action);\n Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');\n }\n });\n }\n }\n }\n ]\n }\n ]\n });\n\nServer Side Code:\npublic JsonResult UploadFile(HttpPostedFileWrapper file, int id)\n {\n var response = Json(new { success = true });\n response.ContentType = \"text/html\";\n\n return Json(response);\n }\n\nResponse, recieved on the client side:\n{\"ContentEncoding\":null,\"ContentType\":\"text/html\",\"Data\":\"success\":true},\"JsonRequestBehavior\":1,\"MaxJsonLength\":null,\"RecursionLimit\":null}\n\nWhat i need to fix in my code to get SUCCESS event after sumniting form?\n\nA:\n\nYou called Json method twice. The only thing you need is\npublic JsonResult UploadFile(HttpPostedFileWrapper file, int id)\n{\n return Json(new { success = true });\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28627,"cells":{"text":{"kind":"string","value":"Q:\n\nMensa Norway Question Help Please\n\nAnyone can please help with this question? Currently stuck here.\nSource: Mensa Norway\n\nA:\n\n Add the first two columns in a row to get the third column, or the first two rows in a column to get the third row. \n\n Nothing + Square = Square\n\n Nothing + Dot = Dot\n\n Two dots added together make a square.\n\n Two squares added together make a dot.\n\n Square + Dot cancel each other\n\nAnswer:\n\n \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28628,"cells":{"text":{"kind":"string","value":"Q:\n\nMule ESB and basic authentication\n\nI wrote a flow accepting JSON, now I want to add http authentication. I want to accept HTTP basic authentication uid and pw.\nSo I am starting with a Hellow World program first, as follows:\n\n\n \n \n \n \n\n\nAnd I test with the following program:\nC:\\curl>curl -H \"Content-Type: application/json\" -u uida:pw -d {\"first\":\"Steven\"\n} http://localhost:8081\nHello World\nC:\\curl>\n\nThis works, as there is no basic auth configured within th eflow, so it ignores the \"-u uid:pw\" I sent on the curl command\nNow I change the flow as follows ( I put 'uid' in the 'Http Settings->User' field, and 'pw' in the 'Http Seetings->Password' field on the GUI\n\n\n \n \n \n \n\n\nNow when I test I get the following:\nC:\\curl>curl -H \"Content-Type: application/json\" -u uida:pw -d {\"first\":\"Steven\"\n} http://localhost:8081\nCannot bind to address \"http://127.0.0.1:8081/\" No component registered on that\nendpoint\n\nI have done this repeatedly, but I get the same response.\nIs there another field that I should have set? Any ideas on how I can resolve this?\nThanks\n\nA:\n\nThe user and password attributes are ineffective on inbound HTTP endpoints, they only work on outbound.\nMule uses Spring Security for authentication. This is detailed in the user guide: http://www.mulesoft.org/documentation/display/current/Configuring+the+Spring+Security+Manager , including an example of the http-security-filter that you need to put in the HTTP inbound endpoint.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28629,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to get system (Windows) memory in R?\n\nDoes anyone know how to get the memory (RAM) used by the system from R?\nI'm using windows. memory.size() and mem_used() functions give you the memory used by R and R objects respectively, but they doesn't consider the memory already occupied by the system and other software. \n\nA:\n\nThis is one way using shell on Windows:\nshell('systeminfo | findstr Memory')\n#Total Physical Memory: 16,271 MB\n#Available Physical Memory: 8,011 MB\n#Virtual Memory: Max Size: 32,655 MB\n#Virtual Memory: Available: 24,040 MB\n#Virtual Memory: In Use: 8,615 MB\n\nYou could use a different string instead of Memory if you want more granular results.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28630,"cells":{"text":{"kind":"string","value":"Q:\n\nandroid gridview not showing top row\n\nI am using a gridview inside a relativelayout and im trying to make the whole grid show up on the screen. The top row is not completely showing..I am only getting the top right button to show. The grid is 4 columns and 6 rows. All of the rows show up besides the one at the top of the screen. My code is as follows:\n\n\n\n\n\nand my main.java is:\npublic class MainActivity extends Activity implements OnClickListener \n{\nprivate long startTime = 0L;\nprivate Handler customHandler = new Handler();\nprivate int game_running = 0;\nprivate int button_clicks = 0;\nprivate int previous_button_id = 0;\nprivate int current_button_id = 0;\nprivate CharSequence button_value = null;\nprivate CharSequence prevbutton_value = null;\nprivate int j = 0;\nprivate int isgameover = 0;\nboolean flag = false;\nboolean reset = false;\nlong gametime = 0;\nlong resettime = 0;\nlong timeInMilliseconds = 0L;\nlong timeSwapBuff = 0L;\nlong updatedTime = 0L;\nboolean resetbool = false;\nprivate ArrayList
text
stringlengths
175
47.7k
meta
dict
Q: Passing object to compare function makes sorting slow? I had the following code in my program. //Compare class class SortByFutureVolume { public: SortByFutureVolume(const Graph& _g): g(_g){} bool operator() (const Index& lhs, const Index& rhs){ return g.getNode(lhs).futureVolume() > g.getNode(rhs).futureVolume(); } private: Graph g; }; And then I use it for sorting like this: std::sort(nodes.begin(), nodes.end(),SortByFutureVolume(g)); When I run the above code on my mac computer for a vector of size 23K it completes in a fraction of seconds. However, when I run on my ubuntu 14 machine. It takes several minutes and it hasn't even completed yet. I search for this problem and found the following solution here Can I prevent std::sort from copying the passed comparison object Basically modifying my code as so fixes the problem: SortByFutureVolume s(g); std::sort(_nodes.begin(), _nodes.begin()+ end, std::ref(s)); After this the runtime on both my mac an ubuntu are comparable. Very much faster. I know that this works but I'm trying to understand why? I know that slow code above was due to copying of graph and SortByFutureVolume. Why do you need std::ref()? Is this solution even correct and is there a better way to do this? A: Instead of having a Graph data member in SortByFutureVolume you should have a Graph & or const Graph & if g can be read only. This way, anytime the SortByFutureVolume is copied the Graph is not copied. class SortByFutureVolume { public: SortByFutureVolume(const Graph& _g): g(_g){} bool operator() (const Index& lhs, const Index& rhs){ return g.getNode(lhs).futureVolume() > g.getNode(rhs).futureVolume(); } private: Graph& g; // or const Graph& g; }; As pointed out by Benjamin Lindley in the comments if You change SortByFutureVolume to store a pointer to the Graph instead of a refernece then SortByFutureVolume becomes copy assignable as pointers can be assigned but references cannot. That would give you class SortByFutureVolume { public: SortByFutureVolume(const Graph& _g): g(&_g){} bool operator() (const Index& lhs, const Index& rhs){ return g->getNode(lhs).futureVolume() > g->getNode(rhs).futureVolume(); } private: const Graph * g; }; As a side not it is okay to have _g as a variable name in a function parameter as it does not start with a capital letter but it is a good habit to not use leading underscores. This is doubly true in the global space where _g would be an invalid identifier as it is reserved for the implementation. A: std::ref is a pointer in disguise. What the code does is that instead of copying a heavy-weight SortByFutureVolume object, it copies around the pointer to the same object - which is obviously much faster. The option would be to make the Graph g a (const) reference inside the sorter object.
{ "pile_set_name": "StackExchange" }
Q: Is there anything like a Python JoinableDeque available? I'm relatively new to Python and looking for something like Python's JoinableQueue, but that has deque or stack-like behavior. Specifically, as I'm processing items in the queue in different processes, I'd like to be able to add new items to be processed before what's already in the queue (i.e. push onto the stack or add to the front of the deque). Java has BlockingDeque which does exactly what I want, but I can't really use Java for this project. Any pointers or new ways of thinking about this problem would be appreciated! A: With multiprocessing, queue semantics isn't just something implemented on top of inter-process communication but is inherent to it. Therefore, the simplest solution is probably to build a joinable stack by using a JoinableQueue and implementing pushes to the stack by first getting all tasks into a temporary queue, then queueing the new element and filling back the tasks from the temporary queue. Pushing to the stack from different processes would require some locking to maintain the order of the stack.
{ "pile_set_name": "StackExchange" }
Q: PHP PDO: chars ÖÄÅ wont show Whatever im trying to do. If i insert into with öäå or making a while loop, from rows that are from the db, and contains öäå, it appears like öäå. It must has something to do with the PDO, because it worked just fine with the mysql_*. Although I had these attributes in mysql_* : # mysql_set_charset("utf8",$link); # mysql_query("SET NAMES 'UTF8'"); My connection in PDO looks like this: $connect = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset:UTF-8", DB_USER, DB_PASS, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); How can I solve this? I believe I also need the "set names" somewhere, how? A: The SET NAMES 'UTF8' statement is correct, but you have to execute it every time. You can instruct PDO to automatically run the command: $dsn = sprintf( 'mysql:dbname=%s;host=%s', DB_NAME, DB_HOST ); $driver_options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' ); try { $dbc = new pdo($dsn, $user, $pw, $driver_options); } catch (PDOException $e) { // Handle exception } (via Galen Grover)
{ "pile_set_name": "StackExchange" }
Q: How to use my API's response.data and format it into a usable array in React.js I am using React and the Pokemon API (https://pokeapi.co/) to make a simple web app where the user can search pokemons by name and filter by type. I successfully implemented the searching for my own data. constructor() { super(); this.state = { contactData: [ { name: 'Abet', phone: '010-0000-0001' }, { name: 'Betty', phone: '010-0000-0002' }, { name: 'Charlie', phone: '010-0000-0003' }, { name: 'David', phone: '010-0000-0004' } ] }; } With the contactData that I have, I successfully search the data that contains the keyword. render() { const mapToComponents = (data) => { //data.sort(); data = data.filter( (contact) => { return contact.name.toLowerCase() .indexOf(this.state.keyword.toLowerCase()) > -1; } ) return data.map((contact, i) => { return (<ContactInfo contact={contact} key={i}/>); }); }; return( <div className="Home"> <input name = "keyword" placeholder = "Search" value = { this.state.keyword } onChange = { this.handleChange } /> <div className="info">{ mapToComponents(this.state.contactData)}</div> </div> ) } My question is, I am not sure how to do the same thing with my response data from the Pokemon API. My response data looks like this in the console: {count: 811, previous: null, results: Array(20), next: "https://pokeapi.co/api/v2/pokemon/?offset=20"} count : 811 next : "https://pokeapi.co/api/v2/pokemon/?offset=20" previous : null results : Array(20) 0 : {url: "https://pokeapi.co/api/v2/pokemon/1/", name: "bulbasaur"} 1 : {url: "https://pokeapi.co/api/v2/pokemon/2/", name: "ivysaur"} 2 : {url: "https://pokeapi.co/api/v2/pokemon/3/", name: "venusaur"} 3 : {url: "https://pokeapi.co/api/v2/pokemon/4/", name: "charmander"} 4 : {url: "https://pokeapi.co/api/v2/pokemon/5/", name: "charmeleon"} 5 : {url: "https://pokeapi.co/api/v2/pokemon/6/", name: "charizard"} 6 : {url: "https://pokeapi.co/api/v2/pokemon/7/", name: "squirtle"} 7 : {url: "https://pokeapi.co/api/v2/pokemon/8/", name: "wartortle"} 8 : {url: "https://pokeapi.co/api/v2/pokemon/9/", name: "blastoise"} 9 : {url: "https://pokeapi.co/api/v2/pokemon/10/", name: "caterpie"} 10 : {url: "https://pokeapi.co/api/v2/pokemon/11/", name: "metapod"} 11 : {url: "https://pokeapi.co/api/v2/pokemon/12/", name: "butterfree"} 12 : {url: "https://pokeapi.co/api/v2/pokemon/13/", name: "weedle"} 13 : {url: "https://pokeapi.co/api/v2/pokemon/14/", name: "kakuna"} 14 : {url: "https://pokeapi.co/api/v2/pokemon/15/", name: "beedrill"} 15 : {url: "https://pokeapi.co/api/v2/pokemon/16/", name: "pidgey"} 16 : {url: "https://pokeapi.co/api/v2/pokemon/17/", name: "pidgeotto"} 17 : {url: "https://pokeapi.co/api/v2/pokemon/18/", name: "pidgeot"} 18 : {url: "https://pokeapi.co/api/v2/pokemon/19/", name: "rattata"} 19 : {url: "https://pokeapi.co/api/v2/pokemon/20/", name: "raticate"} length : 20 __proto__ : Array(0) __proto__ : Object How can format this like the contactData that I've created and display it for searching? A: First you need one method to fetch data from API like this: loadData() { fetch('https://pokeapi.co/api/v2/pokemon/') .then(result => result.json()) .then(items => this.setState({ data: items }) } Then create another method componentDidMount and pass loadData(): componentDidMount() { this.loadData() } From official React documentation: componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering. More information here: React Components JSFiddle example: class Data extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { this.loadData() } // Fetch data from API: loadData() { fetch(`https://pokeapi.co/api/v2/pokemon/`) .then(result => result.json()) .then(items => this.setState({data: items})) } render() { const mapToComponents = data => { // Your logic... // Here you can use data... }; return ( <div> <h1>Pokemon's:</h1> <ul> {this.state.data.results !== undefined ? this.state.data.results.map((x, i) => <li key={i}>{x.name}</li>) : <li>Loading...</li> } </ul> <h1>THIS.STATE.DATA:</h1> <pre> {JSON.stringify(this.state.data, null, 2)} </pre> </div> ); } } ReactDOM.render( <Data />, document.getElementById('container') ); <div id="container"> <!-- This element's contents will be replaced with your component. --> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Removing badges from profile. Is it possible to remove badges if you do not want them? If not, is that something you would consider adding as a feature? A: No, this is not possible. I doubt it will be implemented. If you find it distracting you can hide them locally (others will still see them). For details see: How to disable/remove all badges and reputation? and https://stackapps.com/questions/3105/hide-all-pointless-user-data-gravatar-badges-and-reputation
{ "pile_set_name": "StackExchange" }
Q: How i can make a http get request in genexus? I'm trying to make a http get request in genexus, but in the object httpclient i can't find the property that have the answer and the method Execute() don't return the response of the request. I need to copulate the json response in one SDT. I try something like: &httpClient = new() &httpClient.BaseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + &LocalLatitudeA + ',' + &LocalLongitudeA + '&key=xxxxxxxxxxxxx' &httpClient.Execute('GET', &httpClient.BaseUrl) A: You can do this to retrieve data from an HTTP endpoint and load a SDT with the result: &HttpClient.Execute(!"GET", !"https://reqres.in/api/users?page=2") &Users.FromJson(&HttpClient.ToString()) &HttpClient.ToString() returns the response as a string, and &Users.FromJson() loads the &Users SDT with the received data.
{ "pile_set_name": "StackExchange" }
Q: Wants to understand how @Tested works with JMockit I am using JMockit since long.I would like to understand how @Tested works. Today i was trying to use it within my Test class. What i understand is Whatever class we wants to test we can mark it as @Tested. One thing which was confusing me about the behaviur of this is when i try to set something in @Before.Below is my query. My Class for which i want to write Test case public Class A{ public A(){} } Test class public class ATest { @Tested private A a; @Before public void setUp(){ a.setSomething(); } @Test public void testA(){ } } In this case i get NPE. But if i use the same block of code in my test method directly that just works fine.Can anybody help me to understand the behavior of @Tested. I am using Jmockit version 1.17 I have also checked the post on GitHub as below: https://github.com/jmockit/jmockit1/issues/168 i just wanted to confirm is it also fixing my problem? A: I was able to find what i was looking for http://jmockit.org/api1x/mockit/Tested.html#availableDuringSetup--
{ "pile_set_name": "StackExchange" }
Q: How do you select multiple specific files? Say I've got 5 files, and I'd like to select just two of them. In Windows I would select file 1, then press Control, and then click file 5. How could this be done in Mac Os X? A: You'll do the same thing by doing Command+Click. A: Use cmd + click if you are using a Mac keyboard or use the Windows-key + click if you are using a PC keyboard.
{ "pile_set_name": "StackExchange" }
Q: Iterate through numbers using seq() and rep() I need to use rep() and seq() to get the following vector: 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 Normally I would just use a for statement to achieve this but I am restricted from using that and can only use rep() and seq() to achieve this vector. A: > 1:5 + rep(0:4, each=5) [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
{ "pile_set_name": "StackExchange" }
Q: ServiceContext and OrganizationServiceProxy in Session I have an ASP.Net app that allows users to interact with Dynamics CRM 2011 data through early bound entities. I am currently storing the ServiceContext and OrganizationServiceProxy in session, the reason for this is that I have to get objects of a specific type then get their related entities when a user requires it. Finally updating them when the user hits save. I know the ServiceContext and OrganizationServiceProxy implement IDisposable and as such should be disposed. Currently I am doing this in session end in my Global.asax. I'm in the process of testing my thinking but should I in reality instantiate and dispose of both the proxy and context whenever I get my entities or when I am done with the entire process? All the MS guides show wrap the entire process in a using statement so that the objects are disposed but what if the process requires user interaction? A: Unless you are only using an OrganizationServiceProxy once per page request, I would create a common function that lazy loads an OrganizationServiceProxy only once per request, and then use the unload method to dispose of it if it was loaded(see Closing a conneciton in the "unload" method for the safety of this approach) This would make sense in most of the situations. Remember, there isn't anything special about the Using statement, besides it virtually guaranteeing that the dispose method is going to get called. It may be worth the acceptable risk of a few edge cases causing dispose not to get called for the sake of cleaner code, and not opening up 5 different connections for a single request. I think it's very dangerous for you to be storing the context and proxy in the session because people can go for a coffee or bathroom break, and you're stuck with lot's of unused open connections.
{ "pile_set_name": "StackExchange" }
Q: How to reuse the JIRA velocity templates for emails? I would like to change the notification behavior of JIRA and add additional receivers to certain issue events. I know that I could register the EventPublisher and catch all necessary events. public class MyIssueCreatedResolvedListenerImpl implements InitializingBean, DisposableBean { private final EventPublisher eventPublisher; public MyIssueCreatedResolvedListenerImpl(EventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } @Override public void afterPropertiesSet() throws Exception { eventPublisher.register(this); } @Override public void destroy() throws Exception { eventPublisher.unregister(this); } @EventListener public void onIssueEvent(IssueEvent issueEvent) { // Process the issue events. I'm using the code presented below. } } In the onIssueEvent I would like to reuse the existing email templates from JIRA and send them with the SMTPMailServer object to further receivers. At the moment I'm using following code to read and fill the velocity templates. ApplicationProperties ap = ComponentAccessor.getApplicationProperties(); String baseUrl = ap.getString(APKeys.JIRA_BASEURL); String webworkEncoding = ap.getString(APKeys.JIRA_WEBWORK_ENCODING); VelocityManager vm = ComponentAccessor.getVelocityManager(); VelocityParamFactory vp = ComponentAccessor.getVelocityParamFactory(); Map context = vp.getDefaultVelocityParams(); context.put("baseurl", baseUrl); context.put("currentTimestamp", new Date()); context.put("issue", issueEvent.getIssue()); String renderedText = vm.getEncodedBody("templates/email/html/", "issueclosed.vm", baseUrl, webworkEncoding, context); SMTPMailServer mailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); Email email = new Email("<E-Mail-Adress>"); email.setMimeType("text/html"); email.setEncoding("utf-8"); email.setBody(renderedText); try { mailServer.send(email); } catch (MailException e) { e.printStackTrace(); } The above code work partial. A couple of fields are filled, but I still miss the CSS, images or i18n in the email notification. Please note, I won't use any additional add-ons from the marketplace. Is this the correct implementation to reuse the JIRA templates? How to include the CSS, images, i18n, etc.? Or could I use a different approach? A: couple of fields are filled, but I still miss the CSS, images or i18n How Does Internationalisation Work? Before you implement internationalisation (also called 'i18n' because there are 18 letters between 'i' and 'n') support for your plugin, it is important to understand how a plugin is internationalised. First, all messages in the plugin must be moved outside the code into a properties file in the plugin. The properties file stores the default (English) translations for all messages inside the plugin. The properties file format is a key = value format, where the key is used to refer to the resource in the code and the value is the default message in English. You can't use /images/ in your path unless you map the directory. Including Javascript and CSS resources: For each resource, the location of the resource should match the path to the resource in your plugin JAR file. Resource paths are namespaced to your plugin, so they can't conflict with resources in other plugins with the same location (unlike say i18n or Velocity resources). However, you may find it convenient to use a path name which is specific to your plugin to be consistent with these other types. To include your custom web resource in a page where your plugin is used, you use the #requireResource Velocity macro.
{ "pile_set_name": "StackExchange" }
Q: Upload file using selenium web driver I have already check and search for same question and there are lot of solution but no one is working for me so posing question here. I am doing practice of selenium web driver. I am using this form for practice : http://www.toolsqa.com/automation-practice-form/ Now , I have 3 issues in that. 1 - There are first 2 links called "Partial link test" & "List test" which I am able to click on, using "findelement", but I want to open both link in NEW TAB in same browser. 2 - I am not able to upload file. My code is not working for that element. 3 - How can I select particular value from dropdown of "Continents"?? My code is given below : WebDriver driver = new FirefoxDriver(); driver.get("http://www.toolsqa.com/automation-practice-form/"); driver.manage().window().maximize(); **driver.findElement(By.linkText("Partial Link Test")).click(); driver.findElement(By.linkText("Link Test")).click();** driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.name("firstname")).sendKeys("Tester"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.name("lastname")).sendKeys("Tester"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.id("sex-0")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.id("exp-2")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.id("datepicker")).sendKeys("01/01/1985"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.id("profession-1")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); **driver.findElement(By.id("photo")).sendKeys("C:/Users/Public/Pictures/Sample Pictures/Desert.jpeg");** driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Thread.sleep(600); driver.findElement(By.id("tool-0")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); **driver.findElement(By.id("continents")).click();** driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Please help to correct my code. A: I have added the answers inline to each of your questions, below. Also, an advice, is to use Implicit wait only once at the top while creating a browser instance, as its scope is the whole class itself. So, once declared, then selenium will wait a maximum of that time, for detecting an element. It can be rather overridden by using Explicit waits for certain elements, if necessary Please see this link for better understanding Implicit and Explicit waits: 1 - There are first 2 links called "Partial link test" & "List test" which I am able to click on, using "findelement", but I want to open both link in NEW TAB in same browser. //Clicking and opening Partial Link Text in new tab WebElement element = driver.findElement(By.linkText("Partial Link Test")); Actions act = new Actions(driver); act.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform(); //Clicking and opening Link Text in new tab element = driver.findElement(By.linkText("Link Test")); act.contextClick(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform(); 2 - I am not able to upload file. My code is not working for that element. The path of the file must be like this: driver.findElement(By.id("photo")).sendKeys("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg"); 3 - How can I select particular value from dropdown of "Continents"?? You can use Select class for that like below. It will select the option "Australia". Select sel = new Select(driver.findElement(By.id("continents"))); sel.selectByVisibleText("Australia");
{ "pile_set_name": "StackExchange" }
Q: How to set background image to keep its position while browser width is changing? I am wondering how I could set the background image to keep its position on this site: http://www.jylkkari.fi/wordpress/ When you drag the browser under 960 px wide, the background of sidebar starts to move towards center. I found out this Javascript which could solve this problem. I am still searching if there is a easy way in CSS to keep the image centered while browser width is more than 960 px and on fixed while it is under this size? A: .......................... Define your body min-width:980px; body{ min-width:980px; } --------------for ie used to ie condition css as like this <!--[if lt IE 8]> <link rel="stylesheet" type="text/css" href="ie8-and-down.css" /> <![endif]--> create a css file body{width:980px;} more info about ie css click here
{ "pile_set_name": "StackExchange" }
Q: SQL Code to display data matching on 3 conditions Need to display the number of days elapsed of patients who were admitted to a skill nursing facility, discharged to their homes (with or without care) and was admitted to a hospital or Emergency Room. I was asked to display the number of days elapsed of patients who were admitted to a skill nursing facility, discharged to their homes (with or without care) and was admitted to a hospital or Emergency Room. The metric is to assess the effectiveness of skilled nursing facilities ability to keep patients from being readmitted to hospitals or seen in the emergency room after leaving a nursing facility. I have a much larger query that works great using FOLLOWING and PRECEDING that gives me previous facility and next facility admitted, but it doesn't help with the issue above. I know a need another subquery, but the one I have just isolated the latest and earliest. I need it to be rolling and looking for the first instance that meets the condition. I was asked to either give days or insert the date of last admission. select nursing.*, hospital.* from (Select--nursing stays only SUMMARY.MEMBER_ID , SUMMARY.POS , SUMMARY.ADMIT_DATE , SUMMARY.DISCHARGE_DATE , SUMMARY.Discharge_To FROM PRD.SUMMARY INNER JOIN (Select SUMMARY.MEMBER_ID, MAX(DISCHARGE_DATE) MX_DISCHARGE_DATE FROM PRD.SUMMARY WHERE SUMMARY.DISCHARGE_DATE BETWEEN '2017-01-01' AND '2018-12-31' And SUMMARY.POS = 'Nursing' group by SUMMARY.MEMBER_ID) sq ON sq.MEMBER_ID = SUMMARY.MEMBER_ID and sq.MX_DISCHARGE_DATE = SUMMARY.DISCHARGE_DATE WHERE SUMMARY.DISCHARGE_DATE BETWEEN '2017-01-01' AND '2018-12-31' And SUMMARY.POS = 'Nursing') nursing INNER JOIN ( --hospital stays only Select SUMMARY.MEMBER_ID , SUMMARY.POS , SUMMARY.ADMIT_DATE , SUMMARY.DISCHARGE_DATE , SUMMARY.Discharge_To FROM PRD.SUMMARY INNER JOIN ( select MEMBER_ID, MIN(ADMIT_DATE) MIN_ADMIT_DATE FROM PRD.SUMMARY WHERE SUMMARY.DISCHARGE_DATE BETWEEN '2017-01-01' AND '2018-12-31' And SUMMARY.POS = 'Hospital' GROUP BY SUMMARY.MEMBER_ID) sq on sq.MEMBER_ID = SUMMARY.MEMBER_ID and sq.MIN_ADMIT_DATE = SUMMARY.ADMIT_DATE WHERE SUMMARY.DISCHARGE_DATE BETWEEN '2017-01-01' AND '2018-12-31' And SUMMARY.POS = 'Hospital') hospital on nursing.MEMBER_ID = hospital.MEMBER_ID and nursing.DISCHARGE_DATE >= hospital.ADMIT_DATE DDL to create the above table CREATE TABLE [dbo].[jpsSUMMARY]( [member_id] [int] NULL, [pos] [nvarchar](10) NULL, [admit_date] [date] NULL, [discharge_date] [date] NULL, [discharge_to] [nvarchar](50) NULL ) GO CSV data corresponding to the Expected Output member_id,pos,admit_date,discharge_date,discharge_to 1001,Nursing ,2016-03-08,2016-03-14,Home Without Care 1001,Hospital ,2016-03-21,2016-03-24,Home Without Care 1001,ER ,2016-03-27,2016-03-28,Hospital 1001,Nursing ,2016-08-19,2016-09-02,Home Without Care 1001,ER ,2016-09-05,2016-09-06,Home Without Care Here is the expected output A: I was able to re-constitute that sql, and then prettyprint to look at it. Try this to see if it is any simpler. Do all the OVER's once in the CTE... You may want to remove the ISNULL(CAST(... and accept the results as 0 (zero). revised May10 noon pos -> [pos] WITH SumRN as (SELECT member_id ,[pos] ,admit_date ,discharge_date ,discharge_to ,ROW_NUMBER() Over (Partition By member_id order by discharge_date, admit_date) as rn FROM PRD.SUMMARY --jpsSUMMARY ) SELECT s1.member_id ,s1.[pos] ,s1.admit_date ,s1.discharge_date ,s1.discharge_to ,ISNULL(sp.[pos],'') as Previous ,ISNULL(sf.[pos],'') as Next ,ISNULL(cast(case when sp.[pos] = 'Nursing' and sp.discharge_to Like 'Home%' and s1.[pos] = 'Hospital' Then Datediff(d, sp.discharge_date, s1.admit_date) Else null End as varchar(10)), '') as DaysNursingHosp ,ISNULL(cast(case when sp.[pos] = 'Nursing' and sp.discharge_to Like 'Home%' and s1.[pos] = 'ER' Then Datediff(d, sp.discharge_date, s1.admit_date) Else null End as varchar(10)), '') as DaysNursingER From SumRN s1 Left Join SumRN sp on s1.RN - 1 = sp.RN Left Join SumRn sf on s1.RN + 1 = sf.RN Results-- member_id pos admit_date discharge_date discharge_to Previous Next DaysN2Hosp DaysN2ER 1001 Nursing 2016-03-08 2016-03-14 Home Without Care Hospital 1001 Hospital 2016-03-21 2016-03-24 Home Without Care Nursing ER 7 1001 ER 2016-03-27 2016-03-28 Hospital Hospital Nursing 1001 Nursing 2016-08-19 2016-09-02 Home Without Care ER ER 1001 ER 2016-09-05 2016-09-06 Home Without Care Nursing 3
{ "pile_set_name": "StackExchange" }
Q: Align buttons in bottom of div I need to do the same of the snnipet, but without height in .footer .footer { background: blue; width: 1200px; height: 250px; //I NEED TO CHANGE THIS } .footer .container { width: 100%; height: 100%; margin: 0 auto; } .footer .container .col-25 { width: 25%; float: left; box-sizing: border-box; height: 100%; padding: 0 30px; } .footer .container .col-25 .footer-col { color: #fff; height: 100%; display: inline-block; position: relative; } .footer .container .col-25 .footer-col h2 { font-size: 18px; } .footer .container .col-25 .footer-col input[type="button"] { font-size: 16px; color: #3da6cc; background: #fff; padding: 10px; width: 100%; border: none; border-radius: 3px; position: absolute; bottom: 10px; } .footer .container .col-25 .footer-col.present .text-centered-y { position: absolute; top: 50%; transform: translateY(-50%); } .footer .container .col-25 .footer-col.present .text-centered-y h1 { font-style: italic; } .footer .container .col-25 .footer-col.present .text-centered-y h1 span { color: #29738e; } .footer .container .col-25 .footer-col.present .text-centered-y h3 { font-weight: lighter; } <div class="footer"> <div class="container"> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <input type="button" value="Lorem Ipsum" /> </div> </div> </div> </div> A: Here is the code. Even you don't need to set height. Or you can change too. Or You can extend paragraph/content .footer { background: blue; width: 1200px; } .footer .container { width: 100%; height: 100%; margin: 0 auto; display: flex; } .footer .container .col-25 { width: 25%; box-sizing: border-box; padding: 0 30px; padding-bottom: 50px; } .footer .container .col-25 .footer-col { color: #fff; height: 100%; display: inline-block; position: relative; } .footer .container .col-25 .footer-col h2 { font-size: 18px; } .footer .container .col-25 .footer-col input[type="button"] { font-size: 16px; color: #3da6cc; background: #fff; padding: 10px; width: 100%; border: none; border-radius: 3px; position: absolute; top: 100%; } .footer .container .col-25 .footer-col.present .text-centered-y { position: absolute; top: 50%; transform: translateY(-50%); } .footer .container .col-25 .footer-col.present .text-centered-y h1 { font-style: italic; } .footer .container .col-25 .footer-col.present .text-centered-y h1 span { color: #29738e; } .footer .container .col-25 .footer-col.present .text-centered-y h3 { font-weight: lighter; } <div class="footer"> <div class="container"> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud...</p> <input type="button" value="Lorem Ipsum" /> </div> </div> <div class="col-25"> <div class="footer-col"> <h2>Lorem Ipsum</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <input type="button" value="Lorem Ipsum" /> </div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: y scale in scatterplot scales y axis differently than y values D3.js The scatterplot I'm making has a correct y axis going from 0 to around 5000, but the nodes that are being drawn come way short of their value. The problem (I think) is domain for y scale. I've tried using extent(), min and max, and hard coding values in. (these attempts are there and commented out). I've debugged the values getting fed into the y scale and they seem to be ok, they should be reaching the top of this chart, but they barely come half way up. The only way to get the nodes to the top of the chart is if I hardcode the max of y scale domain to be 3000, which isn't even close to the max y value which is around 4600. picture of chart <!-- STACK OVERFLOW This code at the top is simple HTML/HTTP request stuff, you can scroll down till my other comments to start looking at the problem. I left this code here so people can run the chart on their browser.--> <meta charset="utf-8"> <title>Template Loading D3</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.min.js"></script> <style media="screen"> .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } </style> </head> <body> <h1>Bitcoin BTC</h1> <script type="text/javascript"> var xhr = new XMLHttpRequest(); function makeRequest(){ xhr.open("GET", "https://api.coindesk.com/v1/bpi/historical/close.json?start=2010-07-17&end=2017-09-11", true); xhr.send(); xhr.onreadystatechange = processRequest; } function processRequest(){ console.log("testing, state: ", xhr.readyState) if(xhr.readyState == 4 && xhr.status == 200){ let response = JSON.parse(xhr.responseText); makeChart(response); } } // STACK OVERFLOW -- code above this can be ignored since it's just making HTTP request. // I'm leaving it here so people can serve this code on their own machine and // see it working in their browser. D3 code is below // When the HTTP request is finished, this function gets called to draw my chart, // this is where D3.js starts. function makeChart(response){ var w = window.innerWidth - 100; var h = window.innerHeight - 100; var padding = 20; var Lpadding = 45; // makeDatesAndValues is not part of my problem, this formats the dates // coming from HTTP request into something easier to feed into D3.js X Scale var makeDatesAndValues = function(input){ let dates = []; let values = []; let returnData = []; for(prop in input){ values.push(input[prop]) let counter = 0; let year = []; let month = []; let day = []; for( var j = 0; j < prop.length; j++){ if(lastDate[j] !== "-" && counter == 0){ year.push(prop[j]); } else if(prop[j] == "-"){ counter++; } else if(prop[j] !== "-" && counter == 1){ month.push(prop[j]) } else if(prop[j] !== "-" && counter == 2){ day.push(prop[j]) } } dates.push([Number(year.join("")), Number(month.join("")), Number(day.join(""))]); returnData.push( { date: [Number(year.join("")), Number(month.join("")), Number(day.join(""))], value: input[prop] } ) } return returnData; } var inputData = makeDatesAndValues(response.bpi); // HERE WE GO, this is where I think the problem is, drawing the actual chart. var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); // Here is the problem child, both "y" and the commented out "yScale" are attempts to // get the correct y-coordinates for values fed into the scale // Both of these will make a correct y Axis, but then screw up the y-coordinates of my data // getting fed in, as described on SO var y = d3.scale.linear() .domain([d3.min(inputData, function(d){ return d.value; }), d3.max(inputData, function(d){ return d.value; })]) // .domain([d3.extent(d3.values(inputData, function(d){ return d.value}))]) // .domain([0, 3000]) .range([h - padding, padding]) // var yScale = d3.scale.linear() // // .domain([0, 5000]) // .domain([d3.min(inputData, function(d){ return d.value; }), d3.max(inputData, function(d){ return d.value; })]) // // .domain([d3.extent(d3.values(inputData, function(d){ return d.value}))]) // .range([0, h]) // X scale works fine, no problems here var x = d3.time.scale() .domain([new Date(2010, 7, 18), new Date(2017, 7, 18)]) .range([Lpadding, w]); // Both Axes seem to be working fine var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(8) var yAxis = d3.svg.axis() .scale(y) .orient("left") // .tickSize(-w, 0, 0) .ticks(8) svg.selectAll("circle") .data(inputData) .enter() .append("circle") .attr("cx", function(d){ let thisDate = x(new Date(d.date[0], d.date[1], d.date[2])) return thisDate; }) // And here is the other side of the problem. There are different attempts // to plot they y-coordinate of my values commented out. // None of these are working and I don't understand why it works correctly // for the Y Axis, but my plotted values come way short of where they should be. .attr("cy", function(d, i){ console.log("this is with yScale: ", y(d.value)) console.log("Without: ", d.value) // return y(( d.value) - padding) // return y(d.value); // return y(d.value) - (h - padding) return h - padding - y(d.value); }) .attr("r", function(d){ return 1; }) .attr("fill", "red") svg.append("g") .attr("class", "x axis") .attr("transform", "translate(" + 0 + ", " + (h - padding) + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + Lpadding + ", 0)") .call(yAxis); } makeRequest(); </script> </body> A: I suggest you may need to consider people's feeling when you post such long codes with poor comments. Your problem is you are not awareness the coordinate system of SVG where the y points to bottom. The following is a little modification: svg.selectAll("circle") .data(inputData) .enter() .append("circle") .attr("cx", function(d){ let thisDate = x(new Date(d.date[0], d.date[1], d.date[2])); return thisDate; }) // this is the KEY part you should change: .attr("cy", function(d, i){ return h - padding - y(d.value); }) .attr("r", 1) .attr("fill", "red"); Since you don't offer detail data, I can't check it. hope it will help!
{ "pile_set_name": "StackExchange" }
Q: Sequences with PL SQL I know how to create a sequence in pl sql. However, how would I set the values to all have say 3 digits? is there another sql statement to do this when I create a sequence? so an example would be: 000 001 012 003 Thanks guys! A: First, just to be clear, you do not create sequences in PL/SQL. You can only create sequences in SQL. Second, if you want a column to store exactly three digits, you would need the data type to be VARCHAR2 (or some other string type) rather than the more common NUMBER since a NUMBER by definition does not store leading zeroes. You can, of course, do that, but it would be unusual. That said, you can use the "fm009" format mask to generate a string with exactly 3 characters from a numeric sequence (the "fm" bit is required to ensure that you don't get additional spaces-- you could TRIM the result of the TO_CHAR call as well and dispense with the "fm" bit of the mask). SQL> create table t( col1 varchar2(3) ); Table created. SQL> create sequence t_seq; Sequence created. SQL> ed Wrote file afiedt.buf 1 insert into t 2 select to_char( t_seq.nextval, 'fm009' ) 3 from dual 4* connect by level <= 10 SQL> / 10 rows created. SQL> select * from t; COL --- 004 005 006 007 008 009 010 011 012 013 10 rows selected. A: haven't used plsql in a while, but here goes: given an integer sequence myseq, to_char(myseq.nextval, '009')
{ "pile_set_name": "StackExchange" }
Q: Get Previous item in a list I've a previous/next setup in the works, and the next functionality is working fine (although, that was created by someone else a while back). As for the previous button, that is giving me a few problems. Here is the code so far: private Item getPrevious() { Item CurrentItem = Sitecore.Context.Item; var blogHomeID = "{751B0E3D-26C2-489A-8B8C-8D40E086A970}"; Item BlogItem =db.Items.GetItem(blogHomeID); Item[] EntryList= BlogItem.Axes.SelectItems("descendant::*[@@templatename='BlogEntry']"); Item prevEntry = null; for (int i = 0; i < EntryList.Length; i++) { if (EntryList[i] == CurrentItem) { return prevEntry; } prevEntry = EntryList[i]; } } I get that you need to subtract 1 from the current item in the list to get the previous, but so far, all this seems to do is display the exact same entry for the previous button. It's always the latest entry in the list, not the previous one. I feel like this shouldn't be so difficult but it could be the old code I'm trying to work with. Not sure. A: You can use the GetPreviousSibling() and GetNextSibling() methods: Sitecore.Context.Item.Axes.GetPreviousSibling() Sitecore.Context.Item.Axes.GetNextSibling() These will return the previous and next sibling, or null if the current item is the first/last respectively. If you want to restrict by template type then you can use the preceding and following xpath queries: Item previous = Sitecore.Context.Item.Axes.SelectItems("./preceding::*[@@templateid='{template-guid}']").LastOrDefault(); Item next = Sitecore.Context.Item.Axes.SelectSingleItem("./following::*[@@templateid='{template-guid}']"); Note the use of SelectItems and LastOrDefault() on the first query. Both queries give you a list of Items sorted by order.
{ "pile_set_name": "StackExchange" }
Q: Let's kill all the [character]s Does this site really need a character tag? Nearly every question is about some character in one way or another. And character wouldn't work as the sole tag on a question, which makes it a meta tag and therefore undesirable, according to SE central policy. The purpose of tags is supposed to be for experts in a given subject to find questions to answer on that subject, but there are obviously no experts on characters in general. I propose the burnination of the character tag. Who's with me? A: I think that this tag is useless. No one is going to look for all of the questions about all characters in all movies or TV shows. Most questions with this tag are about a specific character in a specific film... Which means that the film tag should be more than sufficient. There's no need to further point out "hey, this question is just about one character"... and the spotty usage of it shows that it's not helpful. Here are a few questions that are about "characters", have fewer than five tags and yet, don't have the character tag. Is there any hint as to why Jerry needs the money? Why was Ian's onset of Bipolar Disorder so fast? Why did Major Hellstrom get suspicious? Why did Apocalypse say this? Why didn't Pietro Maximoff tell Magneto they were related? Why was this specific character in Age Of Ultron killed off? And that's just from the front page and it's just the ones I absolutely know "should" have it. If we're going to use it to classify questions but most of the questions that "deserve" it don't have it... then the tag is useless. Get rid of it. A: I don't think that this tag, character, is useless. "Nearly every question is about some character". It's good word choice: "near" ...it`s not the same than all. I've made questions about characters myself and I like them: one question with over 5 votes on Hodor, from Game of Thrones, and others less popular questions on Gilfoyle, from Silicon Valley, and even on God, in Supernatural. Maybe vote popularity has to do with show/movie popularity, so that might not be such a huge issue. Just my opinion. On the other hand they're tons of tags not related to characters, just some to mention: film-techniques, production, animation, soundtrack, title, effects, props, among the most used tags on site. The second point: that "character wouldn't work as the sole tag on a question" seems sound. However, keeping the tag even as a secondary one can help to do cross searches on a topic, such as different aspects of a movie. For example it's not the same between these two sets of tags: fight-club, props, ending, production fight-club, character, dialogue, analysis, plot-explanation
{ "pile_set_name": "StackExchange" }
Q: how to get gradle embeded common value in build.gradle I am define a public dependencies in common.build like this(Gradle 6.0.1): ext { java = [ compileSdkVersion: 1.8, minSdkVersion : 1.8, targetSdkVersion : 1.8, versionCode : 1.8, ] version = [ mybatisGeneratorCoreVersion : '1.3.7', itfswMybatisGeneratorPluginVersion: '1.3.8' ] dependencies = [ mybatisGeneratorCore : "org.mybatis.generator:mybatis-generator-core:${version["mybatisGeneratorCoreVersion"]}", ] } and using in root project build.gradle like this: subprojects { apply from: "${rootProject.projectDir}/common.gradle" dependencies { implementation rootProject.ext.dependencies.mybatisGeneratorCore } } and build the project like this: ./gradlew clean :soa-illidan-mini:soa-illidan-mini-service:build -x test and give me this error: ~/Library/Mobile Documents/com~apple~CloudDocs/Document/source/dabai/microservice/soa-illidan-mini on  master! ⌚ 10:59:03 $ ./gradlew clean :soa-illidan-mini:soa-illidan-mini-service:build -x test FAILURE: Build failed with an exception. * Where: Build file '/Users/dolphin/Library/Mobile Documents/com~apple~CloudDocs/Document/source/dabai/microservice/build.gradle' line: 99 * What went wrong: A problem occurred evaluating root project 'microservice'. > Cannot get property 'dependencies' on extra properties extension as it does not exist * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 12s I am followed by internet tutorals ,what should I do to fix this problem? A: move your apply command to root of build.gradle like this: apply from: "${rootProject.projectDir}/common.gradle" just put it to top level of your project config. It works!
{ "pile_set_name": "StackExchange" }
Q: "Can't find API database; API check was not performed" in Android App SDK with Eclipse I'm starting a new Android App using the Android SDK on Eclipse, build tools 19.0.2, on a Windows 7 PC. At some point during my work, I started receiving the error "Can't find API database; API check was not performed". This error is not shown in the code but instead shows a red X in the project folder and a line one error in the Problems window. There is a previous question on this topic but that did not work for me. I have already tried adjusting the target and minimum SDK versions in the manifest and re-installed the SDK multiple times. This problem also occurs with the only other project in my work space and shows the same error. Thanks in advance for any help. A: For me, Eclipse --> Project --> Clean... is enough set everything right again: A: Following works for me: Make sure you installed SDKs listed in your manifest.xml, i.e. mini version and target version. Click the icon with red x on the right hand side tool bar, which has tip of 'Problems(...)' if you move your cursor over it. Right click on your error, choose quick fix. Choose Disable Check in This Project
{ "pile_set_name": "StackExchange" }
Q: When to instantiate a struct explicitly? i'm coming from Java, and there you always do something like: Http http = new Http(...); http.ListenAndServe(); So all information are stored in the local variable "http". It's different in go. There most of the information is stored directly "in another package". You do: import "net/http" ... http.ListenAndServe(...) So you dont have to explicitly (well you could) instantiate a server struct. Just call a function from the package and all the structs will be created from there. (So compared to Java, it acts like static functions with static member variables to store all information ?) So this is how you do it (everytime) in go ? Coming from Java, this is a little bit hard to understand. Especially when to use this method, when to use a factory pattern (like: NewHttpServer(...) ) and when to explicitly create a struct from another package ( like: var http http.Server = http.Server{...} ) Everything might be possible, but what is the idiomatic golang code ? Is there any good document/tutorial which explains it ? A: I'd really suggest reading the Godoc for net/http. The package is very feature-rich and lets you do what you want. The behaviour of http.ListenAndServe is to implicitly use a serve multiplexer known as DefaultServeMux, on which you can register handlers with http.Handle. So you can't deal with the server or multiplexer explicitly like this. It sounds like what you want (a more Java-like solution) is to instantiate a server s := &http.Server{ Addr: ":8080", Handler: myHandler, // takes a path and a http.HandlerFunc ReadTimeout: 10 * time.Second, // optional config WriteTimeout: 10 * time.Second, // ... MaxHeaderBytes: 1 << 20, } and call ListenAndServe on that: log.Fatal(s.ListenAndServe()) Both ways are totally idiomatic, I've seen them used quite frequently. But seriously, don't take my word for it. Go look at the docs, they have lots of examples :)
{ "pile_set_name": "StackExchange" }
Q: Rails 5.1: refresh partial within partial with AJAX I have partial _navigation.html.erb where there is this piece of code: <div class="dropdown profile-element"> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> <span class="clear"> <span class="block m-t-xs"> <div id="userprofile"> <%= render 'users/user', user: current_user %> <b class="caret"></b> </div> </span> </span> </a> <ul class="dropdown-menu animated fadeInRight m-t-xs"> <li><%= link_to t('.profile'), edit_user_path(current_user), remote: true %></li> <li class="divider"></li> <li><%= link_to t('.logout'), logout_path %></li> </ul> </div> I render User name in this _user.html.erb partial: <strong class="font-bold"><%= user.name %></strong> When I login, I see my current_user name in navigation partial as expected. However when I try to Update my User name (modal window), I don't see my current_user value changes in _user.html.erb partial. My users_controller.rb Update action looks like this: def update @user.update(user_params) respond_to do |format| format.json { update_flash } format.js { update_flash } end end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation, :locale, :menu_role, :psw_change, {company_ids: []}, {user_group_ids: []}) end def correct_user users = User.where(id: helpers.users_all) @user = User.find(params[:id]) redirect_to(errors_path) unless users.include?(@user) end def update_flash flash[:notice] = "#{@user.name.unicode_normalize(:nfkd) .encode('ASCII', replace: '')} ", t(:updated) end update.js.erb looks like this: $('#dialog').modal('toggle'); $('#userprofile %>').replaceWith('<%= j render (@user) %>') I see clearly in my console Update action is done, my files are rendered, no errors: Rendering users/update.js.erb Rendered users/_user.html.erb (0.6ms) Rendered users/update.js.erb (8.5ms) Completed 200 OK in 126ms (Views: 41.1ms | ActiveRecord: 16.0ms) What am I doing wrong here, please? It would be nice to be able to show updated current_user name in profile. I'll be happy for any hint, where should I be looking at. Thank you. A: In update.js.erb, you have a typo. You should delete the %>. Try this: $('#userprofile').replaceWith('<%= j render (@user) %>') Also, instead of replacing the entire #userprofile node, you may want to change the html inside of it instead: $('#userprofile').html('<%= j render (@user) %>')
{ "pile_set_name": "StackExchange" }
Q: group a list of triples into map with pair key I have a list of triples List<Triple<String, String, String>> triplets; I want to group into a map like this Map<Pair<String, String>, String> mapping; Where value of the map is the third element of the triple. And in case of the same key it should override the remaining third value. For example def triples = [ {a, b, c} ; {a, d, e} ; {a, b, f } ] // grouping def map = [ {a,b} : c ; {a, d} : e ] How to do that using Java 8 and its grouping in streams? A: This should do the trick: Map<Pair<String, String>, String> result = triplets.stream() .collect( Collectors.toMap( t -> new Pair(t.getOne(), t.getTwo()), Triple::getThree, (v1, v2) -> v2 ) ); Example of a partial pair class: public class Pair<T, U> { //... @Override public int hashCode() { return one.hashCode() + two.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; Pair p = (Pair) obj; return p.one.equals(one) && p.two.equals(two); } } The HashMap class uses equals method to identify key objects uniquely. So you first need to override equals and hashcode methods to show the logical equality of the Pair objects for the Map class. Then come back to the streams and lambda. For each triplet use Collectors.toMap with the Pair object as the key and the other remaining value of the Triplet as the value. Then provide a mergeFunction to handle key conflicts. In your case, you need to keep the previous value while discarding new value. That's all you need to do. Update I have updated the merge function as per the below comments.
{ "pile_set_name": "StackExchange" }
Q: Getting a French passport - born abroad to a French mother I was wondering if any of you have any experience with this: I am looking at getting a French passport. My mother is French and I was born in the UK. My birth was registered at the French Consulate in Liverpool. I understand that I am entitled to one. However, I am not sure which or what documents I must show them, and it isn't very clear online. Would I need to show them my birth certificate (which includes the names of my parents) and must it be legally translated into French? And would I also need to show a scanned copy of my mother's birth certificate, or must I provide them with the actual one? Moreover, do I have to show them a copy of my parent's marriage certificate? Many thanks in advance for any help or advice. A: Would I need to show them my birth certificate? There is a page that discusses whether you need a birth certificate to apply for a passport. It says that one condition that relieves you of this requirement is: vous êtes né(e) à l’étranger et votre acte de naissance étranger a été transcrit dans les registres de l’état civil consulaire français. Translation: you were born abroad and your foreign birth certificate was transcribed in the French consular civil register. I presume that this second clause is what happened when your "birth was registered at the French Consulate in Liverpool." If so, you don't need to show your birth certificate to apply for a passport. I suppose that you might in this case require a document recording or attesting to the transcription of your birth certificate, but I couldn't find anything saying that explicitly, so maybe you do not. And would I also need to show a scanned copy of my Mother's birth certificate, or must I provide them with the actual one? It's not generally necessary to show your parents' birth certificates with a passport application, but if you are under 18 you'll need to show your mother's passport or identity card and livret de famille, the requirements for a first-time passport application for a minor being somewhat different from those for an adult. I assume here that the registration of your birth with the French consulate serves as your proof of French nationality. If it does not for some reason, you will need to have your French nationality certified as a separate step before you can apply for a passport. Doing that will of course require proving your mother's nationality, in which case her birth certificate may be of use.
{ "pile_set_name": "StackExchange" }
Q: Chart legend with row style cuts off I have a Chart in ASP.NET and C#. Whenever I have the chart legend style as row, it cuts off extra labels and displays three dots "..." Is there anyway to fix this or make the legend width larger without changing the chart width? Here is my code for the chart: <asp:chart id="crtMain" runat="server" Height="700" Width="700"> <titles> <asp:Title ShadowOffset="3" Name="Default" /> </titles> <legends> <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default" LegendStyle="Row" /> </legends> <series> <asp:Series Name="Default" /> </series> <chartareas> <asp:ChartArea Name="crtArea" BorderWidth="0" /> </chartareas> </asp:chart> And the code behind: crtMain.Series["Default"].ChartType = SeriesChartType.Pie; crtMain.Series["Default"].IsValueShownAsLabel = true; crtMain.ChartAreas["crtArea"].AxisY.LabelStyle.Format = "c"; crtMain.Series["Default"].LabelFormat = "c"; crtMain.ChartAreas["crtArea"].AxisX.LabelStyle.Font = new System.Drawing.Font("Arial", 15F, System.Drawing.FontStyle.Bold); crtMain.ChartAreas["crtArea"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 15F, System.Drawing.FontStyle.Bold); crtMain.Series["Default"].Font = new System.Drawing.Font("Trebuchet MS", 15F, System.Drawing.FontStyle.Bold); crtMain.Legends["Default"].Font = new System.Drawing.Font("Trebuchet MS", 14F, System.Drawing.FontStyle.Bold); crtMain.Legends[0].Enabled = true; And picture of the issue: Which is coming from the chart here: Any ideas at all? Thanks in advance! A: UPDATE: So I figured out how to do this. I simply put in the code behind: crtMain.Legends["Default"].IsTextAutoFit = true; crtMain.Legends["Default"].MaximumAutoSize = 100; This expanded all the text so I could see every label. Hopefully this will help someone in the future.
{ "pile_set_name": "StackExchange" }
Q: Ext Form with fileuploadfield (response after submit) Can`t really understand where is a mistake.. I have a form with fileuploadfield. Request is sended good, action on my controller gets all params, works with them, and sends response to browser. But in html page, after submiting the form, always fires FAILURE event, and never SUCCESS. Client Side Code Ext.create('Ext.form.Panel', { renderTo: 'Container', bodyPadding: '10 10 0', items: [ { xtype: 'form', width: 300, border: false, fileUpload: true, items: [ { xtype: 'combobox', id: 'PayTypes', width: 215, store: PayTypesStore, valueField: 'id', displayField: 'Name', editable: false, name: 'id' } , { xtype: 'filefield', id: 'form-file', name: 'file', buttonText: '', buttonConfig: { iconCls: 'upload-icon' } } ], buttons: [ { text: 'Send', handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ url: 'UploadFile', waitMsg: 'Uploading your photo...', success: function (fp, o) { console.log("success"); msg('Success', 'Processed file on the server'); }, failure: function (form, action) { console.log(action); Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response'); } }); } } } ] } ] }); Server Side Code: public JsonResult UploadFile(HttpPostedFileWrapper file, int id) { var response = Json(new { success = true }); response.ContentType = "text/html"; return Json(response); } Response, recieved on the client side: {"ContentEncoding":null,"ContentType":"text/html","Data":"success":true},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null} What i need to fix in my code to get SUCCESS event after sumniting form? A: You called Json method twice. The only thing you need is public JsonResult UploadFile(HttpPostedFileWrapper file, int id) { return Json(new { success = true }); }
{ "pile_set_name": "StackExchange" }
Q: Mensa Norway Question Help Please Anyone can please help with this question? Currently stuck here. Source: Mensa Norway A: Add the first two columns in a row to get the third column, or the first two rows in a column to get the third row. Nothing + Square = Square Nothing + Dot = Dot Two dots added together make a square. Two squares added together make a dot. Square + Dot cancel each other Answer:
{ "pile_set_name": "StackExchange" }
Q: Mule ESB and basic authentication I wrote a flow accepting JSON, now I want to add http authentication. I want to accept HTTP basic authentication uid and pw. So I am starting with a Hellow World program first, as follows: <?xml version="1.0" encoding="UTF-8"?> <mule version="EE-3.5.0" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd"> <flow doc:name="HelloWorldFlow1" name="HelloWorldFlow1"> <http:inbound-endpoint doc:description="This endpoint receives an HTTP message." doc:name="HTTP" exchange-pattern="request-response" host="localhost" port="8081"/> <set-payload doc:description="This processor sets the payload of the message to the string 'Hello World'." doc:name="Set Payload" value="Hello World"/> </flow> </mule> And I test with the following program: C:\curl>curl -H "Content-Type: application/json" -u uida:pw -d {"first":"Steven" } http://localhost:8081 Hello World C:\curl> This works, as there is no basic auth configured within th eflow, so it ignores the "-u uid:pw" I sent on the curl command Now I change the flow as follows ( I put 'uid' in the 'Http Settings->User' field, and 'pw' in the 'Http Seetings->Password' field on the GUI <?xml version="1.0" encoding="UTF-8"?> <mule version="EE-3.5.0" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd"> <flow doc:name="HelloWorldFlow1" name="HelloWorldFlow1"> <http:inbound-endpoint doc:description="This endpoint receives an HTTP message." doc:name="HTTP" exchange-pattern="request-response" host="localhost" port="8081" password="pw" user="uid"/> <set-payload doc:description="This processor sets the payload of the message to the string 'Hello World'." doc:name="Set Payload" value="Hello World"/> </flow> </mule> Now when I test I get the following: C:\curl>curl -H "Content-Type: application/json" -u uida:pw -d {"first":"Steven" } http://localhost:8081 Cannot bind to address "http://127.0.0.1:8081/" No component registered on that endpoint I have done this repeatedly, but I get the same response. Is there another field that I should have set? Any ideas on how I can resolve this? Thanks A: The user and password attributes are ineffective on inbound HTTP endpoints, they only work on outbound. Mule uses Spring Security for authentication. This is detailed in the user guide: http://www.mulesoft.org/documentation/display/current/Configuring+the+Spring+Security+Manager , including an example of the http-security-filter that you need to put in the HTTP inbound endpoint.
{ "pile_set_name": "StackExchange" }
Q: How to get system (Windows) memory in R? Does anyone know how to get the memory (RAM) used by the system from R? I'm using windows. memory.size() and mem_used() functions give you the memory used by R and R objects respectively, but they doesn't consider the memory already occupied by the system and other software. A: This is one way using shell on Windows: shell('systeminfo | findstr Memory') #Total Physical Memory: 16,271 MB #Available Physical Memory: 8,011 MB #Virtual Memory: Max Size: 32,655 MB #Virtual Memory: Available: 24,040 MB #Virtual Memory: In Use: 8,615 MB You could use a different string instead of Memory if you want more granular results.
{ "pile_set_name": "StackExchange" }
Q: android gridview not showing top row I am using a gridview inside a relativelayout and im trying to make the whole grid show up on the screen. The top row is not completely showing..I am only getting the top right button to show. The grid is 4 columns and 6 rows. All of the rows show up besides the one at the top of the screen. My code is as follows: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="#000000" android:layout_height="match_parent" > <GridView android:id="@+id/grid" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:columnWidth="20dp" android:horizontalSpacing="1dp" android:numColumns="4" android:verticalSpacing="1dp" > </GridView> and my main.java is: public class MainActivity extends Activity implements OnClickListener { private long startTime = 0L; private Handler customHandler = new Handler(); private int game_running = 0; private int button_clicks = 0; private int previous_button_id = 0; private int current_button_id = 0; private CharSequence button_value = null; private CharSequence prevbutton_value = null; private int j = 0; private int isgameover = 0; boolean flag = false; boolean reset = false; long gametime = 0; long resettime = 0; long timeInMilliseconds = 0L; long timeSwapBuff = 0L; long updatedTime = 0L; boolean resetbool = false; private ArrayList<Button> mButtons = new ArrayList<Button>(); private ArrayList<Button> comp_buttons = new ArrayList<Button>(); private int[] numbers = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, }; Animation fadeout; protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean("Reset", true);; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); shuffle(numbers); fadeout = AnimationUtils.loadAnimation(this,R.anim.fadeout); Button cb = null; for (int i=0; i<24; i++) { cb = new Button(this); cb.setId(i); cb.setOnClickListener(this); cb.setText(Integer.toString(numbers[j])); cb.setTextSize(0); cb.setBackgroundResource(R.drawable.button); cb.setHeight(100); j++; registerForContextMenu(cb); mButtons.add(cb); if(j >= 18) { j = 0; } } GridView gridView = (GridView) findViewById(R.id.grid); gridView.setAdapter(new CustomAdapter(mButtons)); } static void shuffle(int[] ar) { Random rnd = new Random(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } @Override public void onClick(View v) { // TODO Auto-generated method stub } } and my adapter class: public class CustomAdapter extends BaseAdapter { private ArrayList<Button> mButtons = null; public CustomAdapter(ArrayList<Button> b) { mButtons = b; } @Override public int getCount() { return mButtons.size(); } @Override public Object getItem(int position) { return (Object) mButtons.get(position); } @Override public long getItemId(int position) { //in our case position and id are synonymous return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Button button; if (convertView == null) { button = mButtons.get(position); } else { button = (Button) convertView; } if( (position == 0) || (position == 1) || (position == 2) ) { button.setVisibility(convertView.GONE); } return button; } } The idea here is to have the grid eventually scroll vertically (add more buttons with for loop) and I want it to scroll when some of the buttons in the grid disappear. I wanted to be able to draw the grid with buttons correctly first before moving on. Thanks for the help. A: You will need a custom GridView or use smoothScrollToPosition to show the top row. As you add elements to the GridView, it will scroll. If your buttons are too large for the available space, it will scroll down. Likewise, if you specify the height of the GridView it will truncate the buttons. So, you need to measure the available space on the screen, then set your button heights accordingly. Or you can scroll to the top after building it and allow it to scroll vertically, which sounds like what you want anyway. Fundamentally, a GridView scrolls, so loading it with more elements than can fit on the screen initially should result in what you are seeing. Reset the anchor position or resize your elements are your only options.
{ "pile_set_name": "StackExchange" }
Q: Can horses act as witnesses? I recently murdered a guard outside Riften because he mentioned my furry ears. As a Khajit assassin, I only have a certain amount of tolerance to racist riff raff. I slit his throat, drank his mead, then proceded to do the T-bag. I was especially careful to make sure no one saw me, but alas, a bounty appeared on my head. I looked around and saw nothing but a horse standing there, all innocent like. I proceded to make dog food out of it, but at this point it was too late and the bounty remained. Now this begs the question, did the horse act as a witness and somehow manage to alert Riften about my acts of justice, or did someone else see me? A: This has happened to me on more than a couple of occasions. For this answer I decided to test this. I rode up to Riften, hopped off my horse, crouched down saved and shot a guard. And I got a bounty. So I loaded, shot my horse and then shot the guard and did not get a bounty.
{ "pile_set_name": "StackExchange" }
Q: symfony translation resources with custom domain doesn't load I have a little problem. When I add a custom domain to my resource for translation, it doesn't load. My code working (no custom domain) : $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new Symfony\Component\Translation\Loader\YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.en_GB.yml', 'en_GB'); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.fr_FR.yml', 'fr_FR'); return $translator; })); My code I want to do and not working : $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new Symfony\Component\Translation\Loader\YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.en_GB.yml', 'en_GB', 'back-office'); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.fr_FR.yml', 'fr_FR', 'back-office'); return $translator; })); the default domain is "messages", how can I change it ? regards EDIT : I just noticed that it doesn't load the other resource files. If I add empty file resource first then my translation resource file, translation doesn't appear on my twig files, it print the variable. $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/messages.en_GB.yml', 'en_GB'); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/messages.fr_FR.yml', 'fr_FR'); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.en_GB.yml', 'en_GB', 'back-office'); $translator->addResource('yaml', __DIR__ . '/../views/backend/translator/translations/back-office.fr_FR.yml', 'fr_FR', 'back-office'); EDIT 2 : I get it, I should specify the domain on each variable in the twig file or specify the default domain on each twig files : {{ 'label.name'|trans({}, 'app') }} or {% trans_default_domain "app" %} It's really not easy to manage when you have lot of files... A: I get it, I should specify the domain on each variable in the twig file or specify the default domain on each twig files : {{ 'label.name'|trans({}, 'app') }} or {% trans_default_domain "app" %} It's really not easy to manage when you have lot of files...
{ "pile_set_name": "StackExchange" }
Q: What does it mean for a set to be "nested"? What does it mean for a set to be "nested"? and can you please show an example of that is and one that isn't A: Since you have tagged you question real analysis, you are probably interested in nested sequences of sets, which appear, for example, in Cantor intersection theorem. We call a sequence $(A_n)_{n=1}^\infty$ of sets a nested sequence of sets if the next set is always a subset of its predecessor, i.e., $$(\forall n\in\{1,2,\dots\}) A_{n+1} \subseteq A_n.$$ So the nested sequence looks like this $A_1 \supseteq A_2 \supseteq \dots \supseteq A_n \supseteq \dots$ See also Wikipedia article about nested intervals. So examples of nested sequences of subsets of $\mathbb R$ would be: $A_n=(-\frac1n,\frac1n)$ $A_n=[n,\infty)$ $A_n=[0,1+\frac1n)$ If we put, for example, $A_n=\{n\}$, then these sets are not nested. According to Wikipedia, there exists a notion of nested set used in set theory. I was unaware about this notion and I don't know anything about it - so except for the link to Wikipedia article I can't give you more information. But this is probably not what you were after.
{ "pile_set_name": "StackExchange" }
Q: Get concat to work with an array-like object There are places I change an array to an array like object like so: let arr = ['a','b'] let arrLike = {...arr, length: arr.length} console.log(arrLike) > {0: "a", 1: "b", length: 2} It's not perfect, but this allows me to override arrays by using a merge. ie: > let a1 = [1,2,3], b1 = [1,2,3] > Object.assign(a1, arr) [ 'a', 'b', 3 ] > Object.assign(b1, arrLike) [ 'a', 'b'] which is desirable but I would also like concat to work, ['z'].concat(arr) > ["z", "a", "b"] // good ['z'].concat(arrLike) > ["z", {0: "a", 1: "b" length: 2}] // bad Is there anyway to modify arrLike such that concat would work? A: You need to define Symbol.isConcatSpreadable to tell concat() to treat it as array-like: arrLike[Symbol.isConcatSpreadable] = true; Example: let arr = ['a','b']; let arrLike = { ...arr, length: arr.length, [Symbol.isConcatSpreadable]: true }; console.log(['z'].concat(arrLike))
{ "pile_set_name": "StackExchange" }
Q: How to remove folded battery from phone without starting a fire? I was trying to replace the battery in my phone, but since it was very well glued to the phone, I accidentally folded it in half. This immediately caused some dark brown smoke to come out from it, so I took it outside. A few hours later, it seems to have stopped making smoke, and the bottom folded part looks very swollen. I'd like to take it out, but I'm scared it will do something like in this video. Is there anything I can do to avoid it from catching fire? Also, are the fumes it releases dangerous? A: a bloated Li-ion/Li-Po battery is very dangerous and should be handled with lot of care.Usually people would discard if the battery is in a dangerous position to be handled. I'm going to assume that your phone is expensive and you wouldn't want to discard it. Since, you have mentioned that after keeping it out for a while it has stopped making smoke you could do the following: 1.Wear full sleeve cloths, thick fire safety gloves(most important) and some kind of face protection. 2.Always use some kind of prying tool/spudger that is used in mobile repair to remove batteries. Something like in video could occur if the battery has some charge left in it. Overall, its a real risk trying to repair the phone. Proceed with caution before you attempt to. Also keep it in a safe place where it wouldn't cause fire. http://ehs.whoi.edu/ehs/occsafety/LithiumBatterySafetyGuideSG10.pdf
{ "pile_set_name": "StackExchange" }
Q: Self-written Mutex for 2+ Threads I have written the following code, and so far in all my tests it seems as if I have written a working Mutex for my 4 Threads, but I would like to get someone else's opinion on the validity of my solution. typedef struct Mutex{ int turn; int * waiting; int num_processes; } Mutex; void enterLock(Mutex * lock, int id){ int i; for(i = 0; i < lock->num_processes; i++){ lock->waiting[id] = 1; if (i != id && lock->waiting[i]) i = -1; lock->waiting[id] = 0; } printf("ID %d Entered\n",id); } void leaveLock(Mutex * lock, int id){ printf("ID %d Left\n",id); lock->waiting[id] = 0; } A: Broken If you call enterLock() with id 0 followed by enterLock() with id 1 (on another thread perhaps), both calls will succeed. Since your function doesn't change the state of the mutex, it isn't surprising. Perhaps you meant to leave lock->waiting[id] at 1 instead of 0? Note, even if you did that, it wouldn't be enough to fix the mutex. Also, what is the turn variable used for? Spinlock, not mutex Technically, what you are doing is a spinlock. A real mutex should efficiently wait for its turn instead of spinning in a loop. A: Broken for more reasons Without even looking at the details, I can tell that the mutex is not safe. The compiler is allowed to re-order your instructions which means that your writes and reads may not occur in the order you have written them. The compiler may actually even omit them totally... Not to mention there is no guarantee on memory ordering semantics at all. Writing threading primitives correctly is VERY difficult, I do not recommend that you try to write your own unless you are very knowledgeable about the pitfalls. (And if you are, then you know you don't want to do this unless absolutely necesscary).
{ "pile_set_name": "StackExchange" }
Q: A simple problem on ratio. If a solution A which has milk to water in the ratio $7:4$ is mixed with solution B which has the ratio of water to milk as $9:2$ such that the ratio becomes $1:1$,then in what ratio were they mixed? My work: in solution A: milk=$7x$,water=$4x$ in solution B: milk=$9x$,water= $2x$ Now I can't think how to use third part(mixing of both solution.) A: Don't use $x$ for both solution $A$ and solution $B$ - use a different variable, because they refer to different things. If we take $x$ units of solution $A$, we get $(7/11)x$ units of milk and $(4/11)x$ units of water. If we take $y$ units of solution $B$, we get $(9/11)y$ units of milk and $(2/11)y$ units of water. Suppose that mixing $x$ units of $A$ and $y$ units of $B$ results in a combination of milk and water that is in a ratio of $1:1$. Use this information to relate $x$ and $y$.
{ "pile_set_name": "StackExchange" }
Q: remove whitespace between php variable and html characters I have in php: $currencysymbol = "£" And later I want to use it in html to show: £1 = xxxxx But how do I get rid of the whitespace between the symbol and the 1? $currencysymbol 1 = xxxxx //whitespace £ 1 $currencysymbol1 = xxxxx // unknown variable A: Try with <?php echo $currencysymbol."1" = xxxxx; ?>
{ "pile_set_name": "StackExchange" }
Q: Invalid use of group function SELECT COUNT(Value) FROM (SELECT * FROM `***` AS t2 WHERE Ygeo > 0 AND DATEDIFF(SpeedBeginDate, CURDATE()) > 14 AND Sum(Loss) > 1000 GROUP BY HEX(Hash1)) AS t1; В чем может быть проблема? A: Вы используете агрегатную функцию SUM в конструкции WHERE. Этого делать нельзя. Для использования агрегатных функций в условии надо использовать HAVING: SELECT COUNT(Value) FROM ( SELECT * FROM `***` AS t2 WHERE Ygeo > 0 AND DATEDIFF(SpeedBeginDate, CURDATE()) > 14 GROUP BY HEX(Hash1) HAVING Sum(Loss) > 1000 ) AS t1;
{ "pile_set_name": "StackExchange" }
Q: Newb PHP mail form not working I'm sure this is a very basic answer and that I'm overlooking something obvious. I'm trying to get a mail form to work correctly, but it keeps giving sending me to the the php page with the error message stating that the name and comments I entered do not appear to be valid. My HTML: <div id="footer" class="container"> <header> <h2>Questions or comments? <strong>Get in touch:</strong></h2> </header> <div class="row"> <div class="6u"> <section> <div id="contact-form"> <form name="feedback" method="post" action="php/send_form_email.php"> <div class="row half"> <div class="6u"> <input name="name" placeholder="Name" type="text" class="text" /> </div> <div class="6u"> <input name="email" placeholder="Email" type="text" class="text" /> </div> </div> <div class="row half"> <div class="12u"> <textarea name="message" placeholder="Message"></textarea> </div> </div> <div class="row half"> <div class="12u"> <input type="submit" value="submit"> <a href="php/send_form_email.php"></a> </div> </div> </form> </div> </section> My PHP: <?php if(isset($_POST['email'])) { $email_to = "[email protected]"; $email_subject = "Message from rmcabinetry.com"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // validation expected data exists if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['name']; // required $email_from = $_POST['email']; // required $comments = $_POST['message']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$name)) { $error_message .= 'The Name you entered does not appear to be valid.<br />'; } if(strlen($message) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.<br />'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Name: ".clean_string($name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Message: ".clean_string($message)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> <!-- include your own success html here --> Thank you for contacting Riley Mills. We will be in touch with you very soon. <?php } ?> A: This is the error: if(strlen($message) < 2) { You defined the variable as $comments earlier but reference $message here. There is no $message defined any place in your code. Solution: Replace $message with $comments in that section, as well as where it appears further below: $email_message .= "Message: ".clean_string($message)."\n"; OR Replace $comments with $message above where it's defined: $comments = $_POST['message']; // required
{ "pile_set_name": "StackExchange" }
Q: Python - Pygame - rendering translucent text I am using pygame.font.Font.render() to render some text. I'd like the text to be translucent, ie have an alpha value other than 255, so I tried passing a color argument with an alpha value (eg (255, 0, 0, 150)) as the color argument for pygame.font.Font.render() but it didn't have any effect. I also tried using pygame.Surface.convert_alpha() on the resulting Surface object, but that didn't do anything either. Any ideas? A: I'm not sure why, but after some experimentation I have discovered that the surface created with font.render cannot have it's alpha value changed. Just blit that surface to another surface, and change the alpha value of the new surface. textsurface=font.render('Test', True, (0, 0, 0)) surface=pygame.Surface((100, 30)) surface.fill((255, 255, 255)) surface.blit(textsurface, pygame.Rect(0, 0, 10, 10)) surface.set_alpha(50) window.blit(surface, pygame.Rect(0, 30, 10, 10))
{ "pile_set_name": "StackExchange" }
Q: What happens when you place a Ghost Ward beyond the Sightstone's limit? The new Sightstone seems like a fantastic value, Unique: Ghost Ward - Consumes a charge to place a Ghost Ward. You may have a maximum of 2 wards from this item at once. What happens when you put down a third ward while two are still on the map? Does the same happen with the Ruby Sightstone? A: It deletes the oldest ghost ward out at the time and places your new one down. See below for examples Here is two wards from the sight stone You can see the other ward fading out after I placed the third After getting the ruby sight stone I can place a third ward with the other two out However trying to place a fourth ward causing the oldest to disappear still
{ "pile_set_name": "StackExchange" }
Q: how to move images in openGL ES? I have developed some how 5 iphone application, but now there is one game, and still I haven't any idea except word open GL ES, I read it a bit but I need some explanation and guidance for developing it. The theme of game is like "there are many objects are moving from down to upside and i have to pick them and drag in boxes according to their color" can anyone help me for showing proper way how to achieve, the study sources and other material,, Thanks in Advance,,, A: Not a direct answer but why don't you use an objective-c wrapper like cocos2d. That would speed up the things.
{ "pile_set_name": "StackExchange" }
Q: Search entries by matrix field I have a matrix inside of which I have 2 fields, 1. dropdown list containing download types and another asset field. I would like to search first by a category and then I would like to further filter them and see if they have downloads of a certain type. I would like to avoid a 2 step searching if possible and search articles that belong to certain category that have a certain download type associated with it. Any idea on how to achieve this? A: You could loop through the Matrix field on every entry save using the awesome Preparse plugin, to store the categories an entry contains in a new field. https://github.com/aelvan/Preparse-Field-Craft Here’s example code for your Preparse field, it would store strings like firstCategory,thirdCategory,secondCategory. {%- set categories = [] %} {%- for block in entry.myMatrixField.type('myRelevantBlockType') %} {%- if block.myDropdownField %} {%- set categories = categories|merge([ block.myDropdownField.value ]) %} {%- endif %} {%- endfor %} {{- categories|join(',') -}} Once you have populated that field for all your entries, you can filter them by a category using this criteria model. {% set categoryToSearch = 'secondCategory' %} {% set entries = craft.entries({ section: 'myEntriesSection', search: 'myPreparseFieldHandle:*' ~ categoryToSearch ~ '*', }) %} I have to say that I’m not very proud of this solution as it uses search which I usually try to avoid. But I wasn’t able to come up with a better idea.
{ "pile_set_name": "StackExchange" }
Q: Dynamic REST API call angular I have been successful in accessing static API data on the page. I am now trying to access dynami API. I have read some documentation to access the dynamic API, but the documentation by API provider is different from online resources. I am not sure what changes I have to make in existing code to access dynamic API data. Here is the link from API provider - https://drive.google.com/file/d/0B2HH3TWuI4Fdc3RfNGVocy1pT0tuSXlLdHlPMUZSRG5GTWJV/view. I am also confused about the contracts and getter, setter mentioned in the documentation. How and where should I use them? Here is my code for accessing Name, Line and MoneyLine data from static json API - https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json How can I make use of the documentation and access live API data? api.component.ts code import {Component} from '@angular/core'; import {HttpClient} from '@angular/common/http' import {forkJoin} from 'rxjs'; import {map} from 'rxjs/operators'; @Component({ selector: 'app-mlb-api', templateUrl: './mlb-api.component.html', styleUrls: ['./mlb-api.component.css'] }) export class MlbApiComponent { //allhomeTeamName; //allawayTeamName; allline; allOdds; allName; all: Array<{line: string, name: string,oddsAmerican:string}> = []; firstLinePerGame: Array<string>; oddsAmericans: Array<string>; constructor(private http: HttpClient) {} ngOnInit() { const character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json').pipe(map((re: any) => re.events)); const characterHomeworld = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17'); this.firstLinePerGame = new Array<string>(); //this.oddsAmericans = new Array<string>(); forkJoin([character, characterHomeworld]).subscribe(([draftkingsResp, fantasylabsResp]) => { //this.allhomeTeamName = draftkingsResp.map(r => r.homeTeamName); //this.allawayTeamName = draftkingsResp.map(r => r.awayTeamName); this.allName = draftkingsResp.map(r => r.name); this.allline = draftkingsResp.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line); this.allline = this.allline.filter(l => !!l); this.allOdds = draftkingsResp.map(r => r.offers).flat().map(r=>r.outcomes[0]).flat().map(o=>o.oddsAmerican); this.createAllArray(); }); } createAllArray(): void { for (let i = 0; i < this.allline.length; i++) { let item = { line: this.allline[i], //awayTeam: this.allawayTeamName[i], //homeTeam: this.allhomeTeamName[i], name:this.allName[i], oddsAmerican: this.allOdds[i] } this.all.push(item); } } } api.component.html code <table class="table table-striped table-condensed table-hover"> <thead> <tr> <!-- <th class="awayTeamName">awayTeamName&nbsp;<a ng-click="sort_by('awayTeamName')"><i class="icon-sort"></i></a></th> <th class="field3">homeTeam&nbsp;<a ng-click="sort_by('HomeTeam')"><i class="icon-sort"></i></a></th> --> <th class="field3">Name&nbsp;<a ng-click="sort_by('Name')"><i class="icon-sort"></i></a></th> <th class="line">Line&nbsp;<a ng-click="sort_by('line')"><i class="icon-sort"></i></a></th> <th class="field3">Money Line&nbsp;<a ng-click="sort_by('oddsAmericans')"><i class="icon-sort"></i></a></th> </tr> </thead> <tbody> <ng-container *ngFor="let item of all| paginate: { itemsPerPage: 5, currentPage: p }; let i = index"> <tr> <td>{{item.name }}</td> <!-- <td>{{item.awayTeam}}</td> <td>{{item.homeTeam}} </td> --> <td>{{item.line }}</td> <td>{{item.oddsAmerican}}</td> </tr> </ng-container> </tbody> </table> <pagination-controls (pageChange)="p = $event"></pagination-controls> A: I have updated the code according to your requirement. I have made use of the observables to fetch the live data here in the link https://stackblitz.com/edit/stackoverflow-24-06-2019-ewzpst?file=src/app/app.component.html
{ "pile_set_name": "StackExchange" }
Q: Use of Accept-charset HTTP header What are the differences and advantages of using one over the other: Accept: application/json;charset=utf-8 versus: Accept: application/json Accept-Charset: utf-8 Is the first form compliant to rfc 2616? Note: could be json or xml, etc. A: Both of them are compliant. But I prefer second one. "charset" parameter is for media type and media types are defined by IANA, not by RFC 2616. Even if the server understands RFC 2616, you cannot be sure it understands "charset" parameter. Some media types may not have "charset" parameter.
{ "pile_set_name": "StackExchange" }
Q: Grab all characters inside {...} if not contain "{" and "}" I want catch all character inside { ... }, If inside not found "{" and "}" So for example: {amdnia91(\+wowa} Catch it. {amdn{ia91(\+wowa} Not catch (contain "{"). preg_match_all('#(.+?)\{(.+?)\}#', $input, $output); How fix it? EDIT. Explained more: I will try to create css minifier. But there i need catch all names and content inside brackets as separate array value. Curret $input look like this: .something{property:value;prop2:value}#something2{someprop:val;prop:val} It is also minfied so containt multiple ...{}...{} inline. And my code catch all good but... This catch also if inside brackets its brackets, but i don't want catch it if contain brackets inside. A: [^}{] means match any character that is not } or {. So: preg_match_all('#\{([^}{]+)\}#', $input, $output); However, note that in your {amdn{ia91(+wowa} example, this will match the ia91(+wowa fragment. EDIT If you didn't want any match at all for that second example, then try this: preg_match_all('#^[^}{]*\{([^}{]+)\}[^}{]*$#', $input, $output); The regex broken down means: ^ - The start of the line [^}{]* - Any character which is not { or } zero or more times \{ - The literal { character ([^}{]+) - Capture one or more characters which are not { or } \} - The literal } character [^}{]* - Any character which is not { or } zero or more times $ - The end of the line Demonstration Second Edit Given your further explanation on what you need, I'd suggest this: preg_match_all('#(?<=^|})[^}{]*?\{([^}{]+?)\}(?=[^}]*$|[^}]*\{)#', $input, $output); This uses a "look-behind" and a "look-ahead". Broken down, it means: (?<=^|}) Lookbehind: Assert that this is either the start of the line or that the previous character was a literal '}' but do not include that character as part of the whole match [^}{]*? - Lazily match zero or more characters which are not { or } \{ - A literal { ([^}{]+?) - Lazily capture one or more characters which are not { or } \} - A literal } (?=[^}]*$|[^}]*\{) - Lookahead: Ensure that the following characters are either zero or more characters which are not } followed by the line end, or zero or more characters which are not } followed by a literal { but do not include those characters as part of the whole match Demonstration
{ "pile_set_name": "StackExchange" }
Q: Sweave,R,Beamer : How to convert the LaTex text in an Rnw file to R comments? Say I have a .Rnw file containing the usual LaTex mixed in with R code chunks. (I'm especially interested in converting a .Rnw slides document, but this question applies to any .Rnw document). Now I want to convert this to a file which contains all of the R code, plus all of the text that would normally be generated by LaTex, as R comments. In other words, the functionality I want is similar to what Stangle() does, but I also want all the text part of the LaTex converted to plain text that's commented out in the resulting .R file. This would be a very convenient way to automatically generate a commented R file that's easy to look at in your favorite syntax-highlighting editor (e.g. emacs). This might not sound like a great idea for an Sweave document that's a long article with only a bit of R code, but it starts to look appealing when the .Rnw document is actually a slide presentation (e.g. using beamer) -- then the text portion of the slides would make perfect comments for the R code. Anyone have any ideas on how to do this? Thanks in advance. A: Here is one approach using regex. There are still some issues that remain, and I will maintain a list which will be updated with resolutions. # READ LINES FROM RNW FILE lines <- readLines('http://users.stat.umn.edu/~charlie/Sweave/foo.Rnw') # DETECT CODE LINES USING SWEAVE CHUNK DEFINITIONS start_chunk <- grep("^<<.*=$", lines) end_chunk <- grep("^@" , lines) r_lines <- unlist(mapply(seq, start_chunk + 1, end_chunk - 1)) # COMMENT OUT NON CODE LINES AND WRITE TO FILE lines[-r_lines] <- paste("##", lines[-r_lines]) writeLines(lines, con='codefile.R') ISSUES REMAINING: Does not deal well with chunks called inside other chunks using <<chunk_name>>
{ "pile_set_name": "StackExchange" }
Q: If $f , g \in L^2 \cap L^\infty$, then $ \| fg \|_2 \leqslant c ( \|f \|_\infty + \| g \|_\infty ) $? Prove that there exists $c >0$ such that for $f , g \in L^2 ( \mathbb R) \cap L^\infty ( \mathbb R)$ , $$ \| fg \|_{L^2(\mathbb R)} \leqslant c ( \|f \|_\infty + \| g \|_\infty ). $$ Is this true? If so, would you give me a proof for this? A: Suppose it's true. Take $f$, $g$ such that $\| fg \|_{L^2(\mathbb R)}>0\;$. Then for any $a>0$ where whould hold the inequality $$ a^2\| fg \|_{L^2(\mathbb R)} \leqslant c a ( \|f \|_\infty + \| g \|_\infty ). $$ A contradiction. A: More generally, we can't find a function $F\colon \Bbb R^2\to \Bbb R$ such that for all $f,g\in L^2(\Bbb R)\cap L^{\infty}(\Bbb R)$, $$\lVert fg\rVert_{L^2(\Bbb R)}\leq F(\lVert f\rVert_{\infty},\lVert g\rVert_{\infty}).$$ Indeed, consider for a fixed $n$, $f_n=g_n=\chi_{(0,n)}\in L^2\cap L^{\infty}$. Then $$\lVert f_ng_n\rVert_{L^2}=\sqrt n,\quad \lVert f_n\rVert_{\infty}=\lVert g_n\rVert_{\infty}=1,$$ and we would have for each integer $n$, $$\sqrt n\leq F(1,1),$$ which is impossible.
{ "pile_set_name": "StackExchange" }
Q: Nginx routing got cached? On my VPS I have two virtual servers for: 1) apache app (blog), 2) main app Blog (lets call it app1) can be accessed as a subdomain via: blog.sitename.com -> app1. Main app has a language subdomain access as well, so I defined a wildcard access like this: *.sitename.com -> app2. And by default sitename.com resolves to app2. Everything worked great up until last Thursday or Friday (don't remember the exact day). The problem is: blog.sitename.com started being resolved by app2 (not by app1), so the end-user landed on app2 page and "blog" was treated as a language. Also I noticed that this problem didn't occure in some of my browsers (Safari, for example). I tried clearing the cache and cookies for other browsers and it started working again after that. Of course I will not be able to explain this to the users of my site, so is there any way to invalidate the cache (or whatever it is) so that everything would start working again? And yes, I tried setting sendfile off in nginx.conf file and restarting nginx - didn't work. upstream app2 { server unix:/tmp/app2.sock fail_timeout=0; } server { server_name blog.sitename.com; access_log /var/log/nginx/blog.sitename.com.access.log main; error_log /var/log/nginx/blog.sitename.com.error.log; root /var/www/app1; # Wordpress blog index index.php; location / { index index.php; try_files $uri $uri/ /index.php?q=$uri&$args; } location ~ \.php$ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:8081; proxy_redirect off; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; } } server { server_name sitename.com 123.123.123.123; rewrite ^(.*) http://www.sitename.com$1 permanent; } server { listen 80 default deferred; # for Linux listen 443 ssl; # Handle SSL connection ssl_certificate /root/ssl/ssl.crt; ssl_certificate_key /root/ssl/ssl.key; client_max_body_size 4G; server_name *.sitename.com; root /root/app2/public; keepalive_timeout 10; try_files $uri/index.html $uri.html $uri @app; location @app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # HTTP or HTTPS proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app2; } # serve static assets location ~ ^/(assets)/ { gzip_static on; expires 1y; add_header Cache-Control public; } error_page 500 502 503 504 /500.html; location = /500.html { root /root/app2/public; } } A: OK. Finally I found the source of all my problems! Never ever ever ever use 301 redirect if are not 100% sure that it should be that way. 301 redirects get cached on a browser level and there is no way to clear it out. Use 302 instead. And only when you are 100% sure that everything is correct - implement 301, as it is beneficial for performance.
{ "pile_set_name": "StackExchange" }
Q: how we delete a row from parent table when child table connected with paren table by forigen key hi all i am getting a problem while i attenpting to delete a row from parent table, actuall i have created 2 table custmer and account.i make cutomer id(primary key) in customer and customer id (forigen key ) in account.after created it i have filled data inside both table. at this point while i am trying to delete a row from first table (customer ) then it give failure message is that it can't be deleted bcs it is refrenced as forigen key some thing like that............but while we delete row from account table then it's delete sucess fully. .......i want to function like that if i delete a row from parent table(customer) then its in child table that row which has same customer id (account table) is delete automatically............ A: watch out on the cascade deletes! a user will accidentally click on the application's little trash can icon and delete the customer, and then all the cascades will remove every trace of that customer, orders, invoices, payments, history, etc from your database. After the user call you to tell you about their little mistake, you'll have to restore a backup and try to pull the info back into the database. I would look into "soft deletes" where you only change the customer's status from "active" to "inactive". the rows is not deleted, preserving all foreign key data. This allows reports to run on the data, because it still exists, as well as easy an "undo". Soft deletes are not the end all only way to go, it is a business decision on how to handle this, purge the data or mark it inactive. That is only something you can decide, because I don't know your application or business logic. I just thought that I would offer it as an alternative.
{ "pile_set_name": "StackExchange" }
Q: Execute function at soft key enter I'm trying to add a way to execute a function on a soft key enter (or whatever the bottom right hand key would be, I assume its usually a enter/done key) once a edit text field has been filled in with numbers. I also have a calculate button that I would like to keep as a back up in an attempt to 'idiot proof' the app a little bit. below is a snippet of my code thus far; this part is working: onCalculate refers to a button I have. I have error checking for null values and whatever else. EditText something public void onCalculate (View v){ do stuff.... } I want to add something down here to 'do stuff' in the event the user presses the done/enter/bottom right hand soft key instead of pressing the button. Below is a snippet from my layout XML: <EditText android:id="@+id/editText1" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="20dp" android:ems="10" android:inputType="numberDecimal" android:textSize="15sp" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_margin/> I know I probably need to create some kind of key listener for the enter key, but I'm not sure how to go about it. A: You can achieve this by associating an OnEditorActionListener to the EditText. For example: editText1.setImeOptions(EditorInfo.IME_ACTION_DONE); editText1.setOnEditorActionListener(new new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_DONE) { onCalculate(editText1); return true; } } });
{ "pile_set_name": "StackExchange" }
Q: How to select string with less amount of specfied xml tag with sql I have a table where each item have a nvarchar(max) item with xml text. I need some way to chose string with xml in which less amount of specified tag. How to do this in faster way? I read about STRING_SPLIT but it supported only with db with compatibility level 130 and I have compatibility level 110. So for example I have two xml: <main tag> <child> </child> <child> </child> </main tag> and <main tag> <child> </child> </main tag> I need to take <main tag> <child> </child> </main tag> Because the quantity of <child> tag in the second xml is less then in first xml string. SOLUTION I have found the solution. And Its pretty simple. Declare @TempXML Table (XMLText XML) Insert into @TempXML Select t.XMLString from dbo.MyXMLProcedure t Then Select t.XMLText.VALUE('count(/main tag/child)','int') from @TempXML t A: In general, you can't determine the number of XML tags in an XML string using simple string operations, but assuming you are willing to live with the limitations, you can use: (len(@string) - len(replace(UPPER(@string), UPPER(@xmltag), '')))/len(@xmltag) to count the number of occurrences of a specific tag (e.g. use @xmltag = '<CHILD'). If you were working with an XML datatype column, you could use the XQuery count function: SELECT xml.value('count /Main/Child') FROM table
{ "pile_set_name": "StackExchange" }
Q: Calling constructor with member as argument parsed as variable definition I observed peculiar behavior in g++4.6.3. When creating a temporary by calling class constructor File(arg) the compiler chooses to ignore the existence of arg and parse the expression as File arg; Why is the member name ignored? What does the standard say? How to avoid it? (Without using new {} syntax) Is there a related compiler warning? (I could use an arbitrary string arg and it would still work quietly) Code: #include <iostream> class File { public: explicit File(int val) : m_val(val) { std::cout<<"As desired"<< std::endl; } File() : m_val(10) { std::cout<< "???"<< std::endl;} private: int m_val; }; class Test { public: void RunTest1() { File(m_test_val); } void RunTest2() { File(this->m_test_val); } void RunTest3() { File(fhddfkjdh); std::cout<< "Oops undetected typo"<< std::endl; } private: int m_test_val; }; int main() { Test t; t.RunTest1(); t.RunTest2(); t.RunTest3(); return 0; } Output: $ ??? $ As desired $ Oops undetected typo A: The compiler treats the line: File(m_test_val); as File m_test_val; so you're actually creating a named object called m_test_val using the default constructor. Same goes for File(fhddfkjdh). The solution is File(this->m_test_val) - this tells the compiler that you want to use the member to create create a named object. Another would be to name the object - File x(m_test_val).
{ "pile_set_name": "StackExchange" }
Q: Memcached - Single parent config, multiple child configs I am setting up a memcached server in production, and would like the ability to switch between various memory sizes simply by changing out a symlink from one config to another, however I do not want to copy and paste every config into every other config, is it possible to have a master config with multiple child configs? Example: # master config PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="128" OPTIONS="" # Name: memcached_256 # child config for cache server of 256 # include options from master config CACHESIZE="256" # Name: memcached_512 # child config for cache server of 512 # include options from master config CACHESIZE="512" Example dir listing: ls /etc/sysconfig memcached -> /path/to/my/version/controlled/configs/memcached_256 And if I ever need to upgrade, I can simply change the above symlink to: memcached -> /path/to/my/version/controlled/configs/memcached_512 Then after changing out the symlink, simply restart the service. Or if there is a better way to accomplish this functionality, that would be appreciated as well. A: It looks like those files are sourced by the initscript which starts memcached, and not read by memcached itself. You could therefore probably source the master configuration from the child configurations, for example: /etc/sysconf/memcached_master: PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="128" OPTIONS="" /etc/sysconf/memcached_256: . /etc/sysconfig/memcached_master CACHESIZE="256" /etc/sysconf/memcached_512: . /etc/sysconfig/memcached_master CACHESIZE="512" And then symlink /etc/sysconfig/memcached to the child configuration you want to use.
{ "pile_set_name": "StackExchange" }
Q: how to solve second order nonlinear coupled differential equations using NDSolve with hyperbolic function i have to solve some solitons scattering through this coupled equations. i need to get two different graph, but still the graph did not come out. and also the equations quite complicated containing hyperbolic trigo . (maybe just for me). i dont know whether the problems come from the hyperbolic equations that i used, or becoz of initial condition.the coding as below: u = 0.05; g = 0.2; s = NDSolve[{x''[t] == 4/(\[Pi]^2 x[t]^3) - 10/(\[Pi]^2 x[t]^2) - (80 g)/(3 \[Pi]^2 x[t]^3) - ((6 u)/(\[Pi]^2 x[t]^2))[1/Cosh[y[t]/x[t]]^2 - (2 y[t])/x[t] Sinh[y[t]/x[t]]/Cosh[y[t]/x[t]]^3], y''[t] == u (y[t]/(x[t]^3))[Sinh[y[t]/x[t]]/Cosh[y[t]/x[t]]^3], x[1] == -3, x'[1] == 0, y[0] == 1, y'[0] == 3}, {x, y}, {t, 0,100}] Plot[Evaluate[{x[t], y[t]} /. %], {t, 0, 100}, PlotRange -> All, PlotPoints -> 200] A: First, your code contains simple mistake, you should distinguish [] from (), then your equations still can't be solved, it's a common problem for the boundary value problem (BVP) of nonlinear ODE(s), and the almost only solution as far as I know is "shooting method": u = 5/100; g = 2/10; s = NDSolve[{x''[t] == 4/(π^2 x[t]^3) - 10/(π^2 x[t]^2) - (80 g)/(3 π^2 x[t]^3) - ((6 u)/(π^2 x[t]^2))(1/Cosh[y[t]/x[t]]^2 - (2 y[t])/x[t] Sinh[y[t]/x[t]]/Cosh[y[t]/x[t]]^3), y''[t] == u (y[t]/(x[t]^3))(Sinh[y[t]/x[t]]/Cosh[y[t]/x[t]]^3), x[1] == -3, x'[1] == 0, y[0] == 1, y'[0] == 3}, {x, y}, {t, 0, 100}, Method -> {"Shooting", "StartingInitialConditions" -> {x[0] == -3, x'[0] == 0, y[0] == 1, y'[0] == 3}}] Plot[{x[t], y[t]} /. s, {t, 0, 100}, PlotRange -> All, Evaluated -> True]
{ "pile_set_name": "StackExchange" }
Q: Is there any way to save the path and restore it in Cairo? I have two graphs of drawing signals on a gtkmm application. The problem comes when I have to paint a graph with many points (around 300-350k) and lines to the following points since it slows down a lot to paint all the points each iteration. bool DrawArea::on_draw(const Cairo::RefPtr<Cairo::Context>& c) { cairo_t* cr = c->cobj(); //xSignal.size() = ySignal.size() = 350000 for (int j = 0; j < xSignal.size() - 1; ++j) { cairo_move_to(cr, xSignal[j], ySignal[j]); cairo_line_to(cr, xSignal[j + 1], ySignal[j + 1]); } cairo_stroke(cr); return true; } I know that exist a cairo_stroke_preserve but i think is not valid for me because when I switch between graphs, it disappears. I've been researching about save the path and restore it on the Cairo documentation but i don´t see anything. In 2007, a user from Cairo suggested in the documentation 'to do' the same thing but apparently it has not been done. Any suggestion? A: It's not necessary that you draw everything in on_draw. What I understand from your post is that you have a real-time waveform drawing application where samples are available at fixed periods (every few milliseconds I presume). There are three approaches you can follow. Approach 1 This is good particularly when you have limited memory and do not care about retaining the plot if window is resized or uncovered. Following could be the function that receives samples (one by one). NOTE: Variables prefixed with m_ are class members. void DrawingArea::PlotSample(int nSample) { Cairo::RefPtr <Cairo::Context> refCairoContext; double dNewY; //Get window's cairo context refCairoContext = get_window()->create_cairo_context(); //TODO Scale and transform sample to new Y coordinate dNewY = nSample; //Clear area for new waveform segment { refCairoContext->rectangle(m_dPreviousX + 1, m_dPreviousY, ERASER_WIDTH, get_allocated_height()); //See note below on m_dPreviousX + 1 refCairoContext->set_source_rgb(0, 0, 0); refCairoContext->fill(); } //Setup Cairo context for the trace { refCairoContext->set_source_rgb(1, 1, 1); refCairoContext->set_antialias(Cairo::ANTIALIAS_SUBPIXEL); //This is up to you refCairoContext->set_line_width(1); //It's 2 by default and better that way with anti-aliasing } //Add sub-path and stroke refCairoContext->move_to(m_dPreviousX, m_dPreviousY); m_dPreviousX += m_dXStep; refCairoContext->line_to(m_dPreviousX, dNewY); refCairoContext->stroke(); //Update coordinates if (m_dPreviousX >= get_allocated_width()) { m_dPreviousX = 0; } m_dPreviousY = dNewY; } While clearing area the X coordinate has to be offset by 1 because otherwise the 'eraser' will clear of the anti-aliasing on the last coulmn and your trace will have jagged edges. It may need to be more than 1 depending on your line thickness. Like I said before, with this method your trace will get cleared if the widget is resized or 'revealed'. Approach 2 Even here the sample are plotted the same way as before. Only difference is that each sample received is pushed directly into a buffer. When the window is resized or 'reveled' the widget's on_draw is called and there you can plot all the samples one time. Of course you'll need some memory (quite a lot if you have 350K samples in queue) but the trace stays on screen no matter what. Approach 3 This one also takes up a little bit of memory (probably much more depending on the size of you widget), and uses an off-screen buffer. Here instead of storing samples we store the rendered result. Override the widgets on_map method and on_size_allocate to create an offsceen buffer. void DrawingArea::CreateOffscreenBuffer(void) { Glib::RefPtr <Gdk::Window> refWindow = get_window(); Gtk::Allocation oAllocation = get_allocation(); if (refWindow) { Cairo::RefPtr <Cairo::Context> refCairoContext; m_refOffscreenSurface = refWindow->create_similar_surface(Cairo::CONTENT_COLOR, oAllocation.get_width(), oAllocation.get_height()); refCairoContext = Cairo::Context::create(m_refOffscreenSurface); //TODO paint the background (grids may be?) } } Now when you receive samples, instead of drawing into the window directly draw into the off-screen surface. Then block copy the off screen surface by setting this surface as your window's cairo context's source and then draw a rectangle to draw the newly plotted sample. Also in your widget's on_draw just set this surface as the source of widget's cairo context and do a Cairo::Context::paint(). This approach is particularly useful if your widget probably doesn't get resized and the advantage is that the blitting (where you transfer contents of one surface to the other) is way faster than plotting individual line segments.
{ "pile_set_name": "StackExchange" }
Q: Notificador de qualquer evento que o usuário realizar no sistema Estou usando o Framework Spring para o java e gostaria de criar posso criar um tipo de aviso, <scan>, que mostra na tabela que uma nova linha foi adicionada (essa linha vem do banco de dados), e ao clicar nela sumir dando a entender que a linha foi vista, como se fosse um notificador de Facebook por exemplo, mas cada usuário tem o seu, ou seja, avisar para cada um que existe uma nova linha. A: Imagino que voce precise criar algo utilizando aspectos do Spring. Mais informações aqui Com AspectJ, voce pode monitorar algum ponto da sua aplicação e executar processamentos antes, durante ou depois conforme as anotações @Before, @After, @AfterReturning... Esse tipo de programação é muito utilizado pra logs de aplicação, mas pode ser perfeitamente aplicado no seu caso. Com o AspectJ configurado, voce pode executar uma ação @After no seu método de persistência da linha de tabela, e persistir alguma coisa em uma tabela de avisos associada aos usuários.
{ "pile_set_name": "StackExchange" }
Q: To built a series or sequence of coordinates of barycenters of a polygon decomposed into triangles Suppose that we have a convex polygon with $n$ edges. In this case I have drawn a convex polygon with $n=5$. We know that for a homogeneous (or non homogeneous) solid, there are formulas to calculate the coordinates of the centre of gravity using triple integrals (or double integrals) for my image. Since I have decomposed my polygon into three triangles each of these triangles will have its centre of gravity $G_i, \text { for } i=1,2,3$. My question is the following: Is it possible to create a series or a sequence such that the centre of gravity $G_i$ of each triangle that make up the polygon, converges to the centre of gravity $G$ (where it is possible to find exactly its coordinates) when we use the formulas with the integrals? A: Yes. Label your triangles $T_1, T_2, ...$ Let the centres of masses of the triangles be $(x_1,y_1), (x_2,y_2), ...$ Let the masses of the triangles be $m_1, m_2, ...$ Let the centre of mass of the whole shape after $n$ triangles have been added be $(\bar x_n, \bar y_n)$ Let the total mass of the whole shape after $n$ triangles have been added be $M_n=\Sigma_1^n m_i$ Adding another triangle with mass $m_{n+1}$ and centre of mass $(x_{n+1},y_{n+1})$ means $M_{n+1}=M_n+m_{n+1}$ $\bar x_{n+1} M_{n+1} = \bar x_{n} M_{n} + x_{n+1} m_{n+1}$ So $\bar x_{n+1} = \frac{\bar x_{n} M_{n} + x_{n+1} m_{n+1}}{M_n+m_{n+1}}$ Similarly $\bar y_{n+1} = \frac{\bar y_{n} M_{n} + y_{n+1} m_{n+1}}{M_n+m_{n+1}}$ Example For the shape shown above, we have: $M_1=m_1=126$ $\bar x_1=x_1=126$ $\bar y_1=y_1=28$ $M_2=M_1+m_2=126+225=351$ $\bar x_2=\frac{\bar x_1\times M_1+x_2\times m_2}{M_1+ m_2}=15.41$ $\bar y_2=\frac{\bar y_1\times M_1+y_2\times m_2}{M_1+ m_2}=25.44$ $M_3=M_2+m_3=351+108=459$ $\bar x_3=\frac{\bar x_2\times M_2+x_3\times m_3}{M_2+ m_3}=17.67$ $\bar y_3=\frac{\bar y_2\times M_2+y_3\times m_3}{M_2+ m_3}=23.45$ $M_4=M_3+m_4=459+144=603$ $\bar x_4=\frac{\bar x_3\times M_3+x_4\times m_4}{M_3+ m_4}=18.46$ $\bar y_4=\frac{\bar y_3\times M_3+y_4\times m_4}{M_3+ m_4}=20.24$
{ "pile_set_name": "StackExchange" }
Q: Android Studio Emulator wont start "Waiting for target device to come online" So I am currently learning how to develop android apps. I am making my first application and I have no errors but my emulator wont run my app. It is stuck on "Waiting for target device to come online". I am confused on what is wrong because It has worked before. I completely reinstalled everything and it still does not work. Not sure what to do. A: Uncheck then recheck 'Enable ADB Integration' from the Android Studio 'Tools - Android' menu and it will work.
{ "pile_set_name": "StackExchange" }
Q: PyGObject and Gtk.TreeStore / TreeView - How do I acces the parent element? I'm working with PyGObject and I successfully setup a TreeStore and a corresponding TreeView. It is just a simple one-column view. It lists all accounts as parents and then you can click the little triangle and it shows the folders. The code looks like this: accounts_tree_store = Gtk.TreeStore(str) treeview_accounts = self.builder.get_object("treeview_accounts") treeview_accounts.set_model(accounts_tree_store) renderer = Gtk.CellRendererText() account_iter = accounts_tree_store.append(None, ["Account1"]) accounts_tree_store.append(account_iter, ["Folder1"]) accounts_tree_store.append(account_iter, ["Folder2"]) accounts_tree_store.append(account_iter, ["Folder3"]) accounts_tree_store.append(account_iter, ["Folder4"]) accounts_tree_store.append(account_iter, ["Folder5"]) Then I added this so I can get a selection: selected_tree = treeview_accounts.get_selection() selected_tree.connect("changed", Handler().on_tree_select_change) And my function handler looks like this: def on_tree_select_change(self, widget, *args): model, iter = widget.get_selected() if iter: print((model[iter][0])) Now all this works just fine. But I want to also print out the parent of the element that is selected. Something like: "Folder2 for Account4". The question is: How can I access the parent? Is there some sort of "get_parent()" function? I didn't find anything in the docs. Does anyone know how to do this? Thanks in advance!! A: This fuction is called iter_parent and will return parent if iter has one. It's a model's method. model, iter = widget.get_selected() parent = model.iter_parent (iter)
{ "pile_set_name": "StackExchange" }
Q: How to give different colors to parts of the main of a plot I simply represent the curves of Average Total Costs, Average Variable Costs, Average Fixed Costs and Marginal Costs. plot(Q,ATCosts,ylab=NA,ylim=c(0,62),type="l") par(new=T) plot(Q,AVCosts,ylab=NA,ylim=c(0,62),type="l",col="blue") par(new=T) plot(Q,AFCosts,ylab=NA,ylim=c(0,62),type="l",col="red") par(new=T) plot(Q,MCosts,ylab=NA,ylim=c(0,62),type="l",col="green") The main is: title(main="ATC,AVC,AFC,MC") What I would like to know is if there is a way to give each piece of the main (containing a certain type of cost) the color related to that cost in the plot, in order to avoid to use a legend. Thus, ATC must be written in black; AVC must be written in blue...and so on. I tried to overlap another title in the following way: title(main=" ,AVC, , ",col.main="blue") But it didn't give a decent result. A: Not a general solution, because you have to play with the adj to get the right spacing, but it works: plot(1) mtext("ATC, ",col='black',line=2,adj=0.4) mtext("AVC, ",col='blue',line=2,adj=0.45) mtext("AFC, ",col='red',line=2,adj=0.5) mtext("MC",col='green',line=2,adj=0.54)
{ "pile_set_name": "StackExchange" }
Q: Does this Infinite summation of Bessel function has a closed form? The summation is $$\sum_{n>0}\frac{J_n^2(x)}{n}\sin\frac{2n\pi}{3}$$ I found a thread Infinite sum of Bessel Functions and a wiki article here may be helpful. However, I still cannot figure this out. Also see the description of Bessel function of first kind at Mathworld, equation 61-66 may be helpful. A: Neumann's addition theorem is given by \begin{align} J_{0}\left(\sqrt{x^{2} + y^{2} - 2 x y \cos\phi}\ \right) = J_{0}(x) J_{0}(y) + 2 \sum_{n=1}^{\infty} J_{n}(x) J_{n}(y) \cos(n\phi). \end{align} By letting $y=x$ it can quickly be sen that \begin{align} J_{0}\left(2 x \sin(\phi/2) \right) = J_{0}^{2}(x) + 2 \sum_{n=1}^{\infty} J_{n}^{2}(x) \cos(n\phi). \end{align} Integrate both sides with respect to $\phi$ to obtain the expression \begin{align} \sum_{n=1}^{\infty} \frac{1}{n} \, J_{n}^{2}(x) \sin\left(\frac{2 n\pi}{3}\right) = \frac{\pi}{3} \, J_{0}^{2}(x) + \frac{1}{2}\int_{0}^{2\pi/3} J_{0}\left( 2 x \sin\left(\frac{\phi}{2}\right)\right) \, d\phi. \end{align}
{ "pile_set_name": "StackExchange" }
Q: SELECT query getting rows of table as columns in MySQL I have a MySQL database with two tables for questions and answers. Each question has a correct answer and three incorrect answers. There are always four answers for every question and only one is correct. The tables are: CREATE TABLE `question` ( `id_question` smallint(5) unsigned NOT NULL auto_increment, `text` varchar(255) collate utf8_unicode_ci default NULL, PRIMARY KEY (`id_question`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `answer` ( `id_answer` mediumint(8) unsigned NOT NULL auto_increment, `id_question` smallint(5) unsigned NOT NULL, `is_correct` tinyint(1) NOT NULL, `text` varchar(45) collate utf8_unicode_ci default NULL, PRIMARY KEY (`id_answer`,`id_question`), KEY `fk_id_question_idx` (`id_question`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; I need help with a select query. I would like to get a table with questions in the rows and the four answers as columns (first the correct one and then the other three). So far I was able to get an output like this: Question | Answer | Is_Correct ------------------------------- Question 1 Answer 1-1 1 Question 1 Answer 1-2 0 Question 1 Answer 1-3 0 Question 1 Answer 1-4 0 Question 2 Answer 2-1 1 Question 2 Answer 2-2 0 Question 2 Answer 2-3 0 Question 2 Answer 2-4 0 ... How I can get the following result? Question | Correct_Answer | Incorrect_answer1 | Incorrect_answer2 | Incorrect_answer3 -------------------------------------------------------------- Question 1 Answer 1-1 Answer 1-2 Answer 1-3 Answer 1-4 Question 2 Answer 2-1 Answer 2-2 Answer 2-3 Answer 2-4 A: You can pivot the data by using an aggregate function with a CASE expression. You can use user-defined variables to implement a row number on each row by question. Your code will be similar to this: select q.text Question, max(case when a.is_correct = 1 then a.text end) Correct_answer, max(case when a.is_correct = 0 and rn=1 then a.text end) Incorrect_Answer1, max(case when a.is_correct = 0 and rn=2 then a.text end) Incorrect_Answer2, max(case when a.is_correct = 0 and rn=3 then a.text end) Incorrect_Answer3 from question q inner join ( select a.id_question, a.text, a.is_correct, a.id_answer, @row:=case when @prevQ=id_question and is_correct = 0 then @row +1 else 0 end rn, @prevA:=id_answer, @prevQ:=id_question from answer a cross join (select @row:=0, @prevA:=0, @prevQ:=0)r order by a.id_question, a.id_answer ) a on q.id_question = a.id_question group by q.text order by a.id_question, a.id_answer See SQL Fiddle with Demo. This gives the result in separate columns: | QUESTION | CORRECT_ANSWER | INCORRECT_ANSWER1 | INCORRECT_ANSWER2 | INCORRECT_ANSWER3 | ------------------------------------------------------------------------------------------- | Question 1 | Answer 1-1 | Answer 1-2 | Answer 1-3 | Answer 1-4 | | Question 2 | Answer 2-1 | Answer 2-2 | Answer 2-3 | Answer 2-4 |
{ "pile_set_name": "StackExchange" }
Q: UI Screen becomes black after UIAnimation My problem is... I have the object of parent view controller and i wanted to animate second view controller over that. So i added a subview called backgroundview over the view of parentvc.view and then the view which needs to be drawn over the backgroundView. But after animation completes for a second, i can see the views the way i want them to be but then it is replaced by a complete black screen. I think my topmost view is redrawn so how do i rectify this issue. Code :- - (void)viewDidLoad { [super viewDidLoad]; //_colorCaptureOptions = [NSArray arrayWithObjects: @"Camera", @"Color Slider / Color Wheel", nil]; mExtractionQueue = [[NSOperationQueue alloc] init]; [mExtractionQueue setMaxConcurrentOperationCount:1]; CGRect screenRect = [[UIScreen mainScreen] bounds]; //CGRect screenRect = self.view.frame; self.backgroundView = [[UIView alloc] initWithFrame:screenRect]; self.backgroundView.backgroundColor = [UIColor clearColor]; [self.parentVC addChildViewController:self]; [self.parentVC.view addSubview:self.backgroundView]; //[self didMoveToParentViewController:self.parentVC]; UITapGestureRecognizer *guideTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleScrimSelected)]; [self.backgroundView addGestureRecognizer:guideTap]; [self.backgroundView addSubview:self.view]; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat viewHeight = 150; self.backgroundView.alpha = 0.0; self.view.alpha = 1; self.view.frame = CGRectMake(0, screenRect.size.height, screenRect.size.width, viewHeight); [UIView animateWithDuration:0.2 delay:0 options: UIViewAnimationOptionCurveEaseInOut animations:^{ self.backgroundView.alpha = 1.0; self.view.frame = CGRectMake(0, screenRect.size.height - viewHeight, screenRect.size.width, viewHeight); } completion:^(BOOL _finished) { }]; } } A: Well, for clarity you'd better to provide few screenshots. For all the rest: Possibly, your background view is simply black that leads to black screen. Or it even is [UIColor clearColor] better not use childViewController, it breaks MVC better not change frame inside animation directly If you want present another controller with animation, use this UIViewControllerTransitioningDelegate and this UIViewControllerAnimatedTransitioning in your objects, so do not reinvent transitions. Refer to this custom controller transition tutorial Hope this may help you EDIT: [UIColor clearColor] removes colour entirely, so that means you will have no color at all. The best solution for you now is rewrite those controllers, split up one from another, get rid of container for viewControllers, change animation to custom and than problem will disappear as a magic. If you solve you problem, do not forget to mark question as resolved, please
{ "pile_set_name": "StackExchange" }
Q: $T: L^2[0,1] \to L^2[0,1]$, $Tf(x)= \frac{1}{x}\int_{0}^x f(y)$, is a bounded but not compact operator. To show that the image of $T$ lies in $L^2$, and derive its bound, I tried the following: $$\|Tf\|_{2} = \left(\int|\int \frac{1}{x}f(y)dy|^2dx\right)^{\frac{1}{2}} \leq \int \sqrt{\int|\frac{1}{x}f(y)1_{[0,x]}(y)|^2dx}dy = \int_{0}^{1} \sqrt{ \frac{1}{y}-1 }|f(y)|.$$ Then probably using Holder's inequality, but this does not seem to work. Then to show it is not a compact operator, I want to construct a bounded sequence $f_n$ where $Tf_n$ does not have a convergent subsequence. A: For the continuity of $T$, you can also check the link by mechanandroid. For compactness, however, this link sends you to this question, where it is shown that $T : \mathcal{C} ([0,1]) \to \mathcal{C} ([0,1])$ is not compact, but $T : \mathcal{C} ([0,1]) \to \mathbb{L}^2 ([0,1])$ is compact. Of course, the functions used there are not suitable to show the non-compactness of $T : \mathbb{L}^2 ([0,1]) \to \mathbb{L}^2 ([0,1])$. Hence this question does not seem to be a duplicate. Now, what would a suitable sequence of function $(f_n)$ look like? We want $\|f_n\|_{\mathbb{L}^2} \equiv 1$, an $T(f_n)$ as large as possible (so as to avoid convergence to $0$). The first thing is to avoid cancellations in the integral, since it makes $T(f_n)$ smaller. So let us look for non-negative $f_n$. Then, we would like to put the most possible mass close to $0$; then $\int_0^x f_n (t) dt$ will be quite large for a small value of $x$, which makes $T(f_n)$ large. So, a good try is to take $f_n (t) := \sqrt{n} \mathbb{1}_{[0,1/n]} (t)$, which has unit norm. Then: $$T(f_n) (t) = \left \{ \begin{array}{ccc} \sqrt{n} & \text{if} & t \in [0,1/n] \\ 1/(\sqrt{n}t) & \text{if} & t \in [1/n,1] \end{array}\right. .$$ We compute $\|T(f_n)\|_{\mathbb{L}^2}^2 = 1+\int_{1/n}^1 1/(nt^2)dt = 2-1/n$. In addition, $(T(f_n))_{n \geq 0}$ converges almost everywhere to $0$, so any limit point of this sequence must be $0$. Since the norm of $T(f_n)$ converges to $2$, this cannot happen, so $(T(f_n))_{n \geq 0}$ has no limit point.
{ "pile_set_name": "StackExchange" }
Q: How can I hide my data folder in Android? Is there are way to hide my application's data folder in Android? I'm storing some stuff in sdcard/data/{package name} and I would like it to be private. Thanks. Update Sorry, I meant the internal memory. I'll be using it to cache some images. A: When the android security model is intact, files in your application's private storage area are only visible to your application and any other applications you have signed and assigned to share it's userid, unless you set them with world readable permission. However, you cannot rely on this because there are a significant number of devices out there where the original security model is not intact: including development devices and emulators without it turned on, devices where the model is invalidated by bugs, or devices owned by end users who have customized (ie, "rooted") the device. In these cases the application's private files will be accessible to the end user, and likely also to some add-on tools and applications on the device.
{ "pile_set_name": "StackExchange" }
Q: What Does the Heart In Gyms Mean? I have been playing Pokemon Go for a while now, and I am quite new to the new gym style. Whenever I battle another persons Pokemon, the heart inches down a little. What does it mean? A: The heart you are seeing above the Pokemon during gym battles is known as motivation. A Pokemon's motivation level determines how much "energy" it has left to fight. Once the motivation reaches zero, it gets knocked out of the gym and returns to its trainer. From the Niantic help page: Every Pokémon on a Gym has motivation, a measurement of the Pokémon’s desire to defend the location. Trainers from opposing teams battle to reduce the motivation of the Pokémon on the Gym. Pokémon gradually lose motivation over time and by losing battles against opposing team members. As a Pokémon loses motivation, its CP will temporarily decrease, making it weaker in battle. When a Pokémon’s motivation reaches zero, it leaves the Gym and returns to its Trainer the next time it loses a battle.
{ "pile_set_name": "StackExchange" }
Q: How to load shared libraries symbols for remote source level debugging with gdb and gdbserver? I've installed gdb and gdbserver on an angstrom linux ARM board (with external access), and am trying to get source level debugging of a shared library working from my local machine. Currently, if I ssh into the device, I can run gdb and I am able to get everything working, including setting a breakpoint, hitting it and doing a backtrace. My problem comes when I try and do the same using gdbserver and running gdb on my host machine in order to accomplish the same thing (eventually I'd like to get this working in eclipse, but in gdb is good enough for the moment). I notice that when I just use gdb on the server and run "info shared", it correctly loads symbol files (syms read : yes for all), which I'm then able to debug. I've had no such luck doing so remotely, using "symbol-file" or "directory" or "shared". Its obviously seeing the files, but I can't get it load any symbols, even when I specify remote files directly. Any advice on what I can try next? A: There are a few different ways for this to fail, but the typical one is for gdb to pick up local files rather than files from the server. There are also a few different ways to fix this, but the simplest by far is to do this before invoking target remote: (gdb) set sysroot remote: This tells gdb to fetch files from the remote system. If you have debug info there (which I gather from your post that you do), then it will all work fine. The typical problem with this approach is that it requires copying data from the remote. This can be a pain if you have a bad link. In this case you can keep a copy of the data locally and point sysroot at the copy. However, this requires some attention to keeping things in sync.
{ "pile_set_name": "StackExchange" }
Q: Why photoimages don't exist? I will show a reduced portion of the code that gives me a problem. _tkinter.TclError: image "pyimageN" doesn't exist - where N stays for 1, 2, 3, etc... There is a first class that shows a menu using an image in the background. class MenuWindow(): #in this class we show the main part of the program def __init__(self): self.Menu=Tk() self.MCanvas=Canvas(self.Menu) self.MCanvas.bind("<ButtonPress-1>",self.MenuClick) #unuseful lines that configure the window and the canvas# self.Background=PhotoImage(height=600,width=700)#a simple tkinter.PhotoImage object #other unuseful lines that draw the photoimage ( without reading any file, with the method put())# self.MCanvas.create_image((x,y),image=self.Background,state="normal") #unuseful lines that continue the drawing of the canvas# And a second class that shows another window, using another image in the background. This class is launched by the first class via click binding of the function self.MenuClick. class EditorWindow(): #in this class we show the main part of the program def __init__(self): self.Eenu=Tk() self.ECanvas=Canvas(self.Eenu) #unuseful lines that configure the window and the canvas# self.Background=PhotoImage(height=600,width=700) #other unuseful lines that draw the photoimage ( without reading any file , with the method put() )# self.ECanvas.create_image((x,y),image=self.Background,state="normal")#in this line i get the error #unuseful lines that continue the drawing of the canvas# The complere traceback is the following: Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 1399, in __call__ return self.func(*args) File "/Users/albertoperrella/Desktop/slay.py", line 70, in MenuClick EditorWindow(self) File "/Users/albertoperrella/Desktop/slay.py", line 85, in __init__ self.ECanvas.create_image((3,3),image=self.Background,state="normal",anchor="nw") File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2140, in create_image return self._create('image', args, kw) File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2131, in _create *(args + self._options(cnf, kw)))) _tkinter.TclError: image "pyimage2" doesn't exist The two classes are made in a similar way, so I don't know why I get the error with the second one. I am sure that it isn't a writing error e.g.(conttruct instead of construct) and that the images I am using actually exist. So I think that: I am making some concept mistakes, or it is a bug (or subtle behaviour of Tkinter) in python. A: I solved myself the problem : The second class I defined was the problem cause it used another root window, alias Tk(). An equivalent to the normal Tk() window is the Toplevel() that is the same as a root but hasn't its own interpreter context. Shortly, to solve the problem I had to change the first line of the init() method of the EditorWindow class from self.Eenu=Tk() to self.Eenu=Toplevel()
{ "pile_set_name": "StackExchange" }
Q: Intersection point of two lines in 3D I need an algorithm that returns the point of intersection between two lines. The algorithm is capable of determining the relative position then I'm sure the lines will intersect. My question is: I want to avoid linear systems in my program so I found this resolution: $$ \lambda\in{R} $$ $$ r: (x, y, z) + \lambda\vec{v}_1 $$ $$ s: (x_2, y_2, z_2) + \mu\vec{v}_2 $$ $$ \lambda = \mu \, \therefore \lambda(\vec{v}_1 \times \vec{v}_2) = ((x, y, z) - (x_2, y_2, z_2)) \times \vec{v}_2 $$ So it's just I find the value of lambda and replace the equations of lines. But I can't isolate the lambda because the equation will be a division between vectors and the resolution says "we can solve for 'a' by taking the magnitude of each side and dividing"What does that mean? I don't have native English and it was very confusing I thank if someone can explain A: You want to solve for $\lambda$ in the expression: $$\lambda(\vec{v}_1 \times \vec{v}_2) = ((x, y, z) - (x_2, y_2, z_2)) \times \vec{v}_2$$ To do that you can "take the maginitude" of the vector on the left and right hand side of the equation. Here magnitude of a 3d vector $w$ is $$|w| = \sqrt{w_1^2 + w_2^2 + w_3^2}$$ So $$|\lambda(\vec{v}_1 \times \vec{v}_2)| = |((x, y, z) - (x_2, y_2, z_2)) \times \vec{v}_2|$$ You can distribute out the $\lambda$ to find: $$|\lambda||(\vec{v}_1 \times \vec{v}_2)| = |((x, y, z) - (x_2, y_2, z_2)) \times \vec{v}_2|$$ and $$|\lambda| = \frac{|(\vec{v}_1 \times \vec{v}_2)|}{|((x, y, z) - (x_2, y_2, z_2)) \times \vec{v}_2|}$$ Note: I would suggest instead of using the above technique just looking at the ratio of an two coordinates of the vector on the LHS and RHS. i.e. when you have an equation: $$\lambda u = v$$ where $u, v$ are vectors and $\lambda$ is a constant, then $$\lambda = \frac{v_i}{u_i}$$ for any component that isn't $0$. This way you will obtain the sign of $\lambda$. The expression (written in coordinates) will probably be simpler as well.
{ "pile_set_name": "StackExchange" }
Q: How to safely execute batch file viruses for practice? I'm following a tutorial on fork bomb and thought it was pretty interesting. TL;DR: It's basically just a program that replicates itself until the computer freezes/crashes. I want to see how it actually looks like when executing but don't want to screw up my computer. What's a safe way to try out batch file viruses? A: You can run it in a virtual machine. A virtual machine emulates a computer on your computer. You can give it a limited amount of resources (CPU's, memory) and the environment on the virtual machine can not access the computer it runs on. Popular software to run virtual machines are VirtualBox and VMWare.
{ "pile_set_name": "StackExchange" }
Q: What is the ideal way to define property changes from a Model to a View in MVVM? I'm attempting to refactor some code in a MVVM architecture. The Model has public values that are changed directly. The UI listens for changes in these values. Below is the event signaling code: public string LoadFilename { get { return _loadFilename; } set { _loadFilename = value; OnPropertyChanged(); } } public string SaveFilename { get { return _saveFilename; } set { _saveFilename = value; OnPropertyChanged(); } } public string OneSafFilename { get { return _oneSafFilename; } set { _oneSafFilename = value; OnPropertyChanged(); } } public bool IsSaveEnabled { get { return _isSaveEnabled; } set { _isSaveEnabled = value; OnPropertyChanged(); } } public bool IsLoadEnabled { get { return _isLoadEnabled; } set { _isLoadEnabled = value; OnPropertyChanged(); } } public bool IsLoadCheckpointEnabled { get { return _isLoadCheckpointEnabled; } set { _isLoadCheckpointEnabled = value; OnPropertyChanged(); } } public bool IsCheckpointEnabled { get { return _isCheckpointEnabled; } set { _isCheckpointEnabled = value; OnPropertyChanged(); } } public bool IsScenariosEnabled { get { return _isScenariosEnabled; } set { _isScenariosEnabled = value; OnPropertyChanged(); } } Here is the OnPropertyChanged function: public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } This seems like a lot of boilerplate for something that should be natural in MVVM. I'd like to make it more concise, but I'm not sure where to start. With views listening to the above properties, what should the getters and setters look like? A: Implementing the INPC always remains the ugly part of WPF/XAML. With a good base class it could reduce to { get { return _loadFilename; } set { Set(ref _loadFilename, value); } } but that's about as compact as it will get. Resharper has support for (refactoring to) this. Btw, your code is also missing the optimization guard if(value != _loadFilename) . So a BindableBase base class is definitely a good idea.
{ "pile_set_name": "StackExchange" }
Q: saxon:indent-spaces attribute is being ignored In my question here I'm trying to pass in a param to my stylesheet so a user can specify the level of indentation desired. Apparently Xalan cannot read the value of a param into its indent-amount attribute, so I'm trying with this version of Saxon-HE instead. Saxon has the attribute indent-spaces which I am trying to use as follows: <xsl:stylesheet version="2.0" xmlns:saxon="http://saxon.sf.net" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- <xsl:param name="indent-spaces" select="0"/> --> <xsl:output indent="yes" method="xml" omit-xml-declaration="yes" saxon:indent-spaces="10"/><!-- Doesn't matter what I make the value of indent-spaces, the output is always indented 3 spaces --> Why is indent-spaces being ignored? A: The namespace should be xmlns:saxon="http://saxon.sf.net/" instead of xmlns:saxon="http://saxon.sf.net".
{ "pile_set_name": "StackExchange" }
Q: knockout bootstrap validation callback? I don't know where to start, but I will do my best to explain my problem. I've been working with knockout for a while now, I think 5 years, and never had to do this or something similar. Well, we have a big application and is almost finished, but we need to replace some parts of the application with KO components. In one of these components it's really important to have a data-bv-callback-callback to validate the data entered in that field, the thing is that this, is not KO compliance, and i'm not finding a way to get this working, so i need a hand. I've created a JS Fiddle, as an example (well, I took the example from the page of bootstrapvalidator). <form id="callbackForm" class="form-horizontal" data-bv-feedbackicons-valid="glyphicon glyphicon-ok" data-bv-feedbackicons-invalid="glyphicon glyphicon-remove" data-bv-feedbackicons-validating="glyphicon glyphicon-refresh"> <div class="form-group"> <label class="col-lg-3 control-label" id="captchaOperation"></label> <div class="col-lg-2"> <input type="text" class="form-control" name="captcha" data-bv-callback="true" data-bv-callback-message="Wrong answer" data-bv-callback-callback="checkCaptcha" /> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Knockout</label> <div class="col-lg-2"> <input type="text" class="form-control" data-bind="value: Value" name="knockout" data-bv-callback="true" data-bv-callback-message="Wrong answer" data-bv-callback-callback="checkCaptchaKO" /> </div> </div> </form> https://jsfiddle.net/rothariger/9hmmc3e1/ Can someone point me in the right direction? Thanks for any help. Regards. ps: I know that in the example that I passed, I could put data-bv-callback-callback="myViewModel.checkCaptchaKO", but I couldn't do that, because I'm on a component, and I don't know what's my scope. A: You can use ko.dataFor() (docs) to dynamically get the viewmodel associated with a certain element. The element that triggered the validation is passed as the third parameter to the callback. function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); }; function checkCaptcha(value, validator, $field) { var vm = ko.dataFor($field[0]); return +value === vm.captcha1 + vm.captcha2; }; $(function() { ko.applyBindings({ captcha1: randomInt(1, 10), captcha2: randomInt(1, 20), Value: ko.observable() }); $('#callbackForm').bootstrapValidator(); }); <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/css/bootstrapValidator.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script> <form id="callbackForm" class="form-horizontal" data-bv-feedbackicons-valid="glyphicon glyphicon-ok" data-bv-feedbackicons-invalid="glyphicon glyphicon-remove" data-bv-feedbackicons-validating="glyphicon glyphicon-refresh"> <div class="form-group"> <label class="col-lg-3 control-label" id="captchaOperation"> <span data-bind="text: captcha1"></span> + <span data-bind="text: captcha2"></span> = </label> <div class="col-lg-2"> <input type="text" class="form-control" data-bind="textInput: Value" name="knockout" data-bv-callback="true" data-bv-callback-message="Wrong answer" data-bv-callback-callback="checkCaptcha" /> <span data-bind="if: Value">You entered <span data-bind="text: Value"></span>.</span> </div> </div> </form> I recommend to look into knockout-validation, a knockout-aware validation framework makes more sense in this context.
{ "pile_set_name": "StackExchange" }
Q: Getting Error While deploying Spring application on Wildfly16 (Migrating from Wildfly8 to 16) I am doing migration from spring 4 to 5 and also from JDK 8 to 11 and deploying it on wildfly 16. I have build .war file with openJDK 11, and trying to deploy it on wildfly 16 but it is throwing below error stack: 13:39:12,877 {} ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 79) Context initialization failed: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonT arget(Ljava/lang/Object;)Ljava/lang/Object; at deployment.memberinfoservice.war//org.springframework.context.event.AbstractApplicationEventMulticaster.addApplicationListener(AbstractApplicationEventMulticaster.java:109) at deployment.memberinfoservice.war//org.springframework.context.support.AbstractApplicationContext.registerListeners(AbstractApplicationContext.java:825) at deployment.memberinfoservice.war//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103) at deployment.memberinfoservice.war//org.jboss.resteasy.plugins.spring.SpringContextLoaderListener.contextInitialized(SpringContextLoaderListener.java:57) at [email protected]//io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:216) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:185) at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42) at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:250) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35) at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982) at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486) at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377) at java.base/java.lang.Thread.run(Thread.java:834) at [email protected]//org.jboss.threads.JBossThread.run(JBossThread.java:485) 13:39:12,927 {} ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 79) MSC000001: Failed to start service jboss.deployment.unit."memberinfoservice.war".undertow-deployment: org.jboss.msc.service.StartException in servi ce jboss.deployment.unit."memberinfoservice.war".undertow-deployment: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object; at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:81) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35) at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982) at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486) at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377) at java.base/java.lang.Thread.run(Thread.java:834) at [email protected]//org.jboss.threads.JBossThread.run(JBossThread.java:485) Caused by: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object; at deployment.memberinfoservice.war//org.springframework.context.event.AbstractApplicationEventMulticaster.addApplicationListener(AbstractApplicationEventMulticaster.java:109) at deployment.memberinfoservice.war//org.springframework.context.support.AbstractApplicationContext.registerListeners(AbstractApplicationContext.java:825) at deployment.memberinfoservice.war//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291) at deployment.memberinfoservice.war//org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103) at deployment.memberinfoservice.war//org.jboss.resteasy.plugins.spring.SpringContextLoaderListener.contextInitialized(SpringContextLoaderListener.java:57) at [email protected]//io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:216) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:185) at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42) at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502) at [email protected]//io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:250) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96) at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78) ... 8 more 13:39:12,986 {} ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "memberinfoservice.war")]) - failure description: {"WFLYCTL0080: Fa iled services" => {"jboss.deployment.unit.\"memberinfoservice.war\".undertow-deployment" => "java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object; Caused by: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object;"}} 13:39:13,074 {} INFO [org.jboss.as.server] (ServerService Thread Pool -- 44) WFLYSRV0010: Deployed "memberinfoservice.war" (runtime-name : "memberinfoservice.war") 13:39:13,100 {} INFO [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report WFLYCTL0186: Services which failed to start: service jboss.deployment.unit."memberinfoservice.war".undertow-deployment: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lan g/Object;)Ljava/lang/Object; WFLYCTL0448: 1 additional services are down due to their dependencies being missing or failed 13:39:13,175 {} INFO [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server 13:39:13,181 {} INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management 13:39:13,183 {} INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990 13:39:13,186 {} ERROR [org.jboss.as] (Controller Boot Thread) WFLYSRV0026: WildFly Full 16.0.0.Final (WildFly Core 8.0.0.Final) started (with errors) in 19160ms - Started 460 of 725 services (3 services failed or missing depe ndencies, 414 services are lazy, passive or on-demand) It is showing that there is some class missing from spring-aop, Can anybody know how to resolve this error? <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <url>http://maven.apache.org</url> <properties> <java.version>11</java.version> <springframework.version>5.1.5.RELEASE</springframework.version> <resteasy.version>3.0.19.Final</resteasy.version> <metrics.spring.version>3.1.2</metrics.spring.version> </properties> <repository> <id>JBoss repository</id> <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> </repository> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>libs-release</name> <url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-release</url> </repository> <repository> <snapshots /> <id>snapshots</id> <name>libs-snapshot</name> <url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-snapshot</url> </repository> </repositories> <dependencies> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-core</artifactId> <version>${metrics.spring.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-annotation</artifactId> <version>${metrics.spring.version}</version> </dependency> <dependency> <groupId>com.ryantenney.metrics</groupId> <artifactId>metrics-spring</artifactId> <version>${metrics.spring.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-healthchecks</artifactId> <version>${metrics.spring.version}</version> </dependency> <dependency> <groupId>org.apache.axis</groupId> <artifactId>axis</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.xml</groupId> <artifactId>jaxrpc</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>commons-discovery</groupId> <artifactId>commons-discovery</artifactId> <version>0.2</version> </dependency> <!-- Spring dependencies start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${springframework.version}</version> </dependency> <!-- <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> --> <!-- Spring dependencies end --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.24</version> </dependency> <!-- Apache axis 2 jars start --> <dependency> <groupId>org.apache.axis2</groupId> <artifactId>axis2</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.apache.axis2</groupId> <artifactId>axis2-kernel</artifactId> <version>1.6.2</version> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.axis2</groupId> <artifactId>axis2-transport-local</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.apache.axis2</groupId> <artifactId>axis2-transport-http</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.apache.ws.commons.axiom</groupId> <artifactId>axiom-api</artifactId> <version>1.2.14</version> </dependency> <dependency> <groupId>org.apache.ws.commons.axiom</groupId> <artifactId>axiom-impl</artifactId> <version>1.2.14</version> </dependency> <dependency> <groupId>org.apache.ws.commons.schema</groupId> <artifactId>XmlSchema</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.neethi</groupId> <artifactId>neethi</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-jta_1.1_spec</artifactId> <version>1.1</version> <scope>provided</scope> </dependency> <!-- Apache axis 2 jars end --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>3.9.0.Final</version> <scope>provided</scope> <exclusions> <exclusion> <artifactId>resteasy-jaxrs</artifactId> <groupId>org.jboss.resteasy</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-multipart-provider</artifactId> <version>${resteasy.version}</version> <scope>provided</scope> </dependency> <!-- <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-spring</artifactId> <version>3.6.3.Final</version> <scope>provided</scope> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> <exclusion> <artifactId>jaxb-impl</artifactId> <groupId>com.sun.xml.bind</groupId> </exclusion> <exclusion> <artifactId>sjsxp</artifactId> <groupId>com.sun.xml.stream</groupId> </exclusion> <exclusion> <artifactId>jsr250-api</artifactId> <groupId>javax.annotation</groupId> </exclusion> <exclusion> <artifactId>activation</artifactId> <groupId>javax.activation</groupId> </exclusion> </exclusions> </dependency> --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.9</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>5.9</version> <classifier>jdk15</classifier> <scope>compile</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.googlecode.jmockit</groupId> <artifactId>jmockit</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.19</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.10</version> </dependency> <!-- <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.0.4</version> </dependency> <dependency> <groupId>com.shc.uemp</groupId> <artifactId>monitoring-framework</artifactId> <version>0.0.3.1-SNAPSHOT</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <!-- <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> --> <dependency> <groupId>javax.enterprise</groupId> <artifactId>cdi-api</artifactId> <version>1.1</version> </dependency> <!-- JDK 11 Migration --> <!-- START --> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>2.3.1</version> <type>pom</type> </dependency> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>rt</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.4.0-b180830.0438</version> </dependency> <!-- END --> </dependencies> </project> Spring dependency Hierarchy: +- com.ryantenney.metrics:metrics-spring:jar:3.1.2:compile +- org.springframework:spring-beans:jar:5.1.5.RELEASE:compile +- org.springframework:spring-jdbc:jar:5.1.5.RELEASE:compile +- org.springframework:spring-core:jar:5.1.5.RELEASE:compile | \- org.springframework:spring-jcl:jar:5.1.5.RELEASE:compile +- org.springframework:spring-context:jar:5.1.5.RELEASE:compile | \- org.springframework:spring-expression:jar:5.1.5.RELEASE:compile +- org.springframework:spring-web:jar:5.1.5.RELEASE:compile +- org.springframework:spring-tx:jar:5.1.5.RELEASE:compile +- org.springframework:spring-aspects:jar:5.1.5.RELEASE:compile | \- org.aspectj:aspectjweaver:jar:1.9.2:compile +- org.springframework:spring-context-support:jar:4.1.4.RELEASE:compile +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile | \- aopalliance:aopalliance:jar:1.0:compile A: You have mixed the version of your Spring Framework dependencies. For example, as per mvn dependency:tree output, you have spring-aop 4.1.4.RELEASE and spring-core 5.1.5.RELEASE. That won't work because 4.X is not compatible with 5.X. You must use the same version for all Spring Framework dependencies.
{ "pile_set_name": "StackExchange" }
Q: Creating a LOV of Database entries in APEX I need to make a form in APEX where you can link Contact entries from a database address table. Now I want the possibility in the form to select the contact linked from and select the contact linked to. I don't know if that's even possible to make a ListOfValue from Database entries?! Thanx for your help.. A: In the Sample Database Application, you can find examples of LOV usage: Page 7: P7_CUST_STATE, a select list where a Shared Component LOV is used Page 11: P11_CUSTOMER_ID, a popup lov where an SQL query is used
{ "pile_set_name": "StackExchange" }
Q: Laravel Form::select change background-color I have this select: {{ Form::select('set', $sets, $prod->set_id, array('class' => 'form-select', 'id' => 'sel')) }} I want to change the background-color of this select box when I choose a option. But I don't know how I can do it. Could you help me? I think that with javascript it´s possible, but... how? I have the color in my database, one color for one option. A: {{ Form::select(...., array('id' => 'sel'); }} Then just the assign your id to the onChange event in your JS: $(function(){ $('sel').change(function(e) { document.getElementById('sel').style.color="magenta"; }); });
{ "pile_set_name": "StackExchange" }
Q: What is the best way to draw this ellipse in an iPhone app? I'd like to have a similar ellipse as the Mail app in my iPhone app. A screenshot just for reference is here: http://dl-client.getdropbox.com/u/57676/screenshots/ellipse.png Ultimately I'd like the ellipse with a numerical value centered in it. Is it best to use a UIImage for this task? Perhaps less overhead to draw it with Quartz? If it's done with Quartz, can anyone display a solution for drawing it? A: Ah, a rounded rectangle. That's not too hard to draw. You can use Bezier paths to get what you want. The code looks like this: CGRect rect; CGFloat minX = CGRectGetMinX(rect), minY = CGFloatGetMinY(rect), maxX = CGFloatGetMaxX(rect), maxY = CGRectGetMaxY(rect); CGFloat radius = 3.0; // Adjust as you like CGContextBeginPath(context); CGContextMoveToPoint(context, (minX + maxX) / 2.0, minY); CGContextAddArcToPoint(context, minX, minY, minX, maxY, radius); CGContextAddArcToPoint(context, minX, maxY, maxX, maxY, radius); CGContextAddArcToPoint(context, maxX, maxY, maxX, minY, radius); CGContextAddArcToPoint(context, maxX, minY, minX, minY, radius); CGContextClosePath(context); Now that you have a path on your graphics context, you can draw it or outline it using the CGContextDrawPath and CGContextFillPath functions.
{ "pile_set_name": "StackExchange" }
Q: How to find the database exist or not with Jaydata Context I am working on an application with jaydata as ORM and angularjs as middle layer : working with jaydata how can i find with context that whether the DB has already benn created or its the first time it is been created by the code ..>??? A: You can perform this check only if you verify the number of the records in a specific table that normaly contains data.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap radio buttons awkward in column context, not lining up with other columns in row Here is a screen shot of as close as I could get with the radio buttons lining up with the other columns in a row: The issue is that the Radio buttons are not lining up horizontally (not equal space top and bottom). It isn't terrible, but it just looks awkward. It would be nice if there was some way to make the radio buttons really seem like they are a part of the form. Maybe make them bigger, take up more space in their container, and ensure that the radio buttons/labels are aligned vertically. Here is the relevant code in the form: <div class="row"> <div class="col-sm-4"> <div class='form-group'> <%= f.label :web %> <%= f.text_field :web, class: "form-control" %> </div> </div> <div class="col-sm-4"> <div class='form-group'> <%= f.label :business_contact, "Business Contact" %> <%= f.text_field :business_contact, class: "form-control" %> </div> </div> <div class="col-sm-4"> <div class='text-center'> <br> <%= f.label :gender, "Gender: " %> <%= f.radio_button :gender, 'Male', checked: (@employer.gender == 'Male' || @employer.gender == 'male'), class: "radio-inline" %> <%= f.label :male %> <%= f.radio_button :gender, 'Female', checked: (@employer.gender == 'Female' || @employer.gender == 'female'), class: "radio-inline" %> <%= f.label :female %> </div> </div> </div> A: I ended up with this and called it good: <div class="col-sm-4"> <div > <%= f.label :gender %> <br> <%= f.radio_button :gender, 'Male', checked: (@employer.gender == 'Male' || @employer.gender == 'male'), class: "radio-inline" %> <%= f.label :male %> <span> &nbsp;&nbsp;&nbsp;</span> <%= f.radio_button :gender, 'Female', checked: (@employer.gender == 'Female' || @employer.gender == 'female'), class: "radio-inline" %> <%= f.label :female %> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: PJSIP on iOS, compiler error of "undeclared type `pj_thread_t`" I had built PJSIP 2.7.1 and was integrating it for an iOS app written in Swift. Everything worked so I believed it was built the right way, all libs and headers were in the right place too, until one day I was trying to call lib functions from an external thread so I had to register this thread by using pj_thread_register() and declared a pj_thread_t type variable, the compiler started to complain about that the type pj_thread_t was undeclared. I found the pj_thread_t was declared in pj/types.h and was defined in pj/os_core_linux_kernel.c. The types.h was already included in the header search path and I supposed it should work. I guess I must have missed something here. A: I met the same problem in my Swift project. My solution is create a kind of wrapper file in ObjC. Swift and ObjC works with memory in different ways. This is why my wrapper works good. Now I can call pj_thread_t inside my wrapper file. pjsip (C) --> MyWrapper file (ObjC) --> myProject' files (Swift) MyProject-Bridging-Header.h file contain only one row: #import "MyWrapper.h"
{ "pile_set_name": "StackExchange" }
Q: Am I allowed to put single quoted, double quoted heredoc syntax or nowdoc syntax strings directly into a functions parameter that uses a string? Am I allowed to put single quoted, double quoted heredoc syntax or nowdoc syntax strings directly into functions whose parameters require a string like for example strlen('string text') or strlen("some more string text") instead of including a variable for example strlen($str);? If not why? A: You are allowed to do that unless function expects string variable to be passed by reference: // '&' means that argument is passed by reference function requestStringAsVariable(&$str) { $str = '*' . $str . '*'; } $str = 'test'; requestStringAsVariable($str); echo $str; // outputs '*test*'; requestStringAsVariable('foo'); // won't work, as function expects variable
{ "pile_set_name": "StackExchange" }
Q: What is the rationale behind allowing variable shadowing in Rust? In Rust it is encouraged to shadow variables: But wait, doesn’t the program already have a variable named guess? It does, but Rust allows us to shadow the previous value of guess with a new one. Won't this feature just introduce problems like: hard to follow code (easier to create bugs) accessing variables when one intended to access a different variable (creates bugs) I have based this information from my own experience and the following sources: 1 2 3 4 5 What are the underlying reasons behind the decision to include variable shadowing? It does have it advantages as to just create guess and not guess_str vs guess_int. There are both advantages and disadvantages. What convinced the inventors of Rust that the advantages are greater than the disadvantages? The programming world seems divided about this; some languages only issue warnings and discourage shadowing, some languages disallow it explicitly, some allow it and others even encourage it. What is the reasoning? If possible I'd like to understand more, and a complete answer would possibly include: What kind of advantages/disadvantages are there? What are the use cases for shadow variables? When not to use them in Rust? What do different people from different programming background have to keep in mind? (and which pitfalls not to fall into) A: Because it was initially supported and never removed: It’s more like we never forbade shadowing, since it just fell out of the implementation of the compiler. As I recall, Graydon floated the idea of forbidding shadowing, but I stuck up for the feature, nobody else really cared, and so it stayed. - pcwalton See also: RFC 459: Disallow type/lifetime parameter shadowing What does 'let x = x' do in Rust? Why do I need rebinding/shadowing when I can have mutable variable binding? In Rust, what's the difference between "shadowing" and "mutability"?
{ "pile_set_name": "StackExchange" }
Q: Find Nodes NOT MATCHed by a Query I run a Cypher query and update labels of the nodes matching a certain criteria. I also want to update nodes that do not pass that criteria in the same query, before I update the matched ones. Is there a construct in Cypher that can help me achieve this? Here is a concrete formulation. I have a pool of labels from which I choose and assign to nodes. When I run a certain query, I assign one of those labels, l, to the nodes returned under the conditions specified by WHERE clause in the query. However, l could have been assigned to other nodes previously, and I want to rid all those nodes of l which are not the result of this query. The conditions in WHERE clause could be arbitrary; hence simple negation would probably not work. An example code is as follows: MATCH (v) WHERE <some set of conditions> // here I want to remove 'l' from the nodes // not satisfied by the above condition SET v:l I have solved this problem by using a temporary label through this process: Assign x to v. Remove l from all nodes. Assign l to all nodes containing x. Removing x from all nodes. Is there a better way to achieve this in Cypher? A: This seems like one reasonable solution: MATCH (v) WITH REDUCE(s = {a:[], d:[]}, x IN COLLECT(v) | CASE WHEN <some set of conditions> AND NOT('l' IN LABELS(x)) THEN {a: s.a+x, d: s.d} WHEN 'l' IN LABELS(x) THEN {a: s.a, d: s.d+x} END) AS actions FOREACH (a IN actions.a | SET a:l) FOREACH (d IN actions.d | REMOVE d:l) The above query tests every node, and remembers in the actions.a list the nodes that need the l label but do not yet have it, and in the actions.d list the nodes that have the label but should not. Then it performs the appropriate action for each list, without updating any nodes that are already OK.
{ "pile_set_name": "StackExchange" }
Q: Fitting a dose response curve to 3 dose points I have dose-response data sets, of 3 doses, 3 replicates for each dose. I'd like to fit a curve for these data sets and I'm mainly interested in the slope of the curve since I want to be able and distinguish cases such as these two: df.1 <- data.frame(dose = c(10,0.625,2.5,10,0.625,2.5,10,0.625,2.5), response = c(61.408107781412,98.3181200924209,92.6050821600725,19.1515147744906,97.7336163702194,75.7946981922533,82.0473297811668,76.5281098812883,103.062728539761), stringsAsFactors=F) which when plotted: plot(log(df.1$dose),df.1$response), looks like: df.2 <- data.frame(dose = c(10,0.625,2.5,10,0.625,2.5,10,0.625,2.5), response = c(70.1978323700685,77.9487655135013,76.669278705336,27.3732511270187,127.028568421247,67.6604871443974,81.3663399111724,47.0441937203051,85.6920201048891), stringsAsFactors = F) which when plotted: plot(log(df.2$dose),df.2$response) looks like: I tried using the LL.4 model implemented in R's drc package, using the drm function, however the results I get are a bit confusing. For the first data set: fit.1 <- drm(response~dose,data=df.1,fct=LL.4(names=c("slope","low","high","ED50"))) plot(fit.1) gives: and: > summary(fit.1) Model fitted: Log-logistic (ED50 as parameter) (4 parms) Parameter estimates: Estimate Std. Error t-value p-value slope:(Intercept) 3.7577e+00 4.5689e+01 8.2247e-02 0.9376 low:(Intercept) 1.7206e+01 2.0485e+03 8.3995e-03 0.9936 high:(Intercept) 9.0872e+01 1.3778e+01 6.5955e+00 0.0012 ED50:(Intercept) 1.0025e+01 1.4769e+02 6.7877e-02 0.9485 Residual standard error: 23.4205 (5 degrees of freedom) For the second data set: fit.2 <- drm(response~dose,data=df.2,fct=LL.4(names=c("slope","low","high","ED50"))) plot(fit.2) gives: and: > summary(fit.2) Model fitted: Log-logistic (ED50 as parameter) (4 parms) Parameter estimates: Estimate Std. Error t-value p-value slope:(Intercept) -1.0662 NA NA NA low:(Intercept) 86.6585 NA NA NA high:(Intercept) 32.1951 NA NA NA ED50:(Intercept) 10.1519 NA NA NA Residual standard error: 31.75223 (5 degrees of freedom) Warning message: In sqrt(diag(varMat)) : NaNs produced I'd expect the slopes to have the same sign for both data sets but I guess given the low quality of my data a sigmoidal curve is not the way to go. So my question is what is a reasonable model, preferably in R, to fit to such data to get an estimate for the slope. A: A general comment first. You are trying to obtain an estimate from data that contain almost no information relevant to that estimate. There is almost no dose-response relationship in your data, perhaps because your drug does nothing, because the lowest dose is large enough to have the maximal effect, or because the highest dose is only just enough to start to produce a response. Fitting a sigmoid dose-response relationship to those data is entirely pointless. If you really need to know about the slope (usually we care more about the ED50 and range than the slope), you will need to run another set of experiments that yield data with a wider range of doses. If the dose-response relationship is not obvious in the data then fitting a model will yield nonsense estimates. Now, comments with respect to the process of dose-response curve fitting. The models you fitted have parameters for the (mid-point) slope, for the upper plateau, for the lower plateau, and for the mid-point along the x-axis. Four parameters. Assuming your data are for a downwards-going response (i.e. your drug inhibits the response being measured) then you $might$ be able to assume that the upper plateau (the response values at doses of your drug too low to do anything) is at 100%, but you do not give enough information about the responses to know if that is appropriate. If you assume the upper plateau should be at 100 then you can substitute a fixed value of 100 for the upper plateau parameter. That reduces the amount of estimation that the curve fitting process has to achieve. The output of the curve fitting routine fit.2 contains a warning that you should not ignore. I don't know exactly what it means, but I would be surprised if it was not related to the curve fit routine failing to converge on a locally optimal solution. Given that the curve fitting was done without information about the location of the lower plateau (I note that for fit.1 the estimated standard error on the estimate of the lower plateau is orders of magnitude greater than the estimate: a very bad sign), and given that the curve fitting routine probably failed to converge on a solution, it is inappropriate to place any value on the slope estimate.
{ "pile_set_name": "StackExchange" }
Q: Scraping multiple lists from a website. I'm currently working on a web scraper for a website that displays a table of data. The problem I'm running into is that the website doesn't sort my searches by state on the first search. I have to do it though the drop down menu on the second page when it loads. The way I load the first page is with what I believe to be a WebClient POST request. I get the proper html response and can parse though it, but I want to load the more filtered search, but the html I get back is incorrect when I compare it to the html I see in the chrome developers tab. Here's my code // The website I'm looking at. public string url = "https://www.missingmoney.com/Main/Search.cfm"; // The POST requests for the working search, but doesn't filter by states public string myPara1 = "hJava=Y&SearchFirstName=Jacob&SearchLastName=Smith&HomeState=MN&frontpage=1&GO.x=19&GO.y=18&GO=Go"; // The POST request that also filters by state, but doesn't return the correct html that I would need to parse public string myPara2 = "hJava=Y&SearchLocation=1&SearchFirstName=Jacob&SearchMiddleName=&SearchLastName=Smith&SearchCity=&SearchStateID=MN&GO.x=17&GO.y=14&GO=Go"; // I save the two html responses in these public string htmlResult1; public string htmlResult2; public void LoadHtml(string firstName, string lastName) { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; htmlResult1 = client.UploadString(url, myPara1); htmlResult2 = client.UploadString(url, myPara2); } } Just trying to figure out why the first time I pass in my parameters it works and when I do it in the second one it doesn't. Thank you for the time you spent looking at this!!! A: I simply forgot to add the cookie to the new search. Using google chrome or fiddler you can see the web traffic. All I needed to do was add client.Headers.Add(HttpRequestHeader.Cookie, "cookie"); to my code right before it uploaded it. Doing so gave me the right html response and I can now parse though my data. @derloopkat pointed it out, credits to that individual!!!
{ "pile_set_name": "StackExchange" }
Q: I flagged a comment that was claiming an answer is not an answer when it was, but the flag was declined The most recent comment on my answer says my answer is not an answer, just information. I admit it contains primarily information, but at the end I do provide a solution, albeit--as my answer is meant to suggest--one I don't think should be used. So I flagged it, and the flag was declined. Did I just use the wrong flag option, or should I have not bothered flagging the comment at all? A: For the record, the comment was: not a solution. just information. As long as comments aren't abusive, there's no reason to flag them. I don't see this as abuse; the user is merely expressing their opinion. The correct way to handle an answer that you really feel is not an answer is to do any combination of the following: downvote; comment; if you feel strongly that it's obviously not an answer then flag the answer. Just commenting isn't likely to cause anything to happen, so you'd only comment if you don't really care if anything happens. Comments are "ephemeral"; they can be cleaned up, deleted at any time, for any reason by a mod, even if the comments are constructive and helpful (just to reduce the noise on an answer, for instance). Comments are designed to be a "temporary work area" where people can collaborate on how to improve a question/answer. They only deserve speedy and prioritized deletion if they are somehow harming the site. Obviously the mod disagreed with the comment that your answer is not an answer, or the mod would've deleted your answer when reviewing the whole situation. I assume they didn't delete the comment because the user has the right to their opinion, and the comments on your answer aren't noisy enough to warrant speedy deletion. In conclusion, should I have not bothered flagging the comment at all? Yes, you should not have bothered. But don't worry about one single flag decline, as it really doesn't make a dent. On the other hand, getting flags declined on a regular basis (with a very small percentage of helpful flags) is bad for your ability to conveniently reach mods, because users with a large percentage of declined flags have their flags "de-prioritized" (as I understand it) somehow indicating to mods that they're likely bogus. I imagine extreme abusers of the flag system are either suspended/banned or their flags are ignored entirely.
{ "pile_set_name": "StackExchange" }
Q: How to compare event and HTML tag in Javascript I'm trying to compare these codes to boolean value. HTML <a href="#" id="like"> <i class="fa fa-thumbs-o-up fa-fw"></i> </a> jQuery $('#like').on('click', function(event) { ... var htmlTag = '<i class="fa fa-thumbs-o-up fa-fw"></i>'; var isLike = event.target.closest('#like').innerHTML == htmlTag; if (isLike) { console.log('true'); } else { console.log('false'); } ... }); But it's going to false, In fact it should be true. Why? Thanks for every answers. A: You should use .html() method in order to return the html of hyperlink. $('#like').on('click', function(event) { var htmlTag = 'Like<i class="fa fa-thumbs-o-up fa-fw"></i>'; var isLike = $(this).html().trim() == htmlTag; if (isLike) { console.log('true'); } else { console.log('false'); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="like"> Like<i class="fa fa-thumbs-o-up fa-fw"></i> </a>
{ "pile_set_name": "StackExchange" }
Q: Java overriding equals, array Here's a code I'm working on, overriding equals. I've not tried compiling, but Netbeans is giving me a warning saying .equals on incompatible types. public class Customers { private String name; public Customers(name) { this.name = name; } public boolean equals(String name) { return (this.name.equals(name)); } } Main Class public class TestCustomers { public static void main(String args[]) { Customers cus = new Customers[1]; cus[1] = new Customers("John"); if(cus[1].equals("John") ... } } This works fine without using Array. But with array, it shows me a warning. Why does it gives me a warning saying that .equals on incompatible types? Has this got to do with because of Type Erasures in Array? A: The complaint may be because public boolean equals(String name) doesn't really override the Object.equals-method, since Objects.equals takes an Object as argument, and not a String. (This would probably be evident if you took the habit of explicitly writing @Override in front of the methods you intended to override other methods.) Saying that a Customer can equal anything but a Customer seems like a really bad idea to me though. I would do something like this: class Customer { private String name; public Customer(String name) { this.name = String.valueOf(name); } public String getName() { return name; } @Override public boolean equals(Object o) { return (o instanceof Customer) && ((Customer) o).name.equals(name); } @Override public int hashCode() { return name.hashCode(); } } And the main class: public class Main { public static void main(String args[]) { Customer[] cus = new Customer[1]; cus[0] = new Customer("John"); // Compare against name if (cus[0].getName().equals("John")) System.out.println("Name equals."); // Compare against another customer: if (cus[0].equals(new Customer("John"))) System.out.println("Customer equals."); } }
{ "pile_set_name": "StackExchange" }
Q: how to have same size ratio of circle between different screen resolution in flutter I tried to make a custom geofencing, to do this, I display an Url of googlemap and I add a stack with a circle, I had adjust the size with a coefficient to have the good representation. problem my coefficient isn't dynamic with any screen device Container ( padding: const EdgeInsets.only(top :160.0), child : new Card( elevation: 2.0, child: new Stack( alignment: AlignmentDirectional.center, children: <Widget>[ new Container( child: new Image.network(statichomeMapUri.toString()), ), FractionalTranslation( translation: Offset(0.0, 0.0), child: new Container( alignment: new FractionalOffset(0.0, 0.0), decoration: new BoxDecoration( border: new Border.all( color: Colors.orangeAccent.withOpacity(0.5), width: perimetre/3.4, // need to be dynamic ), shape: BoxShape.circle, ), ), ), new Container( //padding: const EdgeInsets.only(bottom:10.0), margin: new EdgeInsets.all(140.0), child : Icon(Icons.home, color: Colors.white, size: 25.0), ), ], ), ), ) A: Get width of the mobile screen using MediaQuery.of(context).size.width And set whatever ratio you want to set
{ "pile_set_name": "StackExchange" }
Q: How do I check the number of tasks currently in the queue? According to the Push queue in GAE there are a number of task request headers. X-AppEngine-QueueName, the name of the queue (possibly default) X-AppEngine-TaskName, the name of the task, or a system-generated unique ID if no name was specified X-AppEngine-TaskRetryCount, the number of times this task has been retried; for the first attempt, this value is 0. This number includes attempts where the task failed due to a lack of available instances and never reached the execution phase. X-AppEngine-TaskExecutionCount, the number of times this task has previously failed during the execution phase. This number does not include failures due to a lack of available instances. X-AppEngine-TaskETA, the target execution time of the task, specified in milliseconds since January 1st 1970. Is there a way to check how many tasks are already enqueued? A: Not from the headers, no. But you can use the QueueStatistics class to query that information.
{ "pile_set_name": "StackExchange" }
Q: Sympy: Specify derivative for function I would like to specify the derivative of a function that is also a function. Is there a way how to do this in sympy? An example how it could look like: import sympy as sp x, y = sp.symbols('x, y') fun = sp.Function("myfun")(x, y) fun.derivative = sp.Function("myfun_derivative")(x,y) My use case is that I want to use afterwards the sympy codegen and specify for "myfun" and for "myfun_derivative" standard methods which use numpy, because they are complex and take a long time to handle for sympy. UPDATE Solution: import sympy as sp x, y = sp.symbols('x, y') class myfun(sp.Function): def fdiff(self, argindex = 1): return sp.Function("myfun_derivative")(x, y, argindex) A: A function and derivative are just expressions so you are free to define them as you wish: >>> from sympy.abc import x >>> f = x**2 >>> df = 2*x So now f and df represent your function and derivative. You could also define an object that returns these values upon initiation and differentiation: In [10]: class myf(Function): ...: def fdiff(self, i): ...: assert i == 1 ...: return 2*x ...: def __new__(self): ...: return x**2 ...: In [11]: myf() Out[11]: 2 x In [12]: myf().diff() Out[12]: 2·x
{ "pile_set_name": "StackExchange" }
Q: Add and remove event handler via reflection c# Good day! My purpose is to implement class which will allow us subscribe and unsubscribe objects to(from) events. Here is the code of my class. public static class EventSubscriber { public static void AddEventHandler(EventInfo eventInfo, object item, Action action) { var parameters = GetParameters(eventInfo); var handler = GetHandler(eventInfo, action, parameters); eventInfo.AddEventHandler(item, handler); } public static void RemoveEventHandler(EventInfo eventInfo, object item, Action action) { var parameters = GetParameters(eventInfo); var handler = GetHandler(eventInfo, action, parameters); eventInfo.RemoveEventHandler(item, handler); } private static ParameterExpression[] GetParameters(EventInfo eventInfo) { return eventInfo.EventHandlerType .GetMethod("Invoke") .GetParameters() .Select(parameter => Expression.Parameter(parameter.ParameterType)) .ToArray(); } private static Delegate GetHandler(EventInfo eventInfo, Action action, ParameterExpression[] parameters) { return Expression.Lambda( eventInfo.EventHandlerType, Expression.Call(Expression.Constant(action), "Invoke", Type.EmptyTypes), parameters) .Compile(); } } As you can see here are 2 public methods which actually subscribe and unsubscribe objects to(from) event. And here is the sample how I test it class Program { static void Main() { Test test = new Test(); test.SubscribeTimer(); while (true) { if(test.a == 10) { break; } } test.UnsubscribeTimer(); while (true) { } } } class Test { System.Timers.Timer timer; public int a = 0; public Test() { timer = new System.Timers.Timer(1000); timer.Start(); } public void SubscribeTimer() { var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed"); EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed); EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerNotElapsed); } public void UnsubscribeTimer() { var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed"); EventSubscriber.AddEventHandler(eventInfo, timer, TimerNotElapsed); EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerElapsed); } public void TimerElapsed() { Console.WriteLine("timer elapsed"); a++; } public void TimerNotElapsed() { Console.WriteLine("timer not elapsed"); a++; } } The expected behaviour of sample is that on the begining we will see the message "timer elapsed" every second, after 10-th second we should see only "timer not elapsed" and we do, but we still see "timer elapsed" too. This means that AddEventHandler method works, but RemoveEventHandler method doesn't. I would be very happy if you will help me. Thanks in advance. A: I think it's because you are creating a new handler each time: (which doesn't match the previous handler, so can't be removed from the invocation list) public static void RemoveEventHandler(EventInfo eventInfo, object item, Action action) { var parameters = GetParameters(eventInfo); var handler = GetHandler(eventInfo, action, parameters); // <-- eventInfo.RemoveEventHandler(item, handler); } Why are you wrapping the Action? To lose the parameters? It is not possible to add/remove the eventInfo.RemoveEventHandler(item, action); because of the parameters. If you want to remove a newly generated handler, you should return that handler when you want to remove it. public static Delegate AddEventHandler(EventInfo eventInfo, object item, Action action) { var parameters = GetParameters(eventInfo); var handler = GetHandler(eventInfo, action, parameters); eventInfo.AddEventHandler(item, handler); return handler; } public static void RemoveEventHandler(EventInfo eventInfo, object item, Delegate handler) { eventInfo.RemoveEventHandler(item, handler); } var handler = EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed); EventSubscriber.RemoveEventHandler(eventInfo, timer, handler);
{ "pile_set_name": "StackExchange" }
Q: Merge polygons in CartoDB? I created this map in cartodb: http://cdb.io/1xBj4Xo Now I have to merge some of the districts to a bigger district. Is it possible to do this in Cartodb? Using a SQL query for instance? I can also provide a .csv-file: http://tradukt.ch/owncloud/public.php?service=files&t=2fe413428dd38103705fa4191236b8fc Screenshot of the table: A: Based on your CSV, Tablename: Wahlkreise Column containing value to union on: wahlkreis Other Columns use an aggregate function to grab one of the values (all of them are the same for each district / wahlkreis In the SQL window in CartoDB, type: SELECT wahlkreis , cartodb_id , max(strong_party) as strong_party , max(einwohner) as einwohner , max(mandate) as mandate , max(kandidaten) as kandidaten , max(frauen) as frauen , max(maenner) as maenner , max(fdp) as fdp , max(svp) as svp , max(sp) as sp , max(glp) as glp , max(gruene) as gruene , max(evp) as evp , max(cvp) as cvp , max(bdp) as bdp , st_union(the_geom_webmercator) as the_geom_webmercator FROM wahlkreise_bl_1 group by wahlkreis, wahlkreise_bl_1.cartodb_id At this point, map interaction must be enabled by adding the CartoDB_id to the SQL and GROUP BY clause, but there seems to be a bug that removes the st_union function from working properly (I will keep digging in). The workflow instead could be to simply use the 'create table from query' option to write your query to a new file, and you can take advantage of the full interactivity based on your SQL processing.
{ "pile_set_name": "StackExchange" }
Q: JavaScript prototypes equivalance for functions I am reading JavaScript: Good parts by Douglas Crockford. I came across this following useful trick. Function.prototype.method = function (name, func) { if (!this.prototype[name]) { this.prototype[name] = func; } }; Based on the above code snippet, what I understood is, as all functions are objects of Function and as the above function adds the 'method' method to prototype of Function, there will be a method method available on all functions. var pfun = function(name){ this.name = name; }; Consider the following log statements console.log(Function.prototype.isPrototypeOf(pfun));//true - Thats fine console.log(pfun.prototype == Function.prototype);//false - why? I couldn't understand why the above logs contradict each other. Here pfun is a functions which has the method method available from its prototype. So I can call the following. pfun.method("greet",function(){ console.log(this.name); }); Now as method method runs, it adds the greet method to pfun's prototype. If the above logs doesn't contradict each other, then greet method should be available to all functions. My question is, why the above logs are contradicting each other? A: isPrototypeOf checks to see if an object is referenced by the internal [[Prototype]] property of another object. All ECMAScript native functions inherit from Function.prototype therefore: Function.prototype.isPrototypeOf(pfun)) returns true. Every native function created by the Function constructor has a default public prototype property that is a plain object (see ECMAScript §13.2 #16). So when you do: pfun.prototype == Function.prototype you are comparing this plain object to Function.prototype1, which are different objects. This confusion is brought about in discussion because the public and private prototype properties are often only distinguished by the context in which the term is used. All native Functions have both, and only for the Function constructor are they the same object by default, i.e. Object.getPrototypeOf(Function) === Function.prototype returns true. This relationship can be established for other Objects, but it doesn't happen by default (and I can't think of an example or sensible reason to do it). 1 The Function.prototype object is a bit of an oddity. It has an internal [[Class]] value of "function" and is callable, so in that regard it's a function. However, its internal [[Prototype]] is Object.prototype, so it can probably be called an instance of Object. When called, it ignores all arguments and returns undefined.
{ "pile_set_name": "StackExchange" }
Q: When it is necessary to close a file and when it is not in python? I was trying to write code that manages resources in a responsible way. I understand that a common idiom to make sure a file is closed after using is with open("filename.txt", 'r') as f: # ...use file `f`... However, I often see people do the following: data = cPickle.load(open("filename.pkl", 'r')) I am wondering is that a right way and does Python always close filename.pkl even if cPickle throws an exception? Some explanation (or pointers to articles that explains) whether that is safe? A: Python doesn't close the file when you open it.thus when you pass it in following code without wrapping the script by with statement : data = cPickle.load(open("filename.pkl", 'r')) You need to close if manually. This is a example form python documentation about pickle module : import pprint, pickle pkl_file = open('data.pkl', 'rb') data1 = pickle.load(pkl_file) pprint.pprint(data1) data2 = pickle.load(pkl_file) pprint.pprint(data2) pkl_file.close() As you can see the file has been closed at the end of code! Also for more info you read the following python documentation about closing a file : When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail. >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: I/O operation on closed file It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks: >>> >>> with open('workfile', 'r') as f: ... read_data = f.read() >>> f.closed True
{ "pile_set_name": "StackExchange" }
Q: How to force culture/region on RegionInfo.DisplayName I'm displaying a country as part of some other information. The country is read out of a database as a country code. This is done like so: Location location = new Location() { Company = reader.GetString("Company"), Address1 = reader.GetString("Address"), Address2 = reader.GetString("Address2", string.Empty), ZipCity = reader.GetString("ZipCity"), Country = new RegionInfo(reader.GetString("Country", string.Empty)).DisplayName, CountryCode = new RegionInfo(reader.GetString("Country", string.Empty)).TwoLetterISORegionName, Att = reader.GetString("Att", string.Empty), Phone = reader.GetString("Phone", string.Empty) }; My problem is that I would really like to force the display name to be in danish. Mind you, the country will now always be denmark, so using native name is not an option. Thank you very much in advance A: So after checking into the possibility of installing a language pack for the .NET Framework, which for some reason wasn't possible for us, we found the following solution. Add this line to your web.config under the system.web node. <globalization enableClientBasedCulture="false" culture="da-DK" uiCulture="da"/> If you have a OS language pack installed on the machine running your software, it will now be forced to that language.
{ "pile_set_name": "StackExchange" }
Q: Problema con procesos y reserva de memoria Tengo el siguiente ejercicio: Realice un programa que expanda N procesos hijos. Cada hijo debe compartir una variable denominada contador, que debe estar inicializada a cero. Esta variable debe ser incrementada por cada hilo 100 veces. Imprima la variable una vez finalicen los hilos y analice el resultado obtenido. Un resultado previsible para 3 procesos sería 300. Tengo el siguiente codigo pero no consigo que me realize correctamente la suma, creo que el problema esta en la reserva de memoria. #define CHILDREN 3 #define OK 7 int suma; void adder(int); int main() { int i,j, shmid, status; key_t key; extern int suma ; struct shmid_ds buf; // Shared memory key = ftok("adicional2.c", 1); if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) == -1){ exit(1); } suma=(int) shmat(shmid,NULL,0); suma=0; // creacion hilos for (i = 0; i < CHILDREN; i++) { pid_t pid = fork(); if (pid==0) {//cuando fork es igual de 0 adder(i); printf("%d",suma); exit(0); } } // Wait to finish for (i = 0; i < CHILDREN; i++) { pid_t pid = wait(&status); printf("\nHijo %d ha terminado status %d\n", pid, WEXITSTATUS(status)); } // Final result printf("\nSuma"); printf("[%d]",suma); printf("\n"); } void adder(int id) { int i,shmid; extern int suma ; key_t key; // Shared memory key = ftok("adicional2.c", 1); if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) == -1) perror("Child"); //Creacion de hilos if(id==0){//proceso 1 fila 1 suma+=100; printf("suma hijo 1= %d",suma); exit(OK); } if(id==1){//proceso 2 fila 2{ suma+=100; printf("suma hijo 2=%d",suma); exit(OK); } if(id==2){ //proceso 3 fila 3{ suma+=100; printf("suma hijo 3=%d",suma); exit(OK); } } Como digo creo que el fallo es de la reserva de memoria, ya que cada hijo me devuelve 100 pero no lo suma con el anterior. A: Tienes varios fallos: No necesitas ninguna variable global en tu programa. Tanto main() como adder() (y por tanto cada uno de los hijos) tienen su propia variable suma. Ahora bien, esas variables no son de tipo int, sino puntero a int y lo que hay que hacer para que compartan el dato es hacer que todas ellas apunten a una misma dirección de memoria física. Ya que cada proceso tiene su propio espacio de direcciones virtuales, es imposible hacer que un puntero en un proceso apunte a una variable en otro proceso. ¿Cómo hacerlo entonces? Pues precisamente gracias a shmget(), que crea una zona de memoria en el sistema que luego pueda ser compartida entre procesos. Una vez creada esa zona, quien la creó recibe un identificador entero (shmid) que debe usarse para, mediante shmat(), obtener un puntero (en el espacio virtual del proceso que lo obtiene) que apunte a la zona compartida en el sistema. Es como una "ventanita" en el espacio de direcciones virtuales de cada proceso que permite "asomarse" a la memoria del sistema. Las "ventanitas" de todos los procesos se asoman al mismo trozo de memoria del sistema y así lo comparten, pero ha de ser a través de punteros. Esto implica que cada hijo debe conocer el valor de shmid para poder mapearlo en su propio espacio de direcciones. Una forma sencilla es pasarle ese valor como parámetro (aunque sólo el padre lo crea). Por tanto sobra la parte en que llamas a shmget() desde los hijos. Éstos sólo deben hacer shmap(), sobre el shmid que les pasa el padre. Cada hijo debe incrementar la suma 100 veces. Imagino que eso quiere decir dentro de un bucle que se repita 100 veces, y no sumando 100 como tú has hecho. El código de los tres hijos es idéntico, por tanto no veo la necesidad de hacer un if para distinguir cuál de los hijos es. Se puede simplificar por tanto su código. Hay un fallo adicional relacionado con la concurrencia, pero de momento no voy a entrar en él. Con todo lo antes dicho el programa quedaría así: #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include<stdio.h> #define CHILDREN 3 #define OK 7 void adder(int,int); // Desaparece la variable suma global int main() { int i,j, shmid, status; key_t key; int *suma ; // La suma en el padre es un puntero struct shmid_ds buf; // El padre crea la zona de memoria compartida en el sistema key = ftok("adicional2.c", 1); if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) == -1){ exit(1); } // Pero debe mapearla en su propio espacio de direcciones suma=(int *) shmat(shmid,NULL,0); // Ahora ya podemos ponerla a cero, pero recuerda que es un puntero *suma=0; // creacion hilos for (i = 0; i < CHILDREN; i++) { pid_t pid = fork(); if (pid==0) {//cuando fork es igual de 0 // Esto lo hará cada hijo adder(shmid, i); // Le pasamos el id de la zona compartida exit(0); // y termina aqui } } // Esperar a que los tres hijos acaben for (i = 0; i < CHILDREN; i++) { pid_t pid = wait(&status); printf("\nHijo %d ha terminado status %d\n", pid, WEXITSTATUS(status)); } // Imprimir resultado final, recordemos que es puntero printf("\nSuma [%d]\n",*suma); } // Esta es la función que ejecutará cada hijo void adder(int shmid, int id) { // Cada hijo tiene su propio puntero a la zona compartida int *suma ; // que hay que mapear al espacio de direcciones del hijo suma=(int *) shmat(shmid,NULL,0); // Ahora el bucle que incrementa 100 veces la suma for (int i=0; i<100; i++ ) { *suma+=1; } // Este hijo imprime su resultado printf("suma hijo %d= %d\n",id, *suma); // exit(OK); // sobraba este exit, pues ya se hace luego en main } Si compilas y ejecutas este programa verás: suma hijo 0= 100 suma hijo 1= 200 Hijo 19226 ha terminado status 0 Hijo 19227 ha terminado status 0 suma hijo 2= 300 Hijo 19228 ha terminado status 0 Suma [300] Por tanto ha funcionado. Sin embargo si lo ejecutas millones de veces, encontrarás algunas en las que el resultado no es 300. Esto puede pasar porque los tres hijos se están ejecutando a la vez y modificando a la vez la misma zona de la memoria, pero la operación: *suma += 1 no es "atómica" (no tiene lugar en una sola instrucción, aunque en C sea una sola línea). Su ejecución se parece más bien a esto otro: int temporal; temporal = *suma; temporal = temporal + 1; *suma = temporal; por tanto podría darse el caso de que un hijo lea *suma, encontrando por ejemplo 10, y mientras le está sumando 1 a su temporal, otro hijo lea también *suma y encuentre todavía 10. Ambos hijos llegarán al resultado 11, y lo guardarán (primero uno y después el otro) en la zona compartida, con lo que en lugar de incrementarse en dos, se habrá incrementado sólo en 1. Esto es improbable, pero puede ocurrir. Y por tanto técnicamente el programa es incorrecto. Arreglarlo implica usar semáforos o cerrojos, que son otro tipo de objeto compartido gestionado por el operativo y que sirve para que los hijos puedan coordinarse. Un hijo solicita el cerrojo, y mientras incrementa su variable ningún otro hijo podrá hacerlo porque cuando vayan a solicitar el cerrojo éste estará ocupado y permanecerán a la espera hasta obtenerlo. Una vez el incremento ha terminado, el hilo libera el cerrojo, permitiendo de ese modo que otro hilo pueda avanzar. Ese cerrojo por tanto permite que los hijos entren "por turnos" a la instrucción *suma+=1. Te dejo como ejercicio esta parte de los cerrojos (lee sobre flock()) o semáforos (lee sobre sem_init(), sem_wait() y sem_post().
{ "pile_set_name": "StackExchange" }