{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n\nnpm\nnpm install bootstrap@3\n\nrequire('bootstrap') will load all of Bootstrap's jQuery plugins onto the jQuery object. The bootstrap module itself does not export anything. You can manually load Bootstrap's jQuery plugins individually by loading the /js/*.js files under the package's top-level directory.\nBootstrap's package.json contains some additional metadata under the following keys:\nless - path to Bootstrap's main Less source file\nstyle - path to Bootstrap's non-minified CSS that's been precompiled using the default settings (no customization)\n\nA: npm install --save bootstrap\n\nafter this import this in App.js\nimport 'bootstrap/dist/css/bootstrap.min.css';\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 236,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845162\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44480910\"\n}"}}},{"rowIdx":1705658,"cells":{"id":{"kind":"string","value":"7d3cf23dbdf8552332c319c9efb48b677c264e9b"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Listening to menu opening I have a RelativeLayout. In that I create several ToggleButton views. The user can set those ToggleButtons on and off. \nWhen the user opens the Activity's OptionMenu I want all those ToggleButtons to become OFF. To do this I am setting programmatically the ToggleButtons to OFF in the onPrepareOptionsMenu code. \nI have also a PopupMenu registered to a Imagebutton. I want also when the users opens the PopupMenu by clicking the Imagebutton all the ToggleButtons to become OFF. So, I am turning the togglebuttons to off in the Imagebutton's setOnClickListener code.\nMy issue is that the updates to the Togglebuttons' state (to Off) are shown only after the OptionsMenu or the PopupMenu is closed. Instead I want all the ToggleButtons become Off as soon the user opens the menus. I thought I have to use some OnFocusChangeListener on some view. I tried to use it on the Activity's top layout but it doesn't work. \nHow could I get the result I want?\n\nA: I found the solution myself by overriding the onWindowFocusChanged method, like this:\n@Override\npublic void onWindowFocusChanged(boolean hasFocus) {\n if (!hasFocus) {\n //code to turn off togglebuttons goes here \n }\n}\n\n"},"original_text":{"kind":"string","value":"Q: Listening to menu opening I have a RelativeLayout. In that I create several ToggleButton views. The user can set those ToggleButtons on and off. \nWhen the user opens the Activity's OptionMenu I want all those ToggleButtons to become OFF. To do this I am setting programmatically the ToggleButtons to OFF in the onPrepareOptionsMenu code. \nI have also a PopupMenu registered to a Imagebutton. I want also when the users opens the PopupMenu by clicking the Imagebutton all the ToggleButtons to become OFF. So, I am turning the togglebuttons to off in the Imagebutton's setOnClickListener code.\nMy issue is that the updates to the Togglebuttons' state (to Off) are shown only after the OptionsMenu or the PopupMenu is closed. Instead I want all the ToggleButtons become Off as soon the user opens the menus. I thought I have to use some OnFocusChangeListener on some view. I tried to use it on the Activity's top layout but it doesn't work. \nHow could I get the result I want?\n\nA: I found the solution myself by overriding the onWindowFocusChanged method, like this:\n@Override\npublic void onWindowFocusChanged(boolean hasFocus) {\n if (!hasFocus) {\n //code to turn off togglebuttons goes here \n }\n}\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 198,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845176\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44480949\"\n}"}}},{"rowIdx":1705659,"cells":{"id":{"kind":"string","value":"cb3c59fff5602bb2ac67a65d038aa1c915bd24c0"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Delete git LFS files not in repo I uploaded some files to git LFS and I went over my storage limit. Now, the files I uploaded don't show up in the repo, but I'm still over my data limit and I can't upload anything. \n\nA: Deleting local Git LFS files\nYou can delete files from your local Git LFS cache with the git lfs prune command:\n$ git lfs prune\n\n✔ 4 local objects, 33 retained\n\nPruning 4 files, (2.1 MB)\n\n✔ Deleted 4 files\n\nThis will delete any local Git LFS files that are considered old. An old file is any file not referenced by:\n\n\n*\n\n*the currently checked out commit\n\n*a commit that has not yet been pushed (to origin, or whatever\nlfs.pruneremotetocheck is set to)\n\n*a recent commit\n\n\nfor details please go through this link https://www.atlassian.com/git/tutorials/git-lfs\n"},"original_text":{"kind":"string","value":"Q: Delete git LFS files not in repo I uploaded some files to git LFS and I went over my storage limit. Now, the files I uploaded don't show up in the repo, but I'm still over my data limit and I can't upload anything. \n\nA: Deleting local Git LFS files\nYou can delete files from your local Git LFS cache with the git lfs prune command:\n$ git lfs prune\n\n✔ 4 local objects, 33 retained\n\nPruning 4 files, (2.1 MB)\n\n✔ Deleted 4 files\n\nThis will delete any local Git LFS files that are considered old. An old file is any file not referenced by:\n\n\n*\n\n*the currently checked out commit\n\n*a commit that has not yet been pushed (to origin, or whatever\nlfs.pruneremotetocheck is set to)\n\n*a recent commit\n\n\nfor details please go through this link https://www.atlassian.com/git/tutorials/git-lfs\n\nA: Currently that is not possible via lfs command line. From the Atlassian Git LFS tutorial:\n\nThe Git LFS command-line client doesn't support pruning files from the server, so how you delete them depends on your hosting provider. In Bitbucket Cloud, you can view and delete Git LFS files via Repository Settings > Git LFS\n\nGitHub even suggest recreating the repo:\n\nTo remove Git LFS objects from a repository, delete and recreate the repository. When you delete a repository, any associated issues, stars, and forks are also deleted.\n\nBut it is still good idea to use tools like BFG to clear out large files in history before moving around.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 249,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845258\",\n \"question_score\": \"7\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481198\"\n}"}}},{"rowIdx":1705660,"cells":{"id":{"kind":"string","value":"0ea7c3950b2bbae2b53e0c96a1a8a5bda9adbb73"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Call super class constructor in Kotlin, Super is not an expression I have two classes Entity and Account as \nabstract class Entity(\n var id: String? = null,\n var created: Date? = Date()) {\n\n constructor(entity: Entity?) : this() {\n fromEntity(entity)\n }\n\n fun fromEntity(entity: Entity?): Entity {\n id = entity?.id\n created = entity?.created\n return this;\n }\n}\n\nand \ndata class Account( \n var name: String? = null,\n var accountFlags: Int? = null\n) : Entity() {\n\n constructor(entity: Entity) : this() {\n super(entity)\n }\n}\n\nWhich gives me the error \n\nSuper is not an expression, it can be only used in the left-hand side of\n a dot '.'\n\nWhy cannot I do that? \nThe following will pass the compilation error, but I am not sure if it is correct.\n constructor(entity: Entity) : this() {\n super.fromEntity(entity)\n}\n\n\nA: You can also move your primary constructor down into the class like this:\ndata class Account: Entity {\n constructor(): super()\n constructor(var name: String? = null, var accountFlags: Int? = null): super()\n constructor(entity: Entity) : super(entity)\n}\n\nAdvantage of this is, compiler will not require your secondary constructor to call primary constructor.\n"},"original_text":{"kind":"string","value":"Q: Call super class constructor in Kotlin, Super is not an expression I have two classes Entity and Account as \nabstract class Entity(\n var id: String? = null,\n var created: Date? = Date()) {\n\n constructor(entity: Entity?) : this() {\n fromEntity(entity)\n }\n\n fun fromEntity(entity: Entity?): Entity {\n id = entity?.id\n created = entity?.created\n return this;\n }\n}\n\nand \ndata class Account( \n var name: String? = null,\n var accountFlags: Int? = null\n) : Entity() {\n\n constructor(entity: Entity) : this() {\n super(entity)\n }\n}\n\nWhich gives me the error \n\nSuper is not an expression, it can be only used in the left-hand side of\n a dot '.'\n\nWhy cannot I do that? \nThe following will pass the compilation error, but I am not sure if it is correct.\n constructor(entity: Entity) : this() {\n super.fromEntity(entity)\n}\n\n\nA: You can also move your primary constructor down into the class like this:\ndata class Account: Entity {\n constructor(): super()\n constructor(var name: String? = null, var accountFlags: Int? = null): super()\n constructor(entity: Entity) : super(entity)\n}\n\nAdvantage of this is, compiler will not require your secondary constructor to call primary constructor.\n\nA: You have a couple of problems in your code.\nFirst, this is the correct syntax, to call a super constructor from a secondary constructor:\nconstructor(entity: Entity) : super(entity)\n\nSecond, you can't call a super constructor from a secondary constructor if your class has a primary constructor (which your class does).\nSolution 1\nabstract class Entity(\n var id: String,\n var created: Date\n)\n\nclass Account(\n var name: String,\n var accountFlags: Int,\n id: String,\n created: Date\n) : Entity(id, created) {\n constructor(account: Account) : this(account.name, account.accountFlags, account.id, account.created)\n}\n\nHere, the copy constructor is in the child class which just delegates to the primary constructor.\nSolution 2\nabstract class Entity(\n var id: String,\n var created: Date\n) {\n constructor(entity: Entity) : this(entity.id, entity.created)\n}\n\nclass Account : Entity {\n var name: String\n var accountFlags: Int\n\n constructor(name: String, accountFlags: Int, id: String, created: Date) : super(id, created) {\n this.name = name\n this.accountFlags = accountFlags\n }\n\n constructor(account: Account) : super(account) {\n this.name = account.name\n this.accountFlags = account.accountFlags\n }\n}\n\nHere I'm only using secondary constructors in the child class which lets me delegate them to individual super constructors. Notice how the code is pretty long.\nSolution 3 (most idiomatic)\nabstract class Entity {\n abstract var id: String\n abstract var created: Date\n}\n\ndata class Account(\n var name: String,\n var accountFlags: Int,\n override var id: String,\n override var created: Date\n) : Entity()\n\nHere I omitted the copy constructors and made the properties abstract so the child class has all the properties. I also made the child class a data class. If you need to clone the class, you can simply call account.copy().\n\nA: Another option is to create companion object and provide factory method e.g.\nclass Account constructor(\n var name: String? = null,\n var accountFlags: Int? = null,\n id: String?,\n created: Date?\n) : Entity(id, created) {\n\n companion object {\n fun fromEntity(entity: Entity): Account {\n return Account(null, null, entity.id, entity.created)\n }\n }\n}\n\n\nA: Use this super.fromEntity(entity) to call super class methods.\nAs Documentation says:\n\nIn Kotlin, implementation inheritance is regulated by the following rule: if a class inherits many implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation (perhaps, using one of the inherited ones). To denote the supertype from which the inherited implementation is taken, we use super qualified by the supertype name in angle brackets, e.g. super.\n\nconstructor(entity: Entity) : this() {\n super.fromEntity(entity)\n}\n\nTo know more read Overriding Rules\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 595,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845282\",\n \"question_score\": \"83\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481268\"\n}"}}},{"rowIdx":1705661,"cells":{"id":{"kind":"string","value":"e39bd80ed962939e087493a74ad88a6845bf196e"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Difference between removeFirstOccurrence and remove Is there any difference between the remove(Object o) method (of List interface) and removeFirstOccurrence(Object o) method (of LinkedList class) in the collections api?\nI could see that both does the same i.e remove first occurrence of the object in the list.\n\nA: No, there is no difference.\nIf you look at source of removeFirstOccurrence(), you'll see:\npublic boolean removeFirstOccurrence(Object o) {\n return remove(o);\n}\n\nThe reason LinkedList has both is given in the javadoc of each:\nremove(Object o)\nSpecified by: remove in interface Collection\nSpecified by: remove in interface Deque\nSpecified by: remove in interface List\nremoveFirstOccurrence(Object o)\nSpecified by: removeFirstOccurrence in interface Deque\n"},"original_text":{"kind":"string","value":"Q: Difference between removeFirstOccurrence and remove Is there any difference between the remove(Object o) method (of List interface) and removeFirstOccurrence(Object o) method (of LinkedList class) in the collections api?\nI could see that both does the same i.e remove first occurrence of the object in the list.\n\nA: No, there is no difference.\nIf you look at source of removeFirstOccurrence(), you'll see:\npublic boolean removeFirstOccurrence(Object o) {\n return remove(o);\n}\n\nThe reason LinkedList has both is given in the javadoc of each:\nremove(Object o)\nSpecified by: remove in interface Collection\nSpecified by: remove in interface Deque\nSpecified by: remove in interface List\nremoveFirstOccurrence(Object o)\nSpecified by: removeFirstOccurrence in interface Deque\n\nA: \nIs there any difference between remove(Object o) method (of List\n interface) and removeFirstOccurrence(Object o) method (of LinkedList\n class) in collections framework?\n\nThese are two distinct methods, coming from two distinct interfaces.\nThe first one (remove(Object o)) is defined in the java.util.Collection interface.\nThe other one (removeFirstOccurrence(Object o) is defined in the java.util.Deque interface.\nThe first one (remove(Object o)) has a contract rather general in the Collection interface :\n\nRemoves a single instance of the specified element from this\n collection, if it is present...\n\nBut the List interface that extends Collection has a more specific contract :\n\nRemoves the first occurrence of the specified element from this list,\n if it is present (optional operation)....\n\nOne the other hand, the removeFirstOccurrence(Object o) defined in the Deque interface specifies a similar contract :\n\nRemoves the first occurrence of the specified element from this deque...\n\n\nIt turns out that the LinkedList implements both directly List and Deque. \nAnd as List.remove(Object o) and Deque.removeFirstOccurrence(Object o) specify a similar contract, it is really not surprising that the behavior and the implementation of these two methods in the LinkedList class be the same.\n\nA: No I do not think any difference is there both remove the first occurrence of element and return.More formally, removes the element with the lowest index i\nJava API ArrayList remove.\n public boolean remove(Object o) {\n if (o == null) {\n for (int index = 0; index < size; index++)\n if (elementData[index] == null) {\n fastRemove(index);\n return true;\n }\n } else {\n for (int index = 0; index < size; index++)\n if (o.equals(elementData[index])) {\n fastRemove(index);\n return true;\n }\n }\n return false;\n }\n\nLinkedList removeFirstOccurrence\nif (o == null) {\n for (Node x = first; x != null; x = x.next) {\n if (x.item == null) {\n unlink(x);\n return true;\n }\n }\n } else {\n for (Node x = first; x != null; x = x.next) {\n if (o.equals(x.item)) {\n unlink(x);\n return true;\n }\n }\n }\n return false;\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 435,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845288\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481291\"\n}"}}},{"rowIdx":1705662,"cells":{"id":{"kind":"string","value":"bdc9a17fc964c221caa086646e09f7bf0975db9d"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Export Visual Studio Solution I want to export the entire solution in visual studio , so i can import that on other computer ?\ni searched in the net and didn't find answer to that question , also \"you cant to that\" is an answer.\ni don't want to copy and paste the entire folder , because I have several things on that folder that i don't want to copy them or start delete each file i don't need , i want to export only the things that solution used.\ntools or other external apps also will be welcomed\nthanks\n\nA: You can easily export your project files as template to reuse later but not the entire solution.\nSo press Save All button every time you make changes to your solution projects. Than close the solution file. Go to where they are saved by default and copy entire project solution folder.\n"},"original_text":{"kind":"string","value":"Q: Export Visual Studio Solution I want to export the entire solution in visual studio , so i can import that on other computer ?\ni searched in the net and didn't find answer to that question , also \"you cant to that\" is an answer.\ni don't want to copy and paste the entire folder , because I have several things on that folder that i don't want to copy them or start delete each file i don't need , i want to export only the things that solution used.\ntools or other external apps also will be welcomed\nthanks\n\nA: You can easily export your project files as template to reuse later but not the entire solution.\nSo press Save All button every time you make changes to your solution projects. Than close the solution file. Go to where they are saved by default and copy entire project solution folder.\n\nA: Second answer would be to use cloud services or use git with visual studio else sign in and share your files to the location where ever you want.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 181,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845301\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481331\"\n}"}}},{"rowIdx":1705663,"cells":{"id":{"kind":"string","value":"92ae2945d6a40b6ad7338480b418700b265b653b"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Multiple Spring boot CommandLineRunner based on command line argument I have created spring boot application with spring cloud task which should executes a few commands(tasks). \nEach task/command is shorted-lived task, and all tasks are start from command line, do some short ETL job and finish execution.\nThere is one spring boot jar which contain all the commands/tasks.\nEach task is CommandLineRunner, and I like to decide which tasks (one or more) will be executed based on the params from command line.\nWhat is the best practice to do so?\nI don't like to have dirty code which ask \"if else\" or something like this.\n\nA: Strangely there is not a built-in mechanism to select a set of CommandLineRunner. By default all of them are executed. \nI have reused - maybe improperly - the Profile mechanism, that is I have annotated each CommandLineRunner with @org.springframework.context.annotation.Profile(\"mycommand\"), and I select the one I want to execute with the System property -Dspring.profiles.active=mycommand\nFor more information on the Profile mechanism, please refer to https://www.baeldung.com/spring-profiles\n"},"original_text":{"kind":"string","value":"Q: Multiple Spring boot CommandLineRunner based on command line argument I have created spring boot application with spring cloud task which should executes a few commands(tasks). \nEach task/command is shorted-lived task, and all tasks are start from command line, do some short ETL job and finish execution.\nThere is one spring boot jar which contain all the commands/tasks.\nEach task is CommandLineRunner, and I like to decide which tasks (one or more) will be executed based on the params from command line.\nWhat is the best practice to do so?\nI don't like to have dirty code which ask \"if else\" or something like this.\n\nA: Strangely there is not a built-in mechanism to select a set of CommandLineRunner. By default all of them are executed. \nI have reused - maybe improperly - the Profile mechanism, that is I have annotated each CommandLineRunner with @org.springframework.context.annotation.Profile(\"mycommand\"), and I select the one I want to execute with the System property -Dspring.profiles.active=mycommand\nFor more information on the Profile mechanism, please refer to https://www.baeldung.com/spring-profiles\n\nA: Similar to this answer https://stackoverflow.com/a/44482525/986160 but using injection and less configuration.\nHaving a similar requirement, what has worked for me is to have one CommandLineApps class implementing CommandLineRunner, then inject all my other command line runners as @Component and use the first argument to delegate to one of the injected runners. Please note that the injected ones should not extend CommandLineRunner and not be annotated as @SpringBootAppplication.\nImportant: be careful though if you put the call in a crontab one call will destroy the previous one if it is not done.\nHere is an example:\n@SpringBootApplication\npublic class CommandLineApps implements CommandLineRunner {\n\n @Autowired\n private FetchSmsStatusCmd fetchSmsStatusCmd;\n\n @Autowired\n private OffersFolderSyncCmd offersFolderSyncCmd;\n\n public static void main(String[] args) {\n ConfigurableApplicationContext ctx = SpringApplication.run(CommandLineApps.class, args);\n ctx.close();\n }\n\n @Override\n public void run(String... args) {\n\n if (args.length == 0) {\n return;\n }\n\n List restOfArgs = Arrays.asList(args).subList(1, args.length);\n\n switch (args[0]) {\n case \"fetch-sms-status\":\n fetchSmsStatusCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));\n break;\n case \"offers-folder-sync\":\n offersFolderSyncCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));\n break;\n }\n }\n}\n\n@Component\npublic class FetchSmsStatusCmd {\n\n [...] @Autowired dependencies \n\n public void run(String[] args) {\n\n if (args.length != 1) {\n logger.error(\"Wrong number of arguments\");\n return;\n }\n [...]\n }\n }\n\n\nA: You can also make your CommandLineRunner implementations @Component and @ConditionalOnExpression(\"${someproperty:false}\")\nthen have multiple profiles, that set someproperty to true to include those CommandLineRunners in the Context.\n@Component\n@Slf4j\n@ConditionalOnExpression(\"${myRunnerEnabled:false}\")\npublic class MyRunner implements CommandLineRunner {\n @Override\n public void run(String ... args) throws Exception {\n log.info(\"this ran\");\n }\n}\n\nand in the yml application-myrunner.yml\nmyRunnerEnabled: true\n\n@SpringBootApplication\npublic class SpringMain {\n public static void main(String ... args) {\n SpringApplication.run(SpringMain.class, args);\n }\n}\n\n\nA: Spring Boot runs all the CommandLineRunner or ApplicationRunner beans from the application context. You cannot select one by any args.\nSo basically you have two possibiities:\n\n\n*\n\n*You have different CommandLineRunner implementations and in each you check the arguments to determine if this special CommandLineRunner should run.\n\n*You implement only one CommandLineRunner which acts as a dispatcher. Code might look something like this:\n\n\nThis is the new Interface that your runners will implement:\npublic interface MyCommandLineRunner {\n void run(String... strings) throws Exception;\n}\n\nYou then define implementations and identify them with a name:\n@Component(\"one\")\npublic class MyCommandLineRunnerOne implements MyCommandLineRunner {\n private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerOne.class);\n\n @Override\n public void run(String... strings) throws Exception {\n log.info(\"running\");\n }\n}\n\nand\n@Component(\"two\")\npublic class MyCommandLineRunnerTwo implements MyCommandLineRunner {\n private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerTwo.class);\n @Override\n public void run(String... strings) throws Exception {\n log.info(\"running\");\n }\n}\n\nThen in your single CommandLineRunner implementation you get hold of the application context and resolve the required bean by name, my example uses just the first argument, and call it's MyCommandLineRunner.run()method:\n@Component\npublic class CommandLineRunnerImpl implements CommandLineRunner, ApplicationContextAware {\n private ApplicationContext applicationContext;\n\n\n @Override\n public void run(String... strings) throws Exception {\n if (strings.length < 1) {\n throw new IllegalArgumentException(\"no args given\");\n }\n\n String name = strings[0];\n final MyCommandLineRunner myCommandLineRunner = applicationContext.getBean(name, MyCommandLineRunner.class);\n myCommandLineRunner.run(strings);\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n}\n\n\nA: You can have multiple CommandLineRunner in single file or application. Which one needs to be executed ( calling \"run\" method) decided by the one and only - Order (@Order annotation).\nIf you need to execute multiple CommandLineRunner, write them, pass the value to Order annotation.\n@Bean\n @Order(value = 1)\n public CommandLineRunner demo1(CustomerRepository customerRepository){\n return (args) ->{\n customerRepository.save(new Customer(\"Viji\", \"Veerappan\"));\n customerRepository.save(new Customer(\"Dhinesh\", \"Veerappan\"));\n customerRepository.save(new Customer(\"Senbagavalli\", \"Veerappan\"));\n };\n }\n\n\n\n@Order(value = 2)\n public CommandLineRunner demo(CustomerRepository customerRepository){\n return (args) ->{\n\n // Save all the customers\n customerRepository.save(new Customer(\"Mahith\", \"Saravanan\"));\n customerRepository.save(new Customer(\"Pooshi\", \"Saravanan\"));\n customerRepository.save(new Customer(\"Dharma\", \"Saravanan\"));\n customerRepository.save(new Customer(\"Mookayee\", \"Veerayandi\"));\n customerRepository.save(new Customer(\"Chellammal\", \"Kandasamy\"));\n\n //fetch all customer\n log.info(\"Fetching all the customers by findAll()\");\n log.info(\"----------------------------------------\");\n for(Customer customer : customerRepository.findAll()){\n log.info(customer.toString());\n }\n log.info(\"\");\n\n //fetch one customer by Id\n log.info(\"Fetch one customer Id by findById(1L)\");\n log.info(\"----------------------------------------\");\n log.info(customerRepository.findById(1L).toString());\n log.info(\"\");\n\n //fetch by last name\n log.info(\"Fetch all customers that have lastname = Saravanan\");\n log.info(\"---------------------------------------------------\");\n for(Customer customer: customerRepository.findByLastName(\"Saravanan\")){\n log.info(customer.toString());\n }\n /*customerRepository.findByLastName(\"Saravanan\").forEach( saravanan ->{\n saravanan.toString();\n });*/\n };\n }\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 812,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845304\",\n \"question_score\": \"12\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481342\"\n}"}}},{"rowIdx":1705664,"cells":{"id":{"kind":"string","value":"54ea34c2dd57aa58d98a90d0439ca0fb4def6816"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Where to find Identity Pool Id in Cognito Where is Identity Pool in Cognito Console. In the docs mentioned:\n\nIdentityPoolId\nAn identity pool ID in the format REGION:GUID.\n\nBut I see only Pool Id and Pool ARN in the console. Which have different formats.\n\nA: If you've navigated to the dashboard, you can also pull the identity pool ID from the URL:\n\n"},"original_text":{"kind":"string","value":"Q: Where to find Identity Pool Id in Cognito Where is Identity Pool in Cognito Console. In the docs mentioned:\n\nIdentityPoolId\nAn identity pool ID in the format REGION:GUID.\n\nBut I see only Pool Id and Pool ARN in the console. Which have different formats.\n\nA: If you've navigated to the dashboard, you can also pull the identity pool ID from the URL:\n\n\nA: After creating the user pool, If you did not create associated Identity pool, Create a new one (Identity pool) and while creating it, set it as below (or as per your needs)\n\nOnce you click create, click Allow on the following screen then you will see the identity pool id like below\n\nIf you already have one, The from Cognito main screen, click Manage Identity Pools, click on the pool you want to get its Id then from side menu click \"Sample Code\" you will see the same screen as in the above image.\n\nA: I can manage to get the IdentityPooId by aws cli:\naws cognito-identity list-identity-pools --max-results 10\n\nThe command returns all of the Cognito identity pools registered for your account.\n{\n \"IdentityPools\": [\n {\n \"IdentityPoolId\": \"XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab\",\n \"IdentityPoolName\": \"\"\n }\n ]\n}\n\n\nA: For folks working with AWS CloudFormation: The documentation for AWS::Cognito::IdentityPool says you can obtain the IdentityPoolId from the return value, via Ref:\n\nReturn Values > Ref: When you pass the logical ID of this resource to the intrinsic Ref\nfunction, Ref returns the IdentityPoolId, such as\nus-east-2:0d01f4d7-1305-4408-b437-12345EXAMPLE.\n\nWith AWS CDK, you can output the IdentityPoolId this way (Python):\ncore.CfnOutput(self, id='IdentityPoolId', value=idp.ref)\n\nWhere idp is an instance of CfnIdentityPool.\n\nA: You can find Identity pool ID if you select Manage Federated Identities on the page https://eu-west-1.console.aws.amazon.com/cognito/home?region=eu-west-1 and create an Federated Identity.\n\n\nA: Just ran into this trying to fill out amplifyconfiguration.json. Trying to figure out which identity pool was connect to the user pool. In the management console, the name top under \"User Pools | Federated Identities\" is the name of the identity pool. In Federated Identities, I can find the identity pool with the same name. On the dashboard, I can see the user pool id listed as one of the authentication methods. Grab the identity pool id out of the url or from the sample code like others have mentioned.\n\nA: You can find here: Amazon Cognito -> Federated identities:\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 392,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845354\",\n \"question_score\": \"51\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481490\"\n}"}}},{"rowIdx":1705665,"cells":{"id":{"kind":"string","value":"962e5f0ae2b80308e7d86c02f5b4a16196545d81"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Difference between Int and Uint8 swift What are the differences between the data types Int & UInt8 in swift. \nLooks like UInt8 is used for binary data, i need to convert UInt8 to Int is this possible. \n\nA: That U in UInt stands for unsigned int.\nIt is not just using for binary data. Uint is used for positive numbers only, like natural numbers.\nI recommend you to get to know how negative numbers are understood from a computer.\n"},"original_text":{"kind":"string","value":"Q: Difference between Int and Uint8 swift What are the differences between the data types Int & UInt8 in swift. \nLooks like UInt8 is used for binary data, i need to convert UInt8 to Int is this possible. \n\nA: That U in UInt stands for unsigned int.\nIt is not just using for binary data. Uint is used for positive numbers only, like natural numbers.\nI recommend you to get to know how negative numbers are understood from a computer.\n\nA: Int8 is an Integer type which can store positive and negative values.\nUInt8 is an unsigned integer which can store only positive values.\nYou can easily convert UInt8 to Int8 but if you want to convert Int8 to UInt8 then make sure value should be positive.\n\nA: UInt8 is an 8bit store, while Int not hardly defined or defined by the compiler:\nhttps://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html\nInt could be 32 or 64 bits\n\nA: \nUpdated for swift:\n\nOperation Output Range Bytes per Element\n\nuint8 0 to 255 1 \n\nInt - 9223372036854775808 to 9223372036854775807 2 or 4 \n\nIf you want to find the max and min range of Int or UInt8:\n let maxIntValue = Int.max\n let maxUInt8Value = UInt8.max\n\n let minIntValue = Int.min\n let minUInt8Value = UInt8.min\n\nIf you want to convert UInt8 to Int, used below simple code:\nfunc convertToInt(unsigned: UInt) -> Int {\n let signed = (unsigned <= UInt(Int.max)) ?\n Int(unsigned) :\n Int(unsigned - UInt(Int.max) - 1) + Int.min\n\n return signed\n}\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 241,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845393\",\n \"question_score\": \"10\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481618\"\n}"}}},{"rowIdx":1705666,"cells":{"id":{"kind":"string","value":"4422880382652e5518718ce096259bbe6be5dc90"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to get feed of Telegram channel I need to show telegram channel posts in a website. but I don't know how to export telegram channel into xml. I need to have both texts and images and also other files and media like mp4 - pdf or other things.\nIs there any way to do that?\n\nA: In three steps:\n\n\n*\n\n*First you need create a bot with @botfather. Then add bot to channel. (There is no need to make bot admin.)\n\n*Second use a programming language and write a program that receives message from channel and send it to server.\n\n*Third you must provide a way in site back-end to receive posts that your program sends.\n\n\nFor second step i suggest you to use python. there are some modules that can deal with bots.i think in your case telepot can be simplest module that do everything you need.\nFor third step you must add more details about your site back-end. anyway i suggest you to write a Restful API for back-end and send posts to site with python requests module.\n"},"original_text":{"kind":"string","value":"Q: How to get feed of Telegram channel I need to show telegram channel posts in a website. but I don't know how to export telegram channel into xml. I need to have both texts and images and also other files and media like mp4 - pdf or other things.\nIs there any way to do that?\n\nA: In three steps:\n\n\n*\n\n*First you need create a bot with @botfather. Then add bot to channel. (There is no need to make bot admin.)\n\n*Second use a programming language and write a program that receives message from channel and send it to server.\n\n*Third you must provide a way in site back-end to receive posts that your program sends.\n\n\nFor second step i suggest you to use python. there are some modules that can deal with bots.i think in your case telepot can be simplest module that do everything you need.\nFor third step you must add more details about your site back-end. anyway i suggest you to write a Restful API for back-end and send posts to site with python requests module.\n\nA: You need to use telegram API to access the content of a channel. \nTelegram API is fairly complicated. There are clients in different languages that makes it easier to interact with the API. \nI personally worked with Telethon and it's relatively simple to get it work. If you follow the directions on the home page, there is also an interactive client you can play around to get yourself familiar with how it works. \nIf you are familiar with other languages there are clients for those languages as well. If you prefer any specific language please comment. \n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 279,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845399\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481634\"\n}"}}},{"rowIdx":1705667,"cells":{"id":{"kind":"string","value":"0b494ab8917bb82519e774c88308b7df02e15a9e"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Enable \"show_touches\" via appium or adb on android emulator Is it possible to enable the \"show_touches\" options on android from appium? Or via adb?\nI have a appium test-script, which misbehaves. I have no Idea why, and I want to see where exactly it clicks.\n\nA: adb shell settings put system show_touches 1\n\n"},"original_text":{"kind":"string","value":"Q: Enable \"show_touches\" via appium or adb on android emulator Is it possible to enable the \"show_touches\" options on android from appium? Or via adb?\nI have a appium test-script, which misbehaves. I have no Idea why, and I want to see where exactly it clicks.\n\nA: adb shell settings put system show_touches 1\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 54,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845423\",\n \"question_score\": \"10\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481713\"\n}"}}},{"rowIdx":1705668,"cells":{"id":{"kind":"string","value":"b322aa47665b818427fbd28ea4c48ddbd3564a55"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Java type inference differences between javac 1.8.0_45 and javac 1.8.0_92? I have some code that compiles with javac 1.8.0_92: \npublic final class Either {\n\n // ...\n\n private final L l;\n private final R r;\n\n // ...\n\n public T join(final Function f, final Function g) {\n Preconditions.checkNotNull(f);\n Preconditions.checkNotNull(g);\n return which == LeftOrRight.LEFT ?\n f.apply(l) :\n g.apply(r);\n }\n\n public Optional left() {\n return join(Optional::of, x -> Optional.empty());\n }\n\n // ...\n}\n\nHowever, with javac 1.8.0_45, some extra types are required (L): \n public Optional left() {\n return join(Optional::of, x -> Optional.empty());\n }\n\nAs you can imagine, this causes issues for packages that a user builds from source. \n\n\n*\n\n*Why is this? \n\n*Is this a bug with that particular build of Java? \n\nA: Yes, this is the JDK bug where type inference fails with nested invocations. If you set either one of the arguments to null, the code compiles.\nhttps://bugs.openjdk.java.net/browse/JDK-8055963\nA fix was committed for Java 9, but they also backported it to 8u60:\nhttps://bugs.openjdk.java.net/browse/JDK-8081020\n"},"original_text":{"kind":"string","value":"Q: Java type inference differences between javac 1.8.0_45 and javac 1.8.0_92? I have some code that compiles with javac 1.8.0_92: \npublic final class Either {\n\n // ...\n\n private final L l;\n private final R r;\n\n // ...\n\n public T join(final Function f, final Function g) {\n Preconditions.checkNotNull(f);\n Preconditions.checkNotNull(g);\n return which == LeftOrRight.LEFT ?\n f.apply(l) :\n g.apply(r);\n }\n\n public Optional left() {\n return join(Optional::of, x -> Optional.empty());\n }\n\n // ...\n}\n\nHowever, with javac 1.8.0_45, some extra types are required (L): \n public Optional left() {\n return join(Optional::of, x -> Optional.empty());\n }\n\nAs you can imagine, this causes issues for packages that a user builds from source. \n\n\n*\n\n*Why is this? \n\n*Is this a bug with that particular build of Java? \n\nA: Yes, this is the JDK bug where type inference fails with nested invocations. If you set either one of the arguments to null, the code compiles.\nhttps://bugs.openjdk.java.net/browse/JDK-8055963\nA fix was committed for Java 9, but they also backported it to 8u60:\nhttps://bugs.openjdk.java.net/browse/JDK-8081020\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 166,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845445\",\n \"question_score\": \"6\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481795\"\n}"}}},{"rowIdx":1705669,"cells":{"id":{"kind":"string","value":"ae96df314e1bf624a6e2bf7fad8377f181baa9d5"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Does ES6 import/export need \".js\" extension? I installed chrome beta - Version 60.0.3112.24 (Official Build) beta (64-bit)\nIn chrome://flags/ I enabled 'Experimental Web Platform features' (see https://jakearchibald.com/2017/es-modules-in-browsers)\nI then tried: \n\n\nwhere index.js has a line like: \nexport { default as drawImage } from './drawImage';\n\nThis refer to an existing file drawImage.js\nwhat I get in the console is error in \nGET http://localhost/bla/src/drawImage \n\nIf I change the export and add \".js\" extension it works fine.\nIs this a chrome bug or does ES6 demands the extension in this case ?\nAlso webpack builds it fine without the extension !\n\nA: ES6 import/export need “.js” extension.\nThere are clear instructions in node document:\n\n*\n\n*Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these.\n\n*This behavior matches how import behaves in browser environments, assuming a typically configured server.\n\nhttps://nodejs.org/api/esm.html#esm_import_expressions\n"},"original_text":{"kind":"string","value":"Q: Does ES6 import/export need \".js\" extension? I installed chrome beta - Version 60.0.3112.24 (Official Build) beta (64-bit)\nIn chrome://flags/ I enabled 'Experimental Web Platform features' (see https://jakearchibald.com/2017/es-modules-in-browsers)\nI then tried: \n\n\nwhere index.js has a line like: \nexport { default as drawImage } from './drawImage';\n\nThis refer to an existing file drawImage.js\nwhat I get in the console is error in \nGET http://localhost/bla/src/drawImage \n\nIf I change the export and add \".js\" extension it works fine.\nIs this a chrome bug or does ES6 demands the extension in this case ?\nAlso webpack builds it fine without the extension !\n\nA: ES6 import/export need “.js” extension.\nThere are clear instructions in node document:\n\n*\n\n*Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these.\n\n*This behavior matches how import behaves in browser environments, assuming a typically configured server.\n\nhttps://nodejs.org/api/esm.html#esm_import_expressions\n\nA: No, modules don't care about extensions. It just needs to be a name that resolves to a source file.\nIn your case, http://localhost/bla/src/drawImage is not a file while http://localhost/bla/src/drawImage.js is, so that's where there error comes from. You can either add the .js in all your import statements, or configure your server to ignore the extension, for example. Webpack does the same. A browser doesn't, because it's not allowed to rewrite urls arbitrarily.\n\nA: The extension is part of the filename. You have to put it in.\nAs proof of this, please try the following:\n\n*\n\n*rename file to drawImage.test\n\n*edit index.js to contain './drawImage.test'\nReload, and you'll see the extension js or test will be completely arbitrary, as long as you specify it in the export.\nObviously, after the test revert to the correct/better js extension.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 296,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845468\",\n \"question_score\": \"44\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481851\"\n}"}}},{"rowIdx":1705670,"cells":{"id":{"kind":"string","value":"582132a6f92297432c5aa28384c6725aa7248be1"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to abort Jenkins build from shell script? I see that returning a non-zero integer in shell script executing on Jenkins will make the result marked as a failure.\nHow do I make it change to Aborted? Is there a plugin to do this? Can I avoid having to use GroovyScript? \n\nA: Instead of returning a non-zero integer and having the build fail, you could trigger an Abort on the build using its Rest API within the shell build step.\nExample using curl:\ncurl -XPOST $BUILD_URL/stop\n\nExample using wget:\nwget --post-data=\"\" $BUILD_URL/stop\n\n"},"original_text":{"kind":"string","value":"Q: How to abort Jenkins build from shell script? I see that returning a non-zero integer in shell script executing on Jenkins will make the result marked as a failure.\nHow do I make it change to Aborted? Is there a plugin to do this? Can I avoid having to use GroovyScript? \n\nA: Instead of returning a non-zero integer and having the build fail, you could trigger an Abort on the build using its Rest API within the shell build step.\nExample using curl:\ncurl -XPOST $BUILD_URL/stop\n\nExample using wget:\nwget --post-data=\"\" $BUILD_URL/stop\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 93,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845498\",\n \"question_score\": \"9\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481928\"\n}"}}},{"rowIdx":1705671,"cells":{"id":{"kind":"string","value":"aaecc592e40ad82fa3e0168b646093bea5ce0996"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to implement an abstract getter with property I have java code:\npublic abstract class A {\n abstract int getA()\n}\n\nI tried:\nclass B : A() {\n val a = 0\n}\n\nDoesn't compile.\nclass B : A() {\n override val a = 0\n}\n\nStill doesn't compile.\nclass B : A() {\n override val a: Int get () = 1\n}\n\nStill doesn't compile.\nclass B : A() {\n override val a: Int override get () = 1\n}\n\nStill doesn't compile.\nclass B : A() {\n val a: Int override get () = 1\n}\n\nNone of them are working. Does that mean I can only use \nclass B : A() {\n override fun getA() = 1\n}\n\n? I think the last one(overriding the method) is ugly.\nThis could be worse when you have a getter-setter pair. It's expected to override getter-setter pair with a var property, but you have to write two methods.\n\nA: According to @Miha_x64 ,\n\nfunctions can be overriden only with a function.\n\nSeems that I was trying something impossible.\n"},"original_text":{"kind":"string","value":"Q: How to implement an abstract getter with property I have java code:\npublic abstract class A {\n abstract int getA()\n}\n\nI tried:\nclass B : A() {\n val a = 0\n}\n\nDoesn't compile.\nclass B : A() {\n override val a = 0\n}\n\nStill doesn't compile.\nclass B : A() {\n override val a: Int get () = 1\n}\n\nStill doesn't compile.\nclass B : A() {\n override val a: Int override get () = 1\n}\n\nStill doesn't compile.\nclass B : A() {\n val a: Int override get () = 1\n}\n\nNone of them are working. Does that mean I can only use \nclass B : A() {\n override fun getA() = 1\n}\n\n? I think the last one(overriding the method) is ugly.\nThis could be worse when you have a getter-setter pair. It's expected to override getter-setter pair with a var property, but you have to write two methods.\n\nA: According to @Miha_x64 ,\n\nfunctions can be overriden only with a function.\n\nSeems that I was trying something impossible.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 179,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845510\",\n \"question_score\": \"6\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44481959\"\n}"}}},{"rowIdx":1705672,"cells":{"id":{"kind":"string","value":"0d45b2b11456e6f63d27379aefec0c68794390be"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Deserialize array of object using jms/serializer I want to deserialize something like this:\n[\n { \"id\": 42 },\n { \"id\": 43 }\n]\n\nAny idea how to do this?\n\nA: It would be\n$serializer->deserialize($json, 'array', 'json')\n\nwhere T is the name of the class with the id property.\n"},"original_text":{"kind":"string","value":"Q: Deserialize array of object using jms/serializer I want to deserialize something like this:\n[\n { \"id\": 42 },\n { \"id\": 43 }\n]\n\nAny idea how to do this?\n\nA: It would be\n$serializer->deserialize($json, 'array', 'json')\n\nwhere T is the name of the class with the id property.\n\nA: Let's say you have a class foo, that has an attribute with an array of bar objects.\nIn your foo class use JMS\\Serializer\\Annotation\\Type as Type; and annotate the attribute like this:\nuse JMS\\Serializer\\Annotation\\Type as Type;\nclass foo {\n /**\n *\n * @Type(\"array\")\n * private $bars = array();\n */\n }\n\nJMS Serializer will serialize/deserialize the contents of foo automagically. This use of @Type should be utilized for all attributes of any classes you will be serializing/deserializing.\nThis also works in situations where you are using string keys (ie. associative array structure). Just substitute \"string\" for int.\n@Type(\"array\")\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 146,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845536\",\n \"question_score\": \"11\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482033\"\n}"}}},{"rowIdx":1705673,"cells":{"id":{"kind":"string","value":"d0af5bfdf237780ecb66d6720a2fff9f171a0b10"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: UnableToResolveError : unable to resolve module `merge` from Libraries/ART/React Native ART.js I am new to React-native. \nI am stuck with this error : \nUnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js\ndependencies I have used are : \n\"dependencies\": {\n \"apsl-react-native-button\": \"^3.0.2\",\n \"react\": \"16.0.0-alpha.6\",\n \"react-native\": \"0.44.2\",\n \"react-native-deprecated-custom-components\": \"^0.1.0\",\n .....................\n },\n\nin node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available.\nWhen I run react-native run-android command, I am facing this error.\nCan anyone help me in this ?\n\nA: Just need to install this module npm i --save merge\n"},"original_text":{"kind":"string","value":"Q: UnableToResolveError : unable to resolve module `merge` from Libraries/ART/React Native ART.js I am new to React-native. \nI am stuck with this error : \nUnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js\ndependencies I have used are : \n\"dependencies\": {\n \"apsl-react-native-button\": \"^3.0.2\",\n \"react\": \"16.0.0-alpha.6\",\n \"react-native\": \"0.44.2\",\n \"react-native-deprecated-custom-components\": \"^0.1.0\",\n .....................\n },\n\nin node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available.\nWhen I run react-native run-android command, I am facing this error.\nCan anyone help me in this ?\n\nA: Just need to install this module npm i --save merge\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 88,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845538\",\n \"question_score\": \"6\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482037\"\n}"}}},{"rowIdx":1705674,"cells":{"id":{"kind":"string","value":"d8ed2e60b8fcf25add113c88cf403f2a5196648d"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Removing trailing spaces with clang-format As the title says, I'm trying to get clang-format to remove the trailing white spaces of my files, but I fail to find the relevant option name.\nCould anyone point me to the obvious?\n\nA: clang-format does remove trailing whitespaces automatically.\nYou can test this by e.g. clang-format -style=Google file.cpp -i.\nIt is also useful to know most modern editors do have built-in options to do this and even more for you on save. Here are a few:\n\n*\n\n*In Sublime text settings set trim_trailing_white_space_on_save to true.\n\n*In VScode set files.trimTrailingWhitespace to true.\n\n*In Vim you need a vimrc file as described here.\n\n*etc.\n\n"},"original_text":{"kind":"string","value":"Q: Removing trailing spaces with clang-format As the title says, I'm trying to get clang-format to remove the trailing white spaces of my files, but I fail to find the relevant option name.\nCould anyone point me to the obvious?\n\nA: clang-format does remove trailing whitespaces automatically.\nYou can test this by e.g. clang-format -style=Google file.cpp -i.\nIt is also useful to know most modern editors do have built-in options to do this and even more for you on save. Here are a few:\n\n*\n\n*In Sublime text settings set trim_trailing_white_space_on_save to true.\n\n*In VScode set files.trimTrailingWhitespace to true.\n\n*In Vim you need a vimrc file as described here.\n\n*etc.\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 110,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845546\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482062\"\n}"}}},{"rowIdx":1705675,"cells":{"id":{"kind":"string","value":"b5ecd8c5f66feec54f0f472aa4be2ecc77338028"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Create PostgreSQL dump with ONE INSERT statement instead of INSERT per row I try to do a table data dump using pg_dump, something like this:\npg96\\bin\\pg_dump ... --format plain --section data --column-inserts --file obj.account.backup --table obj.account database_xyz\n\nInstead of getting \nINSERT INTO obj.account(name, email, password) VALUES ('user1','email1','password1');\nINSERT INTO obj.account(name, email, password) VALUES ('user2','email2','password2');\n\nI would like to get\nINSERT INTO obj.account (name, email, password) VALUES \n('user1','email1','password1'),\n('user2','email2','password2'); \n\nIs there a way for this without any Non-PostgreSQL postprocessing?\n\nA: There is no way to get INSERT statements like that with pg_dump.\n"},"original_text":{"kind":"string","value":"Q: Create PostgreSQL dump with ONE INSERT statement instead of INSERT per row I try to do a table data dump using pg_dump, something like this:\npg96\\bin\\pg_dump ... --format plain --section data --column-inserts --file obj.account.backup --table obj.account database_xyz\n\nInstead of getting \nINSERT INTO obj.account(name, email, password) VALUES ('user1','email1','password1');\nINSERT INTO obj.account(name, email, password) VALUES ('user2','email2','password2');\n\nI would like to get\nINSERT INTO obj.account (name, email, password) VALUES \n('user1','email1','password1'),\n('user2','email2','password2'); \n\nIs there a way for this without any Non-PostgreSQL postprocessing?\n\nA: There is no way to get INSERT statements like that with pg_dump.\n\nA: Since PostgreSQL 12 you can use pg_dump with --rows-per-insert=nrows, see https://www.postgresql.org/docs/12/app-pgdump.html\nI'm aware that this is an old question but I wanted to mention it in case somebody else (like me) finds this while searching for a solution. There are cases where COPY can't be used and for bigger data sets using a single INSERT statement is much faster when importing.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 154,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845548\",\n \"question_score\": \"6\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482070\"\n}"}}},{"rowIdx":1705676,"cells":{"id":{"kind":"string","value":"b8514e23ca2f9baf6e29d86090858055a722dcc2"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Remove lines from CSV file using Powershell I have a CSV file with logging information. Date/time info in the file is written in UNIX time-stamp format. \nI want to remove all lines older than 5 minutes. I use the following code to do this:\n$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300\n$Content = Import-Csv \"logfile.csv\" | where {$_.DateCompleted -gt $FiveMinutesAgo} \n$Content | Export-Csv -delimiter \";\" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'\n\nThe CSV file looks like this:\n\"DateInitiated\";\"DateStarted\";\"DateCompleted\";\"InitiatedBy\";\"Action\";\"Status\"\n\"1496659208\";\"1496659264\";\"1496752840\";\"administrator\";\"Reboot server\";\"Completed\"\n\nNo matter whether the five minutes have already passed or not, my CSV file ends up completely empty after executing the script lines above. \n\nA: I couldn't replicate it in testing (but potentially need the actual source file). I think the issue is that you need to specify both the encoding and delimiter on the Import-CSV as well (as you already have on Export).\nTry this:\n$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300\n$Content = Import-Csv \"test.csv\" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo} \n$Content | Export-Csv -delimiter \";\" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'\n\n"},"original_text":{"kind":"string","value":"Q: Remove lines from CSV file using Powershell I have a CSV file with logging information. Date/time info in the file is written in UNIX time-stamp format. \nI want to remove all lines older than 5 minutes. I use the following code to do this:\n$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300\n$Content = Import-Csv \"logfile.csv\" | where {$_.DateCompleted -gt $FiveMinutesAgo} \n$Content | Export-Csv -delimiter \";\" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'\n\nThe CSV file looks like this:\n\"DateInitiated\";\"DateStarted\";\"DateCompleted\";\"InitiatedBy\";\"Action\";\"Status\"\n\"1496659208\";\"1496659264\";\"1496752840\";\"administrator\";\"Reboot server\";\"Completed\"\n\nNo matter whether the five minutes have already passed or not, my CSV file ends up completely empty after executing the script lines above. \n\nA: I couldn't replicate it in testing (but potentially need the actual source file). I think the issue is that you need to specify both the encoding and delimiter on the Import-CSV as well (as you already have on Export).\nTry this:\n$FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300\n$Content = Import-Csv \"test.csv\" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo} \n$Content | Export-Csv -delimiter \";\" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 170,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845550\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482074\"\n}"}}},{"rowIdx":1705677,"cells":{"id":{"kind":"string","value":"e7f9a718483669030cd3a3eb6b6e58b4f89e90b0"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Dataframe filtering rows by column values I have a Dataframe df\n Num1 Num2 \none 1 0\ntwo 3 2\nthree 5 4\nfour 7 6\nfive 9 8\n\nI want to filter rows that have value bigger than 3 in Num1 and smaller than 8 in Num2.\nI tried this\ndf = df[df['Num1'] > 3 and df['Num2'] < 8]\n\nbut the error occurred.\nValueError: The truth value of a Series is ambiguous.\nso I used\ndf = df[df['Num1'] > 3]\ndf = df[df['Num2'] < 8]\n\nI think the code can be shorter.\nIs there any other way?\n\nA: Yes, you can use the & operator:\ndf = df[(df['Num1'] > 3) & (df['Num2'] < 8)]\n# ^ & operator\nThis is because and works on the truthiness value of the two operands, whereas the & operator can be defined on arbitrary data structures.\nThe brackets are mandatory here, because & binds shorter than > and <, so without brackets, Python would read the expression as df['Num1'] > (3 & df['Num2']) < 8.\nNote that you can use the | operator as a logical or.\n"},"original_text":{"kind":"string","value":"Q: Dataframe filtering rows by column values I have a Dataframe df\n Num1 Num2 \none 1 0\ntwo 3 2\nthree 5 4\nfour 7 6\nfive 9 8\n\nI want to filter rows that have value bigger than 3 in Num1 and smaller than 8 in Num2.\nI tried this\ndf = df[df['Num1'] > 3 and df['Num2'] < 8]\n\nbut the error occurred.\nValueError: The truth value of a Series is ambiguous.\nso I used\ndf = df[df['Num1'] > 3]\ndf = df[df['Num2'] < 8]\n\nI think the code can be shorter.\nIs there any other way?\n\nA: Yes, you can use the & operator:\ndf = df[(df['Num1'] > 3) & (df['Num2'] < 8)]\n# ^ & operator\nThis is because and works on the truthiness value of the two operands, whereas the & operator can be defined on arbitrary data structures.\nThe brackets are mandatory here, because & binds shorter than > and <, so without brackets, Python would read the expression as df['Num1'] > (3 & df['Num2']) < 8.\nNote that you can use the | operator as a logical or.\n\nA: You need add () because operator precedence with bit-wise operator &:\ndf1 = df[(df['Num1'] > 3) & (df['Num2'] < 8)]\nprint (df1)\n Num1 Num2\nthree 5 4\nfour 7 6\n\nBetter explanation is here.\nOr if need shortest code use query:\ndf1 = df.query(\"Num1 > 3 and Num2 < 8\")\nprint (df1)\n Num1 Num2\nthree 5 4\nfour 7 6\n\n\ndf1 = df.query(\"Num1 > 3 & Num2 < 8\")\nprint (df1)\n Num1 Num2\nthree 5 4\nfour 7 6\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 264,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845554\",\n \"question_score\": \"17\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482095\"\n}"}}},{"rowIdx":1705678,"cells":{"id":{"kind":"string","value":"ae42913d24733cbca0cd803d15f2a4ff55d28317"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: False error by eslint-plugin-import for webpack aliases I am using webpack's aliases in my project. Everything works fine in my original project, but when I clone the project, I get error from import/no-unresolved for my webpack aliases:\n\nCasing of $js/Controller does not match the underlying filesystem import/no-unresolved\n\nwhat makes it more interesting is that my project works fine. import/no-unresolved seems to send show false error.\nFor more details, I am adding few links: .eslintrc.js, webpack.config.babel.js, Link to my Repo\nplease let me know if you need anything else.\n\nA: I found the solution. I installed eslint-import-resolver-webpack in order to make Webpack aliases work with eslint resolver. Here is the command to install the plugin:\nnpm install eslint-import-resolver-webpack --save-dev\n\nHere is the link to the repo\n"},"original_text":{"kind":"string","value":"Q: False error by eslint-plugin-import for webpack aliases I am using webpack's aliases in my project. Everything works fine in my original project, but when I clone the project, I get error from import/no-unresolved for my webpack aliases:\n\nCasing of $js/Controller does not match the underlying filesystem import/no-unresolved\n\nwhat makes it more interesting is that my project works fine. import/no-unresolved seems to send show false error.\nFor more details, I am adding few links: .eslintrc.js, webpack.config.babel.js, Link to my Repo\nplease let me know if you need anything else.\n\nA: I found the solution. I installed eslint-import-resolver-webpack in order to make Webpack aliases work with eslint resolver. Here is the command to install the plugin:\nnpm install eslint-import-resolver-webpack --save-dev\n\nHere is the link to the repo\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 126,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845556\",\n \"question_score\": \"7\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482102\"\n}"}}},{"rowIdx":1705679,"cells":{"id":{"kind":"string","value":"2c364ea5781122103c138ce8b9eed5750ef7f016"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Git - How to remove one of two folders with the same name in remote repo I have a repository on github with two folders with the same name but different content. I would like to remove one of these folders. The problem is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep).\nObviously something went wrong in an earlier commit.\nAny ideas how I remove one of these folder without removing the other?\n\nA: \nis that if I list the data in the repo locally, there is only one folder (with the content I would like to keep).\n\nThen it is possible that a git status shows you the second one, deleted.\nOr that your OS was not able to load it, because it is case insensitive\nRegister that deletion to the index, commit and push:\ngit rm --cached -r secondFolder/\ngit add -A .\ngit commit -m \"delete folder\"\ngit push\n\n"},"original_text":{"kind":"string","value":"Q: Git - How to remove one of two folders with the same name in remote repo I have a repository on github with two folders with the same name but different content. I would like to remove one of these folders. The problem is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep).\nObviously something went wrong in an earlier commit.\nAny ideas how I remove one of these folder without removing the other?\n\nA: \nis that if I list the data in the repo locally, there is only one folder (with the content I would like to keep).\n\nThen it is possible that a git status shows you the second one, deleted.\nOr that your OS was not able to load it, because it is case insensitive\nRegister that deletion to the index, commit and push:\ngit rm --cached -r secondFolder/\ngit add -A .\ngit commit -m \"delete folder\"\ngit push\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 168,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845569\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482128\"\n}"}}},{"rowIdx":1705680,"cells":{"id":{"kind":"string","value":"56605cf566b07dab951e6d89715fae3b97c2568d"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to use $this in closure in php I have function like this:\nclass Service {\n function delete_user($username) { \n ...\n $sessions = $this->config->sessions;\n $this->config->sessions = array_filter($sessions, function($session) use ($this){\n return $this->get_username($session->token) != $username;\n });\n }\n}\n\nbut this don't work because you can't use $this inside use, is it possible to execute function which is member of class Service inside a callback? Or do I need to use for or foreach loop?\n\nA: $this is always available in (non-static) closures since PHP 5.4, no need to use it.\nclass Service {\n function delete_user($username) { \n ...\n $sessions = $this->config->sessions;\n $this->config->sessions = array_filter($sessions, function($session) {\n return $this->get_username($session->token) != $username;\n });\n }\n}\n\nSee PHP manual - Anonymous functions - Automatic binding of $this\n"},"original_text":{"kind":"string","value":"Q: How to use $this in closure in php I have function like this:\nclass Service {\n function delete_user($username) { \n ...\n $sessions = $this->config->sessions;\n $this->config->sessions = array_filter($sessions, function($session) use ($this){\n return $this->get_username($session->token) != $username;\n });\n }\n}\n\nbut this don't work because you can't use $this inside use, is it possible to execute function which is member of class Service inside a callback? Or do I need to use for or foreach loop?\n\nA: $this is always available in (non-static) closures since PHP 5.4, no need to use it.\nclass Service {\n function delete_user($username) { \n ...\n $sessions = $this->config->sessions;\n $this->config->sessions = array_filter($sessions, function($session) {\n return $this->get_username($session->token) != $username;\n });\n }\n}\n\nSee PHP manual - Anonymous functions - Automatic binding of $this\n\nA: You can just cast it to something else:\n$a = $this;\n$this->config->sessions = array_filter($sessions, function($session) use ($a, $username){\n return $a->get_username($session->token) != $username;\n});\n\nYou'll also need to pass $username through otherwise it'll always be true.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 158,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845579\",\n \"question_score\": \"23\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482168\"\n}"}}},{"rowIdx":1705681,"cells":{"id":{"kind":"string","value":"60ffaee5d2ce4e5f4d012dcd059ce886ad3613b9"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to slice the file path in Python I am very new to Python as well a programming, and I would like to slice the folder path. For example, if my original path is:\nC:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/\n\nI would like to get the path like this:\nC:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/\n\nWhat are the methods of doing this in Python?\n\nA: You could use the pathlib module:\nfrom pathlib import Path\n\npth = Path('C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/')\n\nprint(pth)\nprint(pth.parent)\nprint(pth.parent.parent) # C:/Users/arul/Desktop/jobs/project_folder\n\nThe module has a lot more of very convenient methods for handling paths: your problem could also be solved using parts like this:\nprint('/'.join(pth.parts[:-2]))\n\nIn Python 2.7 you could build your own parts function using os.path:\nfrom os import path\n\npth = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'\n\ndef parts(pth):\n ret = []\n head, tail = path.split(pth)\n if tail != '':\n ret.append(tail)\n while head != '':\n head, tail = path.split(head)\n ret.append(tail)\n return ret[::-1]\n\nret = path.join(*parts(pth)[:-2])\nprint(ret) # C:/Users/arul/Desktop/jobs/project_folder\n\n"},"original_text":{"kind":"string","value":"Q: How to slice the file path in Python I am very new to Python as well a programming, and I would like to slice the folder path. For example, if my original path is:\nC:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/\n\nI would like to get the path like this:\nC:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/\n\nWhat are the methods of doing this in Python?\n\nA: You could use the pathlib module:\nfrom pathlib import Path\n\npth = Path('C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/')\n\nprint(pth)\nprint(pth.parent)\nprint(pth.parent.parent) # C:/Users/arul/Desktop/jobs/project_folder\n\nThe module has a lot more of very convenient methods for handling paths: your problem could also be solved using parts like this:\nprint('/'.join(pth.parts[:-2]))\n\nIn Python 2.7 you could build your own parts function using os.path:\nfrom os import path\n\npth = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'\n\ndef parts(pth):\n ret = []\n head, tail = path.split(pth)\n if tail != '':\n ret.append(tail)\n while head != '':\n head, tail = path.split(head)\n ret.append(tail)\n return ret[::-1]\n\nret = path.join(*parts(pth)[:-2])\nprint(ret) # C:/Users/arul/Desktop/jobs/project_folder\n\n\nA: If you just want to split on elements, then use this.\n>>> path = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/'\n>>> path.split('elements')[0]\n'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'\n\nOne drawback of this approach is that it'll fail if you encounter the word elements in your path multiple times. In that case, you can do something like:\n>>> '/'.join(path.split('/')[:-3]) + '/'\n'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'\n\nAssuming you know the depth of the path you need.\n\nA: You can do something like this:\nfolder = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/'\n\nfolder.rsplit('/', 3)[0]\n\nstr.rsplit() basically returns a list of the words in the string, separated by the delimiter string (starting from right).\nPlease have a look at documentation for more details on this method.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 253,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845584\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482190\"\n}"}}},{"rowIdx":1705682,"cells":{"id":{"kind":"string","value":"52dbbb8141fd4ac843643bd06e11149b9bffa57b"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Add ARM system image to Android Studio AVD manager I have a 64 bit OS, unfortunately my CPU is not supporting VT-x (as it is an Intel CPU it is not supporting also SVM).\nIt means that normal system image is not usable in Android Studio. Help in Android Studio mentions that one may use \n\nAndroid Virtual Device based on an ARM system image\n\nArmeabi-v7a from \"other images\" is mentioned in Android Studio - How Can I Make an AVD With ARM Instead of HAXM? as one that should work, unfortunately also system images with \"Armeabi-v7a\" ABI are listed as requiring VT-x\n\nHow one may add ARM system image to this list?\nversions: Ubuntu 16.04 64 bit, Android Studio 2.3.3, Intel(R) Core(TM)2 Duo CPU T6600 @ 2.20GHz CPU (according to /proc/cpuinfo)\n"},"original_text":{"kind":"string","value":"Q: Add ARM system image to Android Studio AVD manager I have a 64 bit OS, unfortunately my CPU is not supporting VT-x (as it is an Intel CPU it is not supporting also SVM).\nIt means that normal system image is not usable in Android Studio. Help in Android Studio mentions that one may use \n\nAndroid Virtual Device based on an ARM system image\n\nArmeabi-v7a from \"other images\" is mentioned in Android Studio - How Can I Make an AVD With ARM Instead of HAXM? as one that should work, unfortunately also system images with \"Armeabi-v7a\" ABI are listed as requiring VT-x\n\nHow one may add ARM system image to this list?\nversions: Ubuntu 16.04 64 bit, Android Studio 2.3.3, Intel(R) Core(TM)2 Duo CPU T6600 @ 2.20GHz CPU (according to /proc/cpuinfo)\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 132,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845609\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482279\"\n}"}}},{"rowIdx":1705683,"cells":{"id":{"kind":"string","value":"5fcc08877f6225076da40908eb7683a004981b4d"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Composer branch aliases in different branches I was wondering if the branch-alias property of a composer package differs in different branches. e.g: composer.json of the master branch contains:\n\n\"branch-alias\": {\n \"dev-master\": \"3.0.x-dev\",\n \"dev-foo\": \"3.1.x-dev\n}\n\nand for the foo branch, composer.json contains:\n\n\"branch-alias\": {\n \"dev-master\": 3.0.x-dev,\n \"dev-foo\": \"3.2.x-dev,\n \"dev-bar\": \"3.3.x-dev\n}\n\nNow the following questions need to be answered:\n\n\n*\n\n*What version will the foo branch be aliased as, since the aliases are different in the master and the foo branch? \n\n*Will the bar branch's alias take effect since it is not included in the master branch?\n\n"},"original_text":{"kind":"string","value":"Q: Composer branch aliases in different branches I was wondering if the branch-alias property of a composer package differs in different branches. e.g: composer.json of the master branch contains:\n\n\"branch-alias\": {\n \"dev-master\": \"3.0.x-dev\",\n \"dev-foo\": \"3.1.x-dev\n}\n\nand for the foo branch, composer.json contains:\n\n\"branch-alias\": {\n \"dev-master\": 3.0.x-dev,\n \"dev-foo\": \"3.2.x-dev,\n \"dev-bar\": \"3.3.x-dev\n}\n\nNow the following questions need to be answered:\n\n\n*\n\n*What version will the foo branch be aliased as, since the aliases are different in the master and the foo branch? \n\n*Will the bar branch's alias take effect since it is not included in the master branch?\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 98,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845653\",\n \"question_score\": \"5\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482389\"\n}"}}},{"rowIdx":1705684,"cells":{"id":{"kind":"string","value":"35e8bed7f4e9148aff3de0b6e2b6c2ed06e6bf2e"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 on Windows I have this problem after upgrade AndroidStudio to 3.0 Canary 1\nError:D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml:911 invalid drawable\nError:java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:\nError:Execution failed for task ':app:mergeDebugResources'.\n> Error: java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:\n aapt2 compile -o D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\res\\merged\\debug D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml\n Issues:\n - ERROR: D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml:911 invalid drawable\n\nIt look same \nAAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 but I can not find the way to make it work on Window\nAny help or suggestion would be great appreciated.\n\nA: did you see this https://www.reddit.com/r/androiddev/comments/4u0gw1/support_library_2411_released/\nIf you are using support libraries on version 24.x (you or even your dependencies), this is incompatible with AAPT2 and you should :\n\n\n*\n\n*disbale aapt2 in your gradle.properties file\n:android.enableAapt2=false \n\n*or upgrade google libraries to version 25\nor 26\n\n"},"original_text":{"kind":"string","value":"Q: AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 on Windows I have this problem after upgrade AndroidStudio to 3.0 Canary 1\nError:D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml:911 invalid drawable\nError:java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:\nError:Execution failed for task ':app:mergeDebugResources'.\n> Error: java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:\n aapt2 compile -o D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\res\\merged\\debug D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml\n Issues:\n - ERROR: D:\\Project\\Freelance\\Andoid\\sosokan-android\\sosokan-android\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values\\values.xml:911 invalid drawable\n\nIt look same \nAAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 but I can not find the way to make it work on Window\nAny help or suggestion would be great appreciated.\n\nA: did you see this https://www.reddit.com/r/androiddev/comments/4u0gw1/support_library_2411_released/\nIf you are using support libraries on version 24.x (you or even your dependencies), this is incompatible with AAPT2 and you should :\n\n\n*\n\n*disbale aapt2 in your gradle.properties file\n:android.enableAapt2=false \n\n*or upgrade google libraries to version 25\nor 26\n\n\nA: @Phan Van Linh, can you please check the line from \"values.xml:911\" where you are getting the invalid drawable issue & google it exactly? \nI had the same issue with one of my project and the problematic line was:\n\n\nIt was from an image library I had used in my project. The issue was that I was using an older version of the library. Once I updated to newer version, the error was gone. \nHopefully, your issue might get fixed like mine.\nHappy Hunting!\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 222,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845661\",\n \"question_score\": \"14\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482431\"\n}"}}},{"rowIdx":1705685,"cells":{"id":{"kind":"string","value":"860fba478702792b0a1152294c0cc55cd2fa2f34"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How does a function call give a compile-time type? #include \n\nusing namespace ranges;\n\ntemplate\ntagged_pair\nf(I i, O o)\n{\n return { i, o };\n}\n\nint main()\n{\n char buf[8]{};\n f(std::begin(buf), std::end(buf));\n}\n\nThe code uses range-v3 and can be compiled with clang. \nHowever, I cannot understand why the line tagged_pair is legal. I is a type, tag::in(I) is also a type, and tag::in is not a macro, how does tag::in(I) give a type at compile-time?\nSee also http://en.cppreference.com/w/cpp/experimental/ranges/algorithm/copy\n\nA: It is a type of a function accepting I and returning tag::in, which is also a type.\nThis is used, for example in std::function, like std::function.\n"},"original_text":{"kind":"string","value":"Q: How does a function call give a compile-time type? #include \n\nusing namespace ranges;\n\ntemplate\ntagged_pair\nf(I i, O o)\n{\n return { i, o };\n}\n\nint main()\n{\n char buf[8]{};\n f(std::begin(buf), std::end(buf));\n}\n\nThe code uses range-v3 and can be compiled with clang. \nHowever, I cannot understand why the line tagged_pair is legal. I is a type, tag::in(I) is also a type, and tag::in is not a macro, how does tag::in(I) give a type at compile-time?\nSee also http://en.cppreference.com/w/cpp/experimental/ranges/algorithm/copy\n\nA: It is a type of a function accepting I and returning tag::in, which is also a type.\nThis is used, for example in std::function, like std::function.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 114,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845688\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482513\"\n}"}}},{"rowIdx":1705686,"cells":{"id":{"kind":"string","value":"077cb642bae913a76343bc05359b1c2e2a09df38"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: IBM MobileFirst Platform Installation in Windows 8.1 64Bit I am using my office laptop (Lenovo vV310 - 8GB RAM - 64 Bit OS - Windows 8.1). I have been trying to fix an installation issue with IBM Mobile First Platform for the past few days. I downloaded the IBM Mobile First Developer Kit from link http://public.dhe.ibm.com/ibmdl/export/pub/software/products/en/MobileFirstPlatform/mobilefirst-deved-devkit-windows-8.0.0.0.exe\nThe problem is the installation software InstallAnywhere is not installing and gives the below warning.\nWindows error 2 occured while loading the Java VM\n\nI have JDK 1.8 installed in my notebook and I couldn't fix the issue. I have the java JDK and JRE bin paths set in the environment variables. \nIf any of you have fixed the issue, please share the solution. \n\nA: Open command line as Administrator and type following command.\n[path of mobilefirst-devkit.exe] LAX_VM [\"path of java.exe\"]\n\n\nUsage\n\nC:\\Users\\gaurab\\Downloads\\mobilefirst-deved-devkit-windows-8.0.0.0.exe LAX_VM \"C:\\Program Files\\Java\\jdk1.8.0_112\\bin\\java.exe\"\n\n"},"original_text":{"kind":"string","value":"Q: IBM MobileFirst Platform Installation in Windows 8.1 64Bit I am using my office laptop (Lenovo vV310 - 8GB RAM - 64 Bit OS - Windows 8.1). I have been trying to fix an installation issue with IBM Mobile First Platform for the past few days. I downloaded the IBM Mobile First Developer Kit from link http://public.dhe.ibm.com/ibmdl/export/pub/software/products/en/MobileFirstPlatform/mobilefirst-deved-devkit-windows-8.0.0.0.exe\nThe problem is the installation software InstallAnywhere is not installing and gives the below warning.\nWindows error 2 occured while loading the Java VM\n\nI have JDK 1.8 installed in my notebook and I couldn't fix the issue. I have the java JDK and JRE bin paths set in the environment variables. \nIf any of you have fixed the issue, please share the solution. \n\nA: Open command line as Administrator and type following command.\n[path of mobilefirst-devkit.exe] LAX_VM [\"path of java.exe\"]\n\n\nUsage\n\nC:\\Users\\gaurab\\Downloads\\mobilefirst-deved-devkit-windows-8.0.0.0.exe LAX_VM \"C:\\Program Files\\Java\\jdk1.8.0_112\\bin\\java.exe\"\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 143,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845740\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482679\"\n}"}}},{"rowIdx":1705687,"cells":{"id":{"kind":"string","value":"7847e1b6949a8671014e94e133e668643e736b7a"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Cloud Functions for Firebase - write to database when a new user created I am pretty new Cloud Functions for Firebase and the javascript language. I am trying to add a function every time a user created to write into the database. This is my code:\nconst functions = require('firebase-functions');\nconst admin = require('firebase-admin');\n\nadmin.initializeApp(functions.config().firebase);\n\nexports.addAccount = functions.auth.user().onCreate(event => {\nconst user = event.data; // The firebase user\nconst id = user.uid;\nconst displayName = user.displayName;\nconst photoURL = user.photoURL;\n\nreturn admin.database().ref.child(\"/users/${id}/info/status\").set(\"ok\");} );\n\nwhat I am trying to do is every time a user signup to my app, the functions wil write into the database that his status is \"OK\". But my code dosn't work.\n\nwhat am I doing wrong?\n\nA: I found the problem. The problem is that shouldn't use the ${id}, and I shouldn't have use the child. So the code should look like this:\nconst functions = require('firebase-functions');\nconst admin = require('firebase-admin');\n\nadmin.initializeApp(functions.config().firebase);\n\nexports.addAccount = functions.auth.user().onCreate(event => {\n const user = event.data; // The firebase user\n const id = user.uid;\n const displayName = user.displayName;\n const photoURL = user.photoURL;\n\n return admin.database().ref(\"/users/\"+id+\"/info/status\").set(\"ok\"); \n});\n\n"},"original_text":{"kind":"string","value":"Q: Cloud Functions for Firebase - write to database when a new user created I am pretty new Cloud Functions for Firebase and the javascript language. I am trying to add a function every time a user created to write into the database. This is my code:\nconst functions = require('firebase-functions');\nconst admin = require('firebase-admin');\n\nadmin.initializeApp(functions.config().firebase);\n\nexports.addAccount = functions.auth.user().onCreate(event => {\nconst user = event.data; // The firebase user\nconst id = user.uid;\nconst displayName = user.displayName;\nconst photoURL = user.photoURL;\n\nreturn admin.database().ref.child(\"/users/${id}/info/status\").set(\"ok\");} );\n\nwhat I am trying to do is every time a user signup to my app, the functions wil write into the database that his status is \"OK\". But my code dosn't work.\n\nwhat am I doing wrong?\n\nA: I found the problem. The problem is that shouldn't use the ${id}, and I shouldn't have use the child. So the code should look like this:\nconst functions = require('firebase-functions');\nconst admin = require('firebase-admin');\n\nadmin.initializeApp(functions.config().firebase);\n\nexports.addAccount = functions.auth.user().onCreate(event => {\n const user = event.data; // The firebase user\n const id = user.uid;\n const displayName = user.displayName;\n const photoURL = user.photoURL;\n\n return admin.database().ref(\"/users/\"+id+\"/info/status\").set(\"ok\"); \n});\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 185,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845773\",\n \"question_score\": \"15\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482792\"\n}"}}},{"rowIdx":1705688,"cells":{"id":{"kind":"string","value":"b86868f1e8dd02282362945fab7d80fe1a7f27b5"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: NoUiSlider not visible I am truing to use noUiSlider in my react application. I have done the initialization in my componentDidMount method but noUiSlider is not visibble. I am not getting any error in console. The element list also shows that nouislider is present on page, but I cannot see it.\nimport noUiSlider from 'nouislider'\n\n\nclass AppBarComponent extends Component {\ncomponentDidMount(){\n\n var noUi_slider = document.getElementById('noUiSlider');\n\n $(function () {\n\n noUiSlider.create(noUi_slider, {\n start: [20, 80],\n connect: true,\n range: {\n 'min': 0,\n 'max': 100\n }\n });\n}\n\ncomponentWillUnmount(){}\n\n\nrender() {\n return (\n\n
\n
\n
\n);\n}\n};\n\n\nA: Your first arg to create is \"noUi_slider\"\nbut your div id is \"noUiSlider\"\nSpell these exactly the same.\n"},"original_text":{"kind":"string","value":"Q: NoUiSlider not visible I am truing to use noUiSlider in my react application. I have done the initialization in my componentDidMount method but noUiSlider is not visibble. I am not getting any error in console. The element list also shows that nouislider is present on page, but I cannot see it.\nimport noUiSlider from 'nouislider'\n\n\nclass AppBarComponent extends Component {\ncomponentDidMount(){\n\n var noUi_slider = document.getElementById('noUiSlider');\n\n $(function () {\n\n noUiSlider.create(noUi_slider, {\n start: [20, 80],\n connect: true,\n range: {\n 'min': 0,\n 'max': 100\n }\n });\n}\n\ncomponentWillUnmount(){}\n\n\nrender() {\n return (\n\n
\n
\n
\n);\n}\n};\n\n\nA: Your first arg to create is \"noUi_slider\"\nbut your div id is \"noUiSlider\"\nSpell these exactly the same.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 117,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845777\",\n \"question_score\": \"5\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482803\"\n}"}}},{"rowIdx":1705689,"cells":{"id":{"kind":"string","value":"c7604595bf4138fa79b25fbd18f3215e64525882"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Can you implement PayPal Adaptive Payments with the Customer Leaving Your Site? Is there any way to implement PayPal Adaptive Payments without the customer ever leaving your site? \nThe documentation outlines using an embedded lightbox, but unless the user is already logged in to PayPal (which they almost never are), then it just opens a new window. Theres also no way to control how the lightbox / iframe is displayed - and it looks terrible!\nI have seen on some sites where the PayPal payments form is embedded in an iframe on a page, but I can't see any documentation supporting that.\nI'd be happy to pay for Payments Pro if that would enable it - but I cant find any examples / samples that show using Payments Pro with Adaptive Payments.\nAny help or pointers would be greatly appreciated.\nMatt\n\nA: You can also dynamically select your hosted pages Layout template using the form post TEMPLATE parameter. This will override your default Layout template set in PayPal Manager. \n"},"original_text":{"kind":"string","value":"Q: Can you implement PayPal Adaptive Payments with the Customer Leaving Your Site? Is there any way to implement PayPal Adaptive Payments without the customer ever leaving your site? \nThe documentation outlines using an embedded lightbox, but unless the user is already logged in to PayPal (which they almost never are), then it just opens a new window. Theres also no way to control how the lightbox / iframe is displayed - and it looks terrible!\nI have seen on some sites where the PayPal payments form is embedded in an iframe on a page, but I can't see any documentation supporting that.\nI'd be happy to pay for Payments Pro if that would enable it - but I cant find any examples / samples that show using Payments Pro with Adaptive Payments.\nAny help or pointers would be greatly appreciated.\nMatt\n\nA: You can also dynamically select your hosted pages Layout template using the form post TEMPLATE parameter. This will override your default Layout template set in PayPal Manager. \n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 170,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845778\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482805\"\n}"}}},{"rowIdx":1705690,"cells":{"id":{"kind":"string","value":"cd3a0d94fd451c3dacc8fdbeb65ac0b689a955e0"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: MediaSource does not support ogg audio? MediaSource.isTypeSupported('audio/ogg; codecs=\"vorbis\"') return false - is it mean that I can not stream ogg as a response from POST?\n\nA: That's exactly what it means. The clients which return false for this condition cannot play this media type (older browsers, unsupported OS or client settings which prevent this).\nFor streaming OGG file formats you can definitly use Audio.play(); on most modern browsers, but unfortunately the MediaSource element does not support streaming with POST request - you would have to use the classic streaming method, or download the entire source file as a whole and then play it.\n"},"original_text":{"kind":"string","value":"Q: MediaSource does not support ogg audio? MediaSource.isTypeSupported('audio/ogg; codecs=\"vorbis\"') return false - is it mean that I can not stream ogg as a response from POST?\n\nA: That's exactly what it means. The clients which return false for this condition cannot play this media type (older browsers, unsupported OS or client settings which prevent this).\nFor streaming OGG file formats you can definitly use Audio.play(); on most modern browsers, but unfortunately the MediaSource element does not support streaming with POST request - you would have to use the classic streaming method, or download the entire source file as a whole and then play it.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 104,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845821\",\n \"question_score\": \"14\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44482967\"\n}"}}},{"rowIdx":1705691,"cells":{"id":{"kind":"string","value":"566e6079b07448344a0f763917fbef6ed6e9342f"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: How to bind a click event on “v-html” in Vue I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way?\nhttps://jsfiddle.net/limingyang/bnLmx1en/1/\n\n
\n
\n
\n\nvar app = new Vue({\n el: '#app',\n data: {\n link: 'click me'\n }\n})\n\n\nA: You can add a ref on your div, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted hook:\n\n\nvar app = new Vue({\n el: '#app',\n data: {\n link: 'click me'\n },\n mounted() {\n this.$refs['mydiv'].firstChild.addEventListener('click', function(event) {\n event.preventDefault();\n console.log('clicked: ', event.target);\n })\n }\n})\n\n
\n
\n
\n\n\n"},"original_text":{"kind":"string","value":"Q: How to bind a click event on “v-html” in Vue I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way?\nhttps://jsfiddle.net/limingyang/bnLmx1en/1/\n\n
\n
\n
\n\nvar app = new Vue({\n el: '#app',\n data: {\n link: 'click me'\n }\n})\n\n\nA: You can add a ref on your div, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted hook:\n\n\nvar app = new Vue({\n el: '#app',\n data: {\n link: 'click me'\n },\n mounted() {\n this.$refs['mydiv'].firstChild.addEventListener('click', function(event) {\n event.preventDefault();\n console.log('clicked: ', event.target);\n })\n }\n})\n\n
\n
\n
\n\n\n\nA: For people having problem with @tony19 solution:\nIf your v-html is dynamically updated and you want to do something on the element you have to use\nVue.nextTick(() => {});\n\nBecause you have to wait for the DOM to create the element before accessing its child nodes.\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 197,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845870\",\n \"question_score\": \"21\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483117\"\n}"}}},{"rowIdx":1705692,"cells":{"id":{"kind":"string","value":"b9ce9139faa98df52f0459b73756ed473516f0ab"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: how to escape quotes in gremlin queries I have this query and as you firstName contains single quote Anthony O'Neil\n:> g.addV('person')\n .property('firstName', 'Anthony O'Neil')\n .property('lastName', 'Andersen')\n .property('age', 44)\n\nAny Ideas how to escape it?\n\nA: Escape the apostrophe using \\\nSo your Gremlin becomes:\n:> g.addV('person')\n .property('firstName', 'Anthony O\\'Neil')\n .property('lastName', 'Andersen')\n .property('age', 44)\n\n"},"original_text":{"kind":"string","value":"Q: how to escape quotes in gremlin queries I have this query and as you firstName contains single quote Anthony O'Neil\n:> g.addV('person')\n .property('firstName', 'Anthony O'Neil')\n .property('lastName', 'Andersen')\n .property('age', 44)\n\nAny Ideas how to escape it?\n\nA: Escape the apostrophe using \\\nSo your Gremlin becomes:\n:> g.addV('person')\n .property('firstName', 'Anthony O\\'Neil')\n .property('lastName', 'Andersen')\n .property('age', 44)\n\n\nA: Found out the answer\nfor encoding use this:\nencodeURIComponent(\"Anthony O'Neil\").replace(/[!'()*]/g, escape)\nand the output is: Anthony%20O%27Neil\nfor decoding use this:\ndecodeURIComponent(\"Anthony%20O%27Neil\")\nand you will get back Anthony O'Neil\nif you just want to escape the single quote use this for encoding:\n\"Anthony O'Neill\".replace(/[!'()*]/g, escape)\noutput: Anthony O%27Neill\nand the same function above for decoding\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 110,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845891\",\n \"question_score\": \"6\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483185\"\n}"}}},{"rowIdx":1705693,"cells":{"id":{"kind":"string","value":"255a4d8675032f30271a26e1f2622f6cc00726a5"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Is using batch size as 'powers of 2' faster on tensorflow? I read from somewhere that if you choose a batch size that is a power 2, training will be faster. What is this rule? Is this applicable to other applications? Can you provide a reference paper?\n\nA: \nThe notion comes from aligning computations (C) onto the physical\n processors (PP) of the GPU.\n\nSince the number of PP is often a power of 2, using a number of C different from a power of 2 leads to poor performance.\nYou can see the mapping of the C onto the PP as a pile of slices of size the number of PP.\nSay you've got 16 PP.\nYou can map 16 C on them : 1 C is mapped onto 1 PP.\nYou can map 32 C on them : 2 slices of 16 C , 1 PP will be responsible for 2 C.\nThis is due to the SIMD paradigm used by GPUs. This is often called Data Parallelism : all the PP do the same thing at the same time but on different data.\n"},"original_text":{"kind":"string","value":"Q: Is using batch size as 'powers of 2' faster on tensorflow? I read from somewhere that if you choose a batch size that is a power 2, training will be faster. What is this rule? Is this applicable to other applications? Can you provide a reference paper?\n\nA: \nThe notion comes from aligning computations (C) onto the physical\n processors (PP) of the GPU.\n\nSince the number of PP is often a power of 2, using a number of C different from a power of 2 leads to poor performance.\nYou can see the mapping of the C onto the PP as a pile of slices of size the number of PP.\nSay you've got 16 PP.\nYou can map 16 C on them : 1 C is mapped onto 1 PP.\nYou can map 32 C on them : 2 slices of 16 C , 1 PP will be responsible for 2 C.\nThis is due to the SIMD paradigm used by GPUs. This is often called Data Parallelism : all the PP do the same thing at the same time but on different data.\n\nA: Algorithmically speaking, using larger mini-batches allows you to reduce the variance of your stochastic gradient updates (by taking the average of the gradients in the mini-batch), and this in turn allows you to take bigger step-sizes, which means the optimization algorithm will make progress faster.\nHowever, the amount of work done (in terms of number of gradient computations) to reach a certain accuracy in the objective will be the same: with a mini-batch size of n, the variance of the update direction will be reduced by a factor n, so the theory allows you to take step-sizes that are n times larger, so that a single step will take you roughly to the same accuracy as n steps of SGD with a mini-batch size of 1.\nAs for tensorFlow, I found no evidence of your affirmation, and its a question that has been closed on github : https://github.com/tensorflow/tensorflow/issues/4132\nNote that image resized to power of two makes sense (because pooling is generally done in 2X2 windows), but that’s a different thing altogether.\n\nA: I've heard this, too. Here's a white paper about training on CIFAR-10 where some Intel researchers make the claim:\n\nIn general, the performance of processors is better if the batch size is a power of 2.\n\n(See: https://software.intel.com/en-us/articles/cifar-10-classification-using-intel-optimization-for-tensorflow.)\nHowever, it's unclear just how big the advantage may be because the authors don't provide any training duration data :/\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 418,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845906\",\n \"question_score\": \"19\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483233\"\n}"}}},{"rowIdx":1705694,"cells":{"id":{"kind":"string","value":"8501e630e581b537ea635f2de8f768f78d5b3f8e"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: What is the data type of a single character in a string as an array? string s;\ncin>>s;\n\nsuppose s = \"stackoverflow\" \nnow if we access s[3], it should give out 'c'\nwill s[3] be 'c' or \"c\"?\nas in will it be a char data type or string data type?\n\nA: It returns reference to the character as the operator [] is overloaded for std::string\nchar& operator[] (size_t pos);\nconst char& operator[] (size_t pos) const;\n\n\nwill s[3] be 'c' or \"c\"?\n\nCharacter 'c', not string \"c\".\n"},"original_text":{"kind":"string","value":"Q: What is the data type of a single character in a string as an array? string s;\ncin>>s;\n\nsuppose s = \"stackoverflow\" \nnow if we access s[3], it should give out 'c'\nwill s[3] be 'c' or \"c\"?\nas in will it be a char data type or string data type?\n\nA: It returns reference to the character as the operator [] is overloaded for std::string\nchar& operator[] (size_t pos);\nconst char& operator[] (size_t pos) const;\n\n\nwill s[3] be 'c' or \"c\"?\n\nCharacter 'c', not string \"c\".\n\nA: std::string is not a built-in type, so operator [] in s[3] is a call to a member function defining this operator in the string template.\nYou can find the type by looking up the reference page for operator []:\n\nReturns a reference to the character at specified location pos.\n\nTo look up the type reference and const_reference from the documentation see \"member types\" section of std::basic_string template.\nIf you are looking for std::string of length 1 starting at location 3, use substr instead:\ns.substr(3, 1); // This produces std::string containing \"c\"\n\n\nA: It is easiest to remember that std::string is not a native type like char is, but a wrapper class that contains an array of chars to form a string.\nstd::string simply overloads the C array operator [] to return the char at a given index, hence:\n\nwill s[3] be 'c' or \"c\"?\nAnswer: 'c'\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 235,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845908\",\n \"question_score\": \"4\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483247\"\n}"}}},{"rowIdx":1705695,"cells":{"id":{"kind":"string","value":"0e16ae9cfcfa6765a07edd9137e87b9fffc1e0ef"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Next Button like Navigation's Back Button I want to display Next Button just like Back Button but the rightBarButton does not touch to end of the screen like the back barButton.\n let button = UIButton(type: .system)\n button.setImage(UIImage(named: \"ic_next_button\"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x\n button.setTitle(\"Next\", for: .normal)\n button.sizeToFit()\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)\n\n\n\nA: As the previous answer pointed out, all you need to do is to add a negative fixed space to the left of your nextButton and it will be pushed to the right.\nThis code creates a negative fixed width of 8 points (which seems enough in your case, but feel free to adapt as you need):\nlet negativeWidthButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, \n target: nil, \n action: nil)\nnegativeWidthButtonItem.width = -8\n\nAfter creating this button, add it to the rightBarButtonItems array:\nself.navigationItem.rightBarButtonItems = [negativeWidthButtonItem, nextButton]\n\nSome other answers on StackOverflow also refer to the same solution:\n\n\n*\n\n*reduce left space and right space from navigation bar left and right bar button item\n\n*How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]\n"},"original_text":{"kind":"string","value":"Q: Next Button like Navigation's Back Button I want to display Next Button just like Back Button but the rightBarButton does not touch to end of the screen like the back barButton.\n let button = UIButton(type: .system)\n button.setImage(UIImage(named: \"ic_next_button\"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x\n button.setTitle(\"Next\", for: .normal)\n button.sizeToFit()\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)\n\n\n\nA: As the previous answer pointed out, all you need to do is to add a negative fixed space to the left of your nextButton and it will be pushed to the right.\nThis code creates a negative fixed width of 8 points (which seems enough in your case, but feel free to adapt as you need):\nlet negativeWidthButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, \n target: nil, \n action: nil)\nnegativeWidthButtonItem.width = -8\n\nAfter creating this button, add it to the rightBarButtonItems array:\nself.navigationItem.rightBarButtonItems = [negativeWidthButtonItem, nextButton]\n\nSome other answers on StackOverflow also refer to the same solution:\n\n\n*\n\n*reduce left space and right space from navigation bar left and right bar button item\n\n*How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]\n\nA: Create another UIBarButtonItem with type of .fixedSpace and some negative value as width. Then add both buttons as right bar button item.\n let button = UIButton(type: .system)\n button.setImage(UIImage(named: \"right\"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x\n button.setTitle(\"Next\", for: .normal)\n button.sizeToFit()\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n let nextBtn = UIBarButtonItem(customView: button)\n let spaceBtn = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)\n spaceBtn.width = -8// Change this value as per your need\n self.navigationItem.rightBarButtonItems = [spaceBtn, nextBtn];\n\n\nA: Adding UIBarButtonSystemItem.fixedSpace will occupy the extra space before the BarButtonItem. \n let button = UIButton(type: .system)\n button.setImage(UIImage(named: \"ic_next_button\"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x\n button.setTitle(\"Next\", for: .normal)\n button.sizeToFit()\n button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)\n\n let rightBarButton = UIBarButtonItem()\n rightBarButton.customView = button\n\n let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)\n negativeSpacer.width = -25;\n\n self.navigationItem.setRightBarButtonItems([negativeSpacer, rightBarButton ], animated: false)\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 359,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:845910\",\n \"question_score\": \"7\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483249\"\n}"}}},{"rowIdx":1705696,"cells":{"id":{"kind":"string","value":"87c57d71610ff7acf43f7dae60544222d38d1261"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: Angular4 CLI change favicon.ico to favicon.svg I started to learn Angular 4 and try to remake one site using Angilar4 CLI.\nNow I have a problem with new favicon that I drew in svg. I wrote this in index.html\n\n\nAnd I deleted favicon.ico because it has been shown every time though I changed file.\nAlso I rewrote .angular-cli.json I changed \n\"assets\": [\n \"assets\",\n \"favicon.ico\"\n]\n\nto\n\"assets\": [\n \"assets\",\n \"favicon.svg\"\n]\n\nThe favicon.svg is 16*16 px sized.\n\nA: Finally I found the problem.\nhttps://caniuse.com/#search=favicon\nThere we can see that chrome just doesn't support svg favicons\n"},"original_text":{"kind":"string","value":"Q: Angular4 CLI change favicon.ico to favicon.svg I started to learn Angular 4 and try to remake one site using Angilar4 CLI.\nNow I have a problem with new favicon that I drew in svg. I wrote this in index.html\n\n\nAnd I deleted favicon.ico because it has been shown every time though I changed file.\nAlso I rewrote .angular-cli.json I changed \n\"assets\": [\n \"assets\",\n \"favicon.ico\"\n]\n\nto\n\"assets\": [\n \"assets\",\n \"favicon.svg\"\n]\n\nThe favicon.svg is 16*16 px sized.\n\nA: Finally I found the problem.\nhttps://caniuse.com/#search=favicon\nThere we can see that chrome just doesn't support svg favicons\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 101,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:846008\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483580\"\n}"}}},{"rowIdx":1705697,"cells":{"id":{"kind":"string","value":"b858f09d0ba53a2a9d9f0fc11fc26bb34609196f"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: PyCharm PEP8 on save So I have googled, I have SO'd, I have tried...\nHow can I get PyCharm to do PEP8 auto format as an on save action?\nI found that I can do Ctrl+Alt+L to do auto formatting. I got used to having that as on save action on eclipse, so I'd like that in PyCharm. It was easy to do in GoGland, so why not in PyCharm?\nI'm lost, please help...\n\nA: So what worked for me was roundabout but I haven't found an easy built in option to do this. My solution was to record a macro of format and save and then reassign the ctrl+s keybinding to that macro.\nTo make the macro:\n- Edit>Macros>Start Recording\n- Run ctrl+alt+L and then ctrl+s \n- Edit>Macros>Stop Recording>call it something like save and format\nTo reassign ctrl+s:\n- Settings>Keymap>Macros:\n - Select your macro and 'Add Keyboard Shortcut' and enter ctrl+s\n - Opt to remove it from save since your macro does that anyway\nDocumentation that goes into more detail:\nhttps://www.jetbrains.com/help/pycharm/recording-macros.html\nhttps://www.jetbrains.com/help/pycharm/binding-macros-with-keyboard-shortcuts.html\n"},"original_text":{"kind":"string","value":"Q: PyCharm PEP8 on save So I have googled, I have SO'd, I have tried...\nHow can I get PyCharm to do PEP8 auto format as an on save action?\nI found that I can do Ctrl+Alt+L to do auto formatting. I got used to having that as on save action on eclipse, so I'd like that in PyCharm. It was easy to do in GoGland, so why not in PyCharm?\nI'm lost, please help...\n\nA: So what worked for me was roundabout but I haven't found an easy built in option to do this. My solution was to record a macro of format and save and then reassign the ctrl+s keybinding to that macro.\nTo make the macro:\n- Edit>Macros>Start Recording\n- Run ctrl+alt+L and then ctrl+s \n- Edit>Macros>Stop Recording>call it something like save and format\nTo reassign ctrl+s:\n- Settings>Keymap>Macros:\n - Select your macro and 'Add Keyboard Shortcut' and enter ctrl+s\n - Opt to remove it from save since your macro does that anyway\nDocumentation that goes into more detail:\nhttps://www.jetbrains.com/help/pycharm/recording-macros.html\nhttps://www.jetbrains.com/help/pycharm/binding-macros-with-keyboard-shortcuts.html\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 174,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:846051\",\n \"question_score\": \"11\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483748\"\n}"}}},{"rowIdx":1705698,"cells":{"id":{"kind":"string","value":"9905b6359454820efbb4fb4ccd9117b41df9847e"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: NetShareGetInfo doesn't return permissions I've shared a directory with the (OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ) permissions, but when I call NetShareGetInfo on the share, the permissions are 0 (while all of the other fields are correct).\nCode:\n /* Initialize the share info structure */\n tShareInfo.shi2_netname = pwstrNetName;\n tShareInfo.shi2_type = STYPE_DISKTREE;\n tShareInfo.shi2_remark = L\"\";\n tShareInfo.shi2_permissions = OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ;\n tShareInfo.shi2_max_uses = (DWORD)-1;\n tShareInfo.shi2_current_uses = 0;\n tShareInfo.shi2_path = pwstrPath;\n tShareInfo.shi2_passwd = NULL; \n\n /* Add the share */\n eResult = NetShareAdd(NULL, 2, (LPBYTE)&tShareInfo, &dwError);\n if (NERR_Success != eResult)\n {\n printf(\"Failed sharing\\n\");\n goto lbl_cleanup;\n }\n eResult = NetShareGetInfo(NULL, pwstrNetName, 2, (LPBYTE *)&ptShareInfo);\n if (NERR_Success == eResult)\n {\n printf(\"Path: %s\\n\", ptShareInfo->shi2_path);\n printf(\"Permissions: %d\\n\", ptShareInfo->shi2_permissions);\n }\n\nWhat can be the problem here?\n"},"original_text":{"kind":"string","value":"Q: NetShareGetInfo doesn't return permissions I've shared a directory with the (OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ) permissions, but when I call NetShareGetInfo on the share, the permissions are 0 (while all of the other fields are correct).\nCode:\n /* Initialize the share info structure */\n tShareInfo.shi2_netname = pwstrNetName;\n tShareInfo.shi2_type = STYPE_DISKTREE;\n tShareInfo.shi2_remark = L\"\";\n tShareInfo.shi2_permissions = OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ;\n tShareInfo.shi2_max_uses = (DWORD)-1;\n tShareInfo.shi2_current_uses = 0;\n tShareInfo.shi2_path = pwstrPath;\n tShareInfo.shi2_passwd = NULL; \n\n /* Add the share */\n eResult = NetShareAdd(NULL, 2, (LPBYTE)&tShareInfo, &dwError);\n if (NERR_Success != eResult)\n {\n printf(\"Failed sharing\\n\");\n goto lbl_cleanup;\n }\n eResult = NetShareGetInfo(NULL, pwstrNetName, 2, (LPBYTE *)&ptShareInfo);\n if (NERR_Success == eResult)\n {\n printf(\"Path: %s\\n\", ptShareInfo->shi2_path);\n printf(\"Permissions: %d\\n\", ptShareInfo->shi2_permissions);\n }\n\nWhat can be the problem here?\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 119,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:846054\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483752\"\n}"}}},{"rowIdx":1705699,"cells":{"id":{"kind":"string","value":"c65b9cde8c316cc6eeea43aa947a49fe213452b1"},"text":{"kind":"string","value":"Stackoverflow Stackexchange\n\nQ: In R how to remove small community from igraph in R network graph how to remove small community of twos (two nodes connected with one edge and no connection with other nodes, like jane and ike in this example:\nlibrary(igraph)\ng <- graph_from_literal(Andre----Beverly:Diane:Fernando\n Beverly--Garth:Ed,\n Carol----Andre:Diane:Fernando,\n Diane----Andre:Carol:Fernando:Beverly,\n Fernando-Carol:Andre:Diane:Heather,\n Jane-----Ike )\nplot(g, vertex.label.color=\"blue\", vertex.label.cex=1.5,\n vertex.label.font=2, vertex.size=25, vertex.color=\"white\",\n vertex.frame.color=\"white\", edge.color=\"black\")\n\n\nA: Here's a possible solution using components to find subgraphs and then doing some counting. You could also look into functions from igraph such as groups and sizes to do these operations of getting subgraph vertex count and vertex names.\nlibrary(igraph)\ng <- graph_from_literal(Andre----Beverly:Diane:Fernando,\n Beverly--Garth:Ed,\n Carol----Andre:Diane:Fernando,\n Diane----Andre:Carol:Fernando:Beverly,\n Fernando-Carol:Andre:Diane:Heather,\n Jane-----Ike )\n\n#get all subgraphs\nsub_gs <- components(g)$membership\n\n#find which subgraphs have 2 nodes\nsmall_sub <- names(which(table(sub_gs) == 2))\n\n#get names of nodes to rm\n(rm_nodes <- names(which(sub_gs == small_sub)))\n# [1] \"Jane\" \"Ike\" \n\n#remove nodes by name\ng2 <- delete_vertices(g, rm_nodes)\n\n"},"original_text":{"kind":"string","value":"Q: In R how to remove small community from igraph in R network graph how to remove small community of twos (two nodes connected with one edge and no connection with other nodes, like jane and ike in this example:\nlibrary(igraph)\ng <- graph_from_literal(Andre----Beverly:Diane:Fernando\n Beverly--Garth:Ed,\n Carol----Andre:Diane:Fernando,\n Diane----Andre:Carol:Fernando:Beverly,\n Fernando-Carol:Andre:Diane:Heather,\n Jane-----Ike )\nplot(g, vertex.label.color=\"blue\", vertex.label.cex=1.5,\n vertex.label.font=2, vertex.size=25, vertex.color=\"white\",\n vertex.frame.color=\"white\", edge.color=\"black\")\n\n\nA: Here's a possible solution using components to find subgraphs and then doing some counting. You could also look into functions from igraph such as groups and sizes to do these operations of getting subgraph vertex count and vertex names.\nlibrary(igraph)\ng <- graph_from_literal(Andre----Beverly:Diane:Fernando,\n Beverly--Garth:Ed,\n Carol----Andre:Diane:Fernando,\n Diane----Andre:Carol:Fernando:Beverly,\n Fernando-Carol:Andre:Diane:Heather,\n Jane-----Ike )\n\n#get all subgraphs\nsub_gs <- components(g)$membership\n\n#find which subgraphs have 2 nodes\nsmall_sub <- names(which(table(sub_gs) == 2))\n\n#get names of nodes to rm\n(rm_nodes <- names(which(sub_gs == small_sub)))\n# [1] \"Jane\" \"Ike\" \n\n#remove nodes by name\ng2 <- delete_vertices(g, rm_nodes)\n\n\nA: We can use induced_subgraph + membership like below to filterout the clusters of small size (e.g., size 2 or even smaller)\ninduced_subgraph(\n g,\n V(g)[ave(1:vcount(g), membership(components(g)), FUN = length) > 2]\n)\n\n"},"subdomain":{"kind":"string","value":"stackoverflow"},"metadata":{"kind":"string","value":"{\n \"language\": \"en\",\n \"length\": 180,\n \"provenance\": \"stackexchange_0000F.jsonl.gz:846078\",\n \"question_score\": \"3\",\n \"source\": \"stackexchange\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"url\": \"https://stackoverflow.com/questions/44483836\"\n}"}}}],"truncated":false,"partial":true},"paginationData":{"pageIndex":17056,"numItemsPerPage":100,"numTotalItems":1709447,"offset":1705600,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzg4ODgzNiwic3ViIjoiL2RhdGFzZXRzL210ZWIvYXJlbmEtc3RhY2tleGNoYW5nZSIsImV4cCI6MTc1Nzg5MjQzNiwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.CaLEbz6iLpUVAZxVqfTHTEDK8B3qw8Iih6CxfbhbftL-ZxATpl8lS6RFFIRvjBdBwGnsWm5H-U67IFnUM53GAw","displayUrls":true},"discussionsStats":{"closed":1,"open":1,"total":2},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
0445c8e02028d0f5040e17ea527ede10089081ef
Stackoverflow Stackexchange Q: method Attribute on C# expression-bodied member Is there any way to specify an AttributeTargets.Method attribute on an expression-bodied member in C# 6? Consider the following read-only property: public bool IsLast { [DebuggerStepThrough] get { return _next == null; } } The abbreviated synax would be: public bool IsLast => _next == null; But there appears to be nowhere to put the method attribute. None of the following work: [DebuggerStepThrough] public bool IsLast => _next == null; // decorates property, not method public bool IsLast => [DebuggerStepThrough] _next == null; // error public bool IsLast [DebuggerStepThrough] => _next == null; // error [Edit:] Suggesting that this is not a duplicate of 'Skip expression bodied property in debugger' since this question asks about any method-suitable attribute in general, rather than just the DebuggerStepThrough attribute--which is only given as an example here--in particular. A: You can apply an AttributeTargets.Method attribute to an expression-bodied method, but not to an expression-bodied property.
Q: method Attribute on C# expression-bodied member Is there any way to specify an AttributeTargets.Method attribute on an expression-bodied member in C# 6? Consider the following read-only property: public bool IsLast { [DebuggerStepThrough] get { return _next == null; } } The abbreviated synax would be: public bool IsLast => _next == null; But there appears to be nowhere to put the method attribute. None of the following work: [DebuggerStepThrough] public bool IsLast => _next == null; // decorates property, not method public bool IsLast => [DebuggerStepThrough] _next == null; // error public bool IsLast [DebuggerStepThrough] => _next == null; // error [Edit:] Suggesting that this is not a duplicate of 'Skip expression bodied property in debugger' since this question asks about any method-suitable attribute in general, rather than just the DebuggerStepThrough attribute--which is only given as an example here--in particular. A: You can apply an AttributeTargets.Method attribute to an expression-bodied method, but not to an expression-bodied property. A: Answering my own question: The following syntax works but it is not quite as compact as the (non-working) attempts shown in the question. public bool IsLast { [DebuggerStepThrough] get => _next == null; }
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:844277", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478148" }
8b5b51a53bd0fd8a6f20c34909ba2e1c3543bf14
Stackoverflow Stackexchange Q: How does FirstAsync work? In my everlasting quest to suck less I'm trying to understand Rx.net's FirstAsync() syntax. Most documentation is for the deprecated First() If I understand correctly it allows me to start a stream as soon as the first element from a stream arrives. Say I have a stream myStream and I want to start a stream that takes the first element and starts a stream based on that one element. In my case it would be a stream of one. I expect it to do this: ---1-2-> ---A---> How would I go about this? myStream.FirstAsync().Return(() => return "A"); // doesn't compile A: I don't know why the other two answers are saying .FirstAsync() returns a Task (or that you should call .Result). It does not return a Task, it returns an IObservable<TSource>. Observables are awaitable, but they are not tasks. To achieve your desired functionality, do the following: myStream.FirstAsync().Select(_ => "A"). You can also do myStream.Take(1).Select(_ => "A"). The difference between this and the FirstAsync version, is that the FirstAsync version will throw an exception if myStream completes without any elements. Take(1) will complete with no error.
Q: How does FirstAsync work? In my everlasting quest to suck less I'm trying to understand Rx.net's FirstAsync() syntax. Most documentation is for the deprecated First() If I understand correctly it allows me to start a stream as soon as the first element from a stream arrives. Say I have a stream myStream and I want to start a stream that takes the first element and starts a stream based on that one element. In my case it would be a stream of one. I expect it to do this: ---1-2-> ---A---> How would I go about this? myStream.FirstAsync().Return(() => return "A"); // doesn't compile A: I don't know why the other two answers are saying .FirstAsync() returns a Task (or that you should call .Result). It does not return a Task, it returns an IObservable<TSource>. Observables are awaitable, but they are not tasks. To achieve your desired functionality, do the following: myStream.FirstAsync().Select(_ => "A"). You can also do myStream.Take(1).Select(_ => "A"). The difference between this and the FirstAsync version, is that the FirstAsync version will throw an exception if myStream completes without any elements. Take(1) will complete with no error. A: In answer to "How does FirstAsync work?": It returns a new IObservable<T> that contains either: * *The first item from the source stream (when it eventually produces one), followed by a complete. *or, if the source stream completes without producing an item, an exception (via OnError), which you would need to handle with a Catch or in your Subscribe etc. If you would rather a get a default value instead of an exception when the source completes without ever producing a first item, use FirstOrDefaultAsync
stackoverflow
{ "language": "en", "length": 277, "provenance": "stackexchange_0000F.jsonl.gz:844280", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478157" }
a5d10a2f02c7b3ee0ad5c8be673e40823da484c6
Stackoverflow Stackexchange Q: How can I return a Flux when my response is wrapped in a json pagination object with Spring 5? I've got a web service that I'm trying to consume with the new Spring 5 WebClient. Working example # GET /orders/ [ { orderId: 1, ... }, { orderId: 1, ... } ] And the java code for the call // Java Flux<Order> ordersStream = webClient.get() .uri("/orders/") .exchange() .flatMap(response -> response.bodyToFlux(Order.class)); Problem The response from the web service is paginated and therefore doesn't contain the list of items directly as in the example above. It looks like this # GET /orders/ { "error": null, "metadata": { "total": 998, "limit": 1000, "offset": 0 }, "data": [ { orderId: 1, ... }, { orderId: 2, ... }, ] } How can I get the sub key "data" as a Flux<Order>? Possible solution, but I don't know if it's the best approach... Create a wrapper class and convert the wrappers .data to a flux. But now we need to deserialize the whole response at once, potentially running out of memory. // Java Flux<Order> ordersStream = webClient.get() .uri("/orders/") .exchange() .flatMap(response -> response.bodyToMono(PageWrapper.class)) .flatMapMany(wrapper -> Flux.fromIterable(wrapper.data)); Is there a better way?
Q: How can I return a Flux when my response is wrapped in a json pagination object with Spring 5? I've got a web service that I'm trying to consume with the new Spring 5 WebClient. Working example # GET /orders/ [ { orderId: 1, ... }, { orderId: 1, ... } ] And the java code for the call // Java Flux<Order> ordersStream = webClient.get() .uri("/orders/") .exchange() .flatMap(response -> response.bodyToFlux(Order.class)); Problem The response from the web service is paginated and therefore doesn't contain the list of items directly as in the example above. It looks like this # GET /orders/ { "error": null, "metadata": { "total": 998, "limit": 1000, "offset": 0 }, "data": [ { orderId: 1, ... }, { orderId: 2, ... }, ] } How can I get the sub key "data" as a Flux<Order>? Possible solution, but I don't know if it's the best approach... Create a wrapper class and convert the wrappers .data to a flux. But now we need to deserialize the whole response at once, potentially running out of memory. // Java Flux<Order> ordersStream = webClient.get() .uri("/orders/") .exchange() .flatMap(response -> response.bodyToMono(PageWrapper.class)) .flatMapMany(wrapper -> Flux.fromIterable(wrapper.data)); Is there a better way?
stackoverflow
{ "language": "en", "length": 196, "provenance": "stackexchange_0000F.jsonl.gz:844288", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478189" }
16735967cf18c6e8766d33636b13d09f5c199127
Stackoverflow Stackexchange Q: How to share an image with Discordrb Api? I'm coding a Discord Bot with the Discordrb Api, and I can't find a way to share an image on my computer to discord. bot.command :food do |event| agent = Mechanize.new link = 'https://source.unsplash.com/random/featured/?Food' agent.get(link).save "images/pic.jpg" end A: Ok so I've found a way to do that bot.command :food do |event| agent = Mechanize.new link = 'https://source.unsplash.com/random/featured/?Food,Plate' agent.get(link).save "pic.png" event.send_file(File.open('pic.png', 'r'), caption: "Voiçi votre repas # {event.user.name} .") sleep(5) event File.delete("pic.png") end I hope that this can help some people. Channel#send_file
Q: How to share an image with Discordrb Api? I'm coding a Discord Bot with the Discordrb Api, and I can't find a way to share an image on my computer to discord. bot.command :food do |event| agent = Mechanize.new link = 'https://source.unsplash.com/random/featured/?Food' agent.get(link).save "images/pic.jpg" end A: Ok so I've found a way to do that bot.command :food do |event| agent = Mechanize.new link = 'https://source.unsplash.com/random/featured/?Food,Plate' agent.get(link).save "pic.png" event.send_file(File.open('pic.png', 'r'), caption: "Voiçi votre repas # {event.user.name} .") sleep(5) event File.delete("pic.png") end I hope that this can help some people. Channel#send_file A: I'd like to add as answer to this question, that if you're sending a image that's stored online, you might want to simply send an embed instead. bot.command :food do |event| event.channel.send_embed("Check out the image below") do |embed| embed.image = Discordrb::Webhooks::EmbedImage.new(url: "https://source.unsplash.com/random/featured/?Food,Plate") end end Channel#send_embed Embed
stackoverflow
{ "language": "en", "length": 137, "provenance": "stackexchange_0000F.jsonl.gz:844299", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478224" }
e2f25ede835fc75066bcd1270bb21ec5489696ea
Stackoverflow Stackexchange Q: How do I implement a custom binding for Azure Functions? Azure Functions come with a fixed set of pre-existing bindings. At the same time, Azure Functions are based on Web Jobs SDK, which have some extensibility story. It enables creating custom binding types, including custom triggers. Is it possible to run those custom bindings in Azure Function runtime? If yes, is there a tutorial or documentation on how to do that? If no, any plans to? Some sample usage scenario would be integrating to non-Azure products (e.g. Kafka) or custom in-house protocols. A: Custom input and output bindings are now fully supported. More information can be found on the Azure WebJobs wiki: https://github.com/Azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings This wiki describes how to define a custom binding extension for the WebJobs SDK. These same extensions can be used, without modification, in Azure Functions. A sample binding which writes to a Slack channel be found here: https://github.com/lindydonna/SlackOutputBinding
Q: How do I implement a custom binding for Azure Functions? Azure Functions come with a fixed set of pre-existing bindings. At the same time, Azure Functions are based on Web Jobs SDK, which have some extensibility story. It enables creating custom binding types, including custom triggers. Is it possible to run those custom bindings in Azure Function runtime? If yes, is there a tutorial or documentation on how to do that? If no, any plans to? Some sample usage scenario would be integrating to non-Azure products (e.g. Kafka) or custom in-house protocols. A: Custom input and output bindings are now fully supported. More information can be found on the Azure WebJobs wiki: https://github.com/Azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings This wiki describes how to define a custom binding extension for the WebJobs SDK. These same extensions can be used, without modification, in Azure Functions. A sample binding which writes to a Slack channel be found here: https://github.com/lindydonna/SlackOutputBinding A: We have a preview of 'Bring Your Own Binding' feature'. See Extensibility for more details on the feature and WebJobsExtensionSamples for sample and docs. Also, you can track the feature here
stackoverflow
{ "language": "en", "length": 184, "provenance": "stackexchange_0000F.jsonl.gz:844302", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478231" }
267290b5fd7716f98eabd7255ecfc6320034a706
Stackoverflow Stackexchange Q: Modify an object between two files I am developing a nodejs project and stuck at this problem. I have an empty object in one file and will update this object value in a secondf ile. jsonFile.js var jsonObj = { first: [] , second: [] , third: [], }; exports.jsonObj=jsonObj; pushdata.js var obj= require('./jsonFile.js'); // i'll retrieve data from file and push into the obj... // for the sake of simplicity im not writing data fetching code.. ojb.jsonObj.first.push("user1"); How can I update this object in pushdata.js file in such a way that it also updates/change the object in jsonFile.js A: The best way to handle this is to do the following: * *Change jsonFile.js to a .json file (you can still require it as you have) *Update it as you have e.g. ojb.jsonObj.first.push("user1"); *Write the changes to the file system. Here's a code example: jsonFile.json { "first": [], "second": [], "third": [] } pushdata.js var fs = require('fs'); var obj = require('./jsonFile.json'); ojb.first.push("user1"); fs.writeFileSync(__dirname + '/jsonFile.json', JSON.stringify(obj, null, 4), 'utf8'); Using writeFileSync for simplicity but best to do file system writes using async functionality to avoid blocking code.
Q: Modify an object between two files I am developing a nodejs project and stuck at this problem. I have an empty object in one file and will update this object value in a secondf ile. jsonFile.js var jsonObj = { first: [] , second: [] , third: [], }; exports.jsonObj=jsonObj; pushdata.js var obj= require('./jsonFile.js'); // i'll retrieve data from file and push into the obj... // for the sake of simplicity im not writing data fetching code.. ojb.jsonObj.first.push("user1"); How can I update this object in pushdata.js file in such a way that it also updates/change the object in jsonFile.js A: The best way to handle this is to do the following: * *Change jsonFile.js to a .json file (you can still require it as you have) *Update it as you have e.g. ojb.jsonObj.first.push("user1"); *Write the changes to the file system. Here's a code example: jsonFile.json { "first": [], "second": [], "third": [] } pushdata.js var fs = require('fs'); var obj = require('./jsonFile.json'); ojb.first.push("user1"); fs.writeFileSync(__dirname + '/jsonFile.json', JSON.stringify(obj, null, 4), 'utf8'); Using writeFileSync for simplicity but best to do file system writes using async functionality to avoid blocking code. A: you cant' update jsonFile.js file this way, because require create instance every time when call require() if you want to update the file, you need to create json data file, read that json file using fs module and convert into javascript object and update javascript object and then use JSON.stringfy to convert string and then write file using fs module. OR you can create service in nodeJS for sharing data between modules
stackoverflow
{ "language": "en", "length": 262, "provenance": "stackexchange_0000F.jsonl.gz:844306", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478239" }
c14e10cc5346783a747734d3615f29ab56a17c19
Stackoverflow Stackexchange Q: How to handle extremely long LSTM sequence length? I have some data that is sampled at at a very high rate (on the order of hundreds of times per second). This results in a sequence length that is huge (~90,000 samples) on average for any given instance. This entire sequence has a single label. I am trying to use an LSTM neural network to classify new sequences as one of these labels (multiclass classification). However, using an LSTM with a such a large sequence length results in a network that is quite large. What are some methods to effectively 'chunk' these sequences so that I could reduce the sequence length of the neural network, yet still maintain the information captured in the entire instance? A: This post is from some time ago, but I thought I would chime in here. For this specific problem that you are working on (one-dimensional continuous-valued signal with locality, composition-ality, and stationarity), I would highly recommend a CNN convolutional neural network approach, as opposed to using an LSTM.
Q: How to handle extremely long LSTM sequence length? I have some data that is sampled at at a very high rate (on the order of hundreds of times per second). This results in a sequence length that is huge (~90,000 samples) on average for any given instance. This entire sequence has a single label. I am trying to use an LSTM neural network to classify new sequences as one of these labels (multiclass classification). However, using an LSTM with a such a large sequence length results in a network that is quite large. What are some methods to effectively 'chunk' these sequences so that I could reduce the sequence length of the neural network, yet still maintain the information captured in the entire instance? A: This post is from some time ago, but I thought I would chime in here. For this specific problem that you are working on (one-dimensional continuous-valued signal with locality, composition-ality, and stationarity), I would highly recommend a CNN convolutional neural network approach, as opposed to using an LSTM. A: Three years later, we have what seems to be the start of solutions for this type of problem: sparse transformers. See https://arxiv.org/abs/1904.10509 https://openai.com/blog/sparse-transformer/ A: When you have very long sequences RNNs can face the problem of vanishing gradients and exploding gradients. There are methods. The first thing you need to understand is why we need to try above methods? It's because back propagation through time can get real hard due to above mentioned problems. Yes introduction of LSTM has reduced this by very large margin but still when it's is so long you can face such problems. So one way is clipping the gradients. That means you set an upper bound to gradients. Refer to this stackoverflow question Then this problem you asked What are some methods to effectively 'chunk' these sequences? One way is truncated back propagation through time. There are number of ways to implement this truncated BPTT. Simple idea is * *Calculate the gradients only for number of given time steps That means if your sequence is 200 time steps and you only give 10 time steps it will only calculate gradient for 10 time step and then pass the stored memory value in that 10 time step to next sequence(as the initial cell state) . This method is what tensorflow using to calculate truncated BPTT. 2.Take the full sequence and only back propagate gradients for some given time steps from selected time block. It's a continuous way Here is the best article I found which explains these trunacated BPTT methods. Very easy. Refer to this Styles of Truncated Backpropagation
stackoverflow
{ "language": "en", "length": 438, "provenance": "stackexchange_0000F.jsonl.gz:844312", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478272" }
98d621a5ae7b094e3e84c640cd7f934048e085fd
Stackoverflow Stackexchange Q: How do I iterate until a fixed point in Clojure? I'm frequently in the position that my code reads like so: (iterate improve x) And I'm looking for the first value that no longer is an improvement over the previous. Neither filter nor take-while lend themselves to an obvious solution. However, I'm hesitant to write out: (loop [current x next (improve x)] (if (= current next) current (recur next (improve next)))) or: (let [improvements (iterate improve x)] (->> (map vector improvements (rest improvements)) (filter (partial apply =)) (ffirst))) Because at some point this is becoming repetitive and surely fixed point iteration is such a basic task that there must be some kind of library support somewhere, right? A: You could use drop-while then first: (defn still-improving? [[x y]] ...) (->> st (iterate transition) (partition 2 1) (drop-while still-improving?) ffirst)
Q: How do I iterate until a fixed point in Clojure? I'm frequently in the position that my code reads like so: (iterate improve x) And I'm looking for the first value that no longer is an improvement over the previous. Neither filter nor take-while lend themselves to an obvious solution. However, I'm hesitant to write out: (loop [current x next (improve x)] (if (= current next) current (recur next (improve next)))) or: (let [improvements (iterate improve x)] (->> (map vector improvements (rest improvements)) (filter (partial apply =)) (ffirst))) Because at some point this is becoming repetitive and surely fixed point iteration is such a basic task that there must be some kind of library support somewhere, right? A: You could use drop-while then first: (defn still-improving? [[x y]] ...) (->> st (iterate transition) (partition 2 1) (drop-while still-improving?) ffirst) A: You can use reduce and reduced to stop when necessary. reduced wraps the argument in a special object, which reduce is designed to look for and stop processing immediately returning the wrapped value. (def vals (iterate improve x)) (reduce #(if (= %1 %2) (reduced %1) %2) vals)
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:844330", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478322" }
bfa2871c373528e30ef6e4fce39dfe77cc599212
Stackoverflow Stackexchange Q: If statement won't print text I have this code: from Tools.scripts.treesync import raw_input username = raw_input("Enter Username : ") password = raw_input("Enter Password : ") if username == "bert" and password == "peter": print("Logged in") and i want it to say logged in but it doesn't say anything. It just won't accept anything I'm doing, does anyone know the answer? (started today so it can be a small fix) EDIT: it should have been input instead of raw_input A: No need to import anything. Also raw_input was changed to input in Python 3. So Your_variable = input("Enter input:") Would do good. If you want to use raw_input functionality in Python 3 then use eval(input()) Difference between them previously. If you enter 5 to input It takes the value, finds it type and stores it as an integer A = input("Enter :") Where as raw_input stored it as a string This has changed now so simply use input. And if you want to store anything as an integer . Just use this. a = int(input("Enter value: "))
Q: If statement won't print text I have this code: from Tools.scripts.treesync import raw_input username = raw_input("Enter Username : ") password = raw_input("Enter Password : ") if username == "bert" and password == "peter": print("Logged in") and i want it to say logged in but it doesn't say anything. It just won't accept anything I'm doing, does anyone know the answer? (started today so it can be a small fix) EDIT: it should have been input instead of raw_input A: No need to import anything. Also raw_input was changed to input in Python 3. So Your_variable = input("Enter input:") Would do good. If you want to use raw_input functionality in Python 3 then use eval(input()) Difference between them previously. If you enter 5 to input It takes the value, finds it type and stores it as an integer A = input("Enter :") Where as raw_input stored it as a string This has changed now so simply use input. And if you want to store anything as an integer . Just use this. a = int(input("Enter value: ")) A: raw_input is a built-in function, you don't need to import anything. Just delete the first line and run it again.
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:844340", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478355" }
bbe7ccd42178b92d59b8f1ddaa0e0d8e48c04a30
Stackoverflow Stackexchange Q: Swift - How to change UITabBarItem badge font? I have a UITabBar. I set a value for tab bar items: tabBarItem3?.badgeValue = String(self.numberOfProducts) Now I want to change its font to a specific font. Then I used this code : tabBarItem3?.setBadgeTextAttributes([NSFontAttributeName: UIFont(name: "IRANSans", size: 14)], for: .normal) It doesn't work. What should I do? A: Swift 3 UITabBarItem.appearance().setBadgeTextAttributes([.font: UIFont.systemFont(ofSize: 30, weight: .medium)], for: .normal) UITabBarItem.appearance().setBadgeTextAttributes([.font: UIFont.systemFont(ofSize: 30, weight: .medium)], for: .selected)
Q: Swift - How to change UITabBarItem badge font? I have a UITabBar. I set a value for tab bar items: tabBarItem3?.badgeValue = String(self.numberOfProducts) Now I want to change its font to a specific font. Then I used this code : tabBarItem3?.setBadgeTextAttributes([NSFontAttributeName: UIFont(name: "IRANSans", size: 14)], for: .normal) It doesn't work. What should I do? A: Swift 3 UITabBarItem.appearance().setBadgeTextAttributes([.font: UIFont.systemFont(ofSize: 30, weight: .medium)], for: .normal) UITabBarItem.appearance().setBadgeTextAttributes([.font: UIFont.systemFont(ofSize: 30, weight: .medium)], for: .selected) A: UIKit updates the badge font sometime after the view's layoutSubviews or viewWillAppear. Fully overriding this will need a bit of code. You want to start by observing the badge's font change. tabBarItem.addObserver(self, forKeyPath: "view.badge.label.font", options: .new, context: nil) Now once the observe method is called it's safe to set the badge font. There's one catch however. UIKit wont apply the same change twice. To get around this issue first set the badge attributes to nil and then reapply your font. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "view.badge.label.font" { let badgeAttributes = [NSFontAttributeName: UIFont(name: "IRANSans", size: 14)] tabBarItem?.setBadgeTextAttributes(nil, for: .normal) tabBarItem?.setBadgeTextAttributes(badgeAttributes, for: .normal) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } Just incase of future iOS updates, you might want to wrap the addObserver in a try-catch. Also don't forget to remove the observer when your done! A: Try this two functions from UITabBarController extension: var tabBarController : UITabBarController bottomBar = UITabBarController() ... ... ... // Change badge font size bottomBar.setBadgeFontSize(fontSize: 10.0) // Change badge font bottomBar.setBadgeFont(font: UIFont.boldSystemFont(ofSize: 12.0)) Swift 4 extension UITabBarController { /** Change the badge font size of an UITabBarController item. - Parameter fontSize: new font size - Parameter subviews: nil or optional when called from UITabBarController object. Example of usage (programmatically): ``` let bottomBar = UITabBarController() ... ... ... bottomBar.setBadgeFontSize(fontSize: 10.0) ``` */ func setBadgeFontSize(fontSize: CGFloat, subviews: [UIView]? = nil) { let arraySubviews = (subviews == nil) ? self.view.subviews : subviews! for subview in arraySubviews { let describingType = String(describing: type(of: subview)) if describingType == "_UIBadgeView" { for badgeSubviews in subview.subviews { let badgeSubviewType = String(describing: type(of: badgeSubviews)) if badgeSubviewType == "UILabel" { let badgeLabel = badgeSubviews as! UILabel badgeLabel.fontSize = fontSize break } } } else { setBadgeFontSize(fontSize: fontSize, subviews: subview.subviews) } } } /** Change the badge font size of an UITabBarController item. - Parameter font: new font - Parameter subviews: nil or optional when called from UITabBarController object. Example of usage (programmatically): ``` let bottomBar = UITabBarController() ... ... ... bottomBar.setBadgeFont(font: UIFont.boldSystemFont(ofSize: 12.0)) ``` */ func setBadgeFont(font: UIFont, subviews: [UIView]? = nil) { let arraySubviews = (subviews == nil) ? self.view.subviews : subviews! for subview in arraySubviews { let describingType = String(describing: type(of: subview)) if describingType == "_UIBadgeView" { for badgeSubviews in subview.subviews { let badgeSubviewType = String(describing: type(of: badgeSubviews)) if badgeSubviewType == "UILabel" { let badgeLabel = badgeSubviews as! UILabel badgeLabel.font = font break } } } else { setBadgeFont(font: font, subviews: subview.subviews) } } } } A: For iOS15+ let tabBarAppearance: UITabBarAppearance = UITabBarAppearance() tabBarAppearance.configureWithOpaqueBackground() tabBarAppearance.stackedLayoutAppearance.normal.badgeTextAttributes = [ .font: UIFont.systemFont(ofSize: 11) ] // also can change title: // tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [...] // tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [...] UITabBar.appearance().standardAppearance = tabBarAppearance UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance For iOS14 and below UITabBarItem.appearance().setBadgeTextAttributes([ .font: UIFont.systemFont(ofSize: 11) ], for: .normal) A: Swift 3 UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 10)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 10)], for: .selected)
stackoverflow
{ "language": "en", "length": 553, "provenance": "stackexchange_0000F.jsonl.gz:844358", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478417" }
58611ec19cceb734a77c3cef6568340db5e28421
Stackoverflow Stackexchange Q: Unity 5.6 with Google Cardboard showing very different images in each eye Building a VR app in unity for iOS. Added the GvrEditorEmulator into my project and as you can see the images that are sent to each eye are far more different than they should be. For example, the mountain in the left eye doesn't appear anywhere in the right eye. As a result the 3D effect is not working when I put the phone into Google Cardboadr. Anyone know how to fix this or why this might be happening? A: Turns out this is a known bug with Google Cardboard: https://forum.unity3d.com/threads/ios-cardboard-support-broken.461239/
Q: Unity 5.6 with Google Cardboard showing very different images in each eye Building a VR app in unity for iOS. Added the GvrEditorEmulator into my project and as you can see the images that are sent to each eye are far more different than they should be. For example, the mountain in the left eye doesn't appear anywhere in the right eye. As a result the 3D effect is not working when I put the phone into Google Cardboadr. Anyone know how to fix this or why this might be happening? A: Turns out this is a known bug with Google Cardboard: https://forum.unity3d.com/threads/ios-cardboard-support-broken.461239/ A: Have you tried changing camera target with ? this.GetComponent<Camera>().stereoTargetEye = StereoTargetEyeMask.Both; is terrain with trees stored as one object, or couple smaller ones? Maybe it's too huge to be processed with VR enabled on mobile - seems like GUI elements are rendered correctly.
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:844383", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478473" }
344b9e862ec06fea6b0edcb09e0b44b9e1f02b96
Stackoverflow Stackexchange Q: p5.js input position relative to canvas Here's what I have: function setup() { var cnv = createCanvas(960,540); cnv.parent("sketchHolder"); background('white'); var input = createInput(); input.position(10,10); input.parent("sketchHolder"); } I have a div named "sketchHolder" centered with css. I am trying to make the input position relative to the canvas, but it is positioned on the entire webpage outside on the canvas instead. Any suggestions? A: function setup() { var cnv = createCanvas(960, 540); cnv.parent("sketchHolder"); background("blue"); var input = createInput(); input.position(10, 10); input.parent("sketchHolder"); } #sketchHolder { width: 960px; height: 540px; margin: 0 auto; position: relative; } <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script> <div id="sketchHolder"></div> Codepen link
Q: p5.js input position relative to canvas Here's what I have: function setup() { var cnv = createCanvas(960,540); cnv.parent("sketchHolder"); background('white'); var input = createInput(); input.position(10,10); input.parent("sketchHolder"); } I have a div named "sketchHolder" centered with css. I am trying to make the input position relative to the canvas, but it is positioned on the entire webpage outside on the canvas instead. Any suggestions? A: function setup() { var cnv = createCanvas(960, 540); cnv.parent("sketchHolder"); background("blue"); var input = createInput(); input.position(10, 10); input.parent("sketchHolder"); } #sketchHolder { width: 960px; height: 540px; margin: 0 auto; position: relative; } <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script> <div id="sketchHolder"></div> Codepen link
stackoverflow
{ "language": "en", "length": 102, "provenance": "stackexchange_0000F.jsonl.gz:844402", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478531" }
477d43d97429f0aade6584dd325c0981e16eaf5a
Stackoverflow Stackexchange Q: Require assets in react's JSX? A completely noob question, sorry. I'm using dva to generate a project. If I want to create an <img /> tag, I can get the SRC for the asset like this: <img src={require('../assets/card-cultural.png')} alt="" /> This works properly. However, I need to generate this code: <picture> <source srcset="assets/card-cultural.png, assets/[email protected] 2x" /> <img src={require('../assets/card-cultural.png')} alt="" /> </picture> Notice the srcset value on source. How would I generate that string using require?
Q: Require assets in react's JSX? A completely noob question, sorry. I'm using dva to generate a project. If I want to create an <img /> tag, I can get the SRC for the asset like this: <img src={require('../assets/card-cultural.png')} alt="" /> This works properly. However, I need to generate this code: <picture> <source srcset="assets/card-cultural.png, assets/[email protected] 2x" /> <img src={require('../assets/card-cultural.png')} alt="" /> </picture> Notice the srcset value on source. How would I generate that string using require?
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:844423", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478606" }
d9e981a9b214e414947120fc69eec66f320d146d
Stackoverflow Stackexchange Q: ReturnUrl is null in ASP.NET Core login I have ASP.NET Core application with individual accounts; very similar to what gets generated by VS2017. For testing purposes I put [Authorize] attribute on About() action in Home controller. I am redirected to Login page as expected, and I see that URL is http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout - also as expected. However, in the POST Login method ReturnUrl is null. I have Login method in Account Controller: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model) { ... } I also tried ReturnUrl as parameter explicitly, with or without [FromQuery]. In all permutations it is null. A: You should be sure that you are using Html.BeginForm("Login", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"] }) [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model, string ReturnUrl) { ... }
Q: ReturnUrl is null in ASP.NET Core login I have ASP.NET Core application with individual accounts; very similar to what gets generated by VS2017. For testing purposes I put [Authorize] attribute on About() action in Home controller. I am redirected to Login page as expected, and I see that URL is http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout - also as expected. However, in the POST Login method ReturnUrl is null. I have Login method in Account Controller: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model) { ... } I also tried ReturnUrl as parameter explicitly, with or without [FromQuery]. In all permutations it is null. A: You should be sure that you are using Html.BeginForm("Login", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"] }) [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginInputModel model, string ReturnUrl) { ... } A: This is how i managed to get mine working The Get Action [HttpGet] [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; if (HttpContext.User.Identity.IsAuthenticated) { if (Url.IsLocalUrl(ViewBag.ReturnUrl)) return Redirect(ViewBag.ReturnUrl); return RedirectToAction("Index", "Home"); } return View(); } My Form is like this : <form asp-action="Login" method="post" asp-route-returnurl="@ViewBag.ReturnUrl" > The post action : [HttpPost] [AllowAnonymous] public async Task<ActionResult> Login(VMLogin model, string returnUrl) { ViewBag.ReturnUrl = returnUrl; if (!ModelState.IsValid) { return View(model); } //Authentication here if (Url.IsLocalUrl(ViewBag.ReturnUrl)) return Redirect(ViewBag.ReturnUrl); return RedirectToAction("Index", "Home"); } A: For .net core this is how you can fix the issue. In your View, @using (Html.BeginForm(new { returnUrl = Context.Request.Query["ReturnUrl"] })) In your Controller, [HttpPost] public IActionResult Login(YourViewModel m, string returnUrl = null) { if (!string.IsNullOrEmpty(returnUrl)) { return LocalRedirect(returnUrl); } return RedirectToAction("Index", "Home"); } A: first you must get return url in get method like this : [HttpGet] public IActionResult Login(string returnUrl) { TempData["ReturnUrl"] = returnUrl; return View(); } get returnUrl as parameter in get method and send in to post method by tempdata. the post method also like this : [HttpPost] public async Task<IActionResult> Login(LoginViewModel model) { //Your Login Code ... if (!string.IsNullOrEmpty(TempData["ReturnUrl"] as string) && Url.IsLocalUrl(TempData["ReturnUrl"] as string)) { return Redirect(TempData["ReturnUrl"] as string); } return RedirectToAction(controllerName:"Home",actionName:"Index"); }
stackoverflow
{ "language": "en", "length": 330, "provenance": "stackexchange_0000F.jsonl.gz:844443", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478657" }
ea3f57b94c9943ae0eab102bc4635c6502731ffd
Stackoverflow Stackexchange Q: Insert a randomly chosen element of one list in another I have two lists: list1=["a","b","c","d"] and list2=["z","y","x","w"]. I would like to take a random element of list1 and put it at list2[1]. I write list2.insert(1,random.sample(list1,1)) but I get ['z',['b'],'y','x','w'] How do I remove the brackets around the 'b'? A: Use random.choice, random.sample is for getting a bunch of items: list2.insert(1, random.choice(list1))
Q: Insert a randomly chosen element of one list in another I have two lists: list1=["a","b","c","d"] and list2=["z","y","x","w"]. I would like to take a random element of list1 and put it at list2[1]. I write list2.insert(1,random.sample(list1,1)) but I get ['z',['b'],'y','x','w'] How do I remove the brackets around the 'b'? A: Use random.choice, random.sample is for getting a bunch of items: list2.insert(1, random.choice(list1)) A: >>> import random >>> list1 = ["a", "b", "c", "d"] >>> list2 = ["z", "y", "x", "w"] >>> list2.insert(1, random.sample(list1, 1)[0]) >>> list2 ['z', 'b', 'y', 'x', 'w'] Just modifying your sample, but indexing the 0th element to remove the braces. A: Here you go, assuming you wanted to remove it from list1: list2.insert(1, list1.pop(random.randrange(len(list1)))
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:844453", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478682" }
325141bba2db49fdce6c40ac4ec1127d7573c18e
Stackoverflow Stackexchange Q: Rolling Unique Sum for 3 previous months in python The following is the dataset I am looking at. Input:- Date Name 01/01/2017 A 01/03/2017 B 02/05/2017 A 03/17/2017 C 04/08/2017 D 05/10/2017 B 06/12/2017 D Output:- Date Unique Count Jan 2017 2 Feb 2017 2 Mar 2017 3 Apr 2017 3 May 2017 3 Jun 2017 2 I want to get unique counts of "Name" in previous 3 months on rolling basis. For example for date 06/12/2017 the previous 3 months including itself is april, May, June. So April had "D", May had "B" and June had "D". So the unique count of June Month is 2. Similarly for all the other months as well. I am looking for a pandas function that could help me achieve this. Or any custom code that could implement this. Any help is appreciated. A: Try: months = pd.to_datetime(d.loc[:, "Date"]).dt.to_period("M") out = pd.DataFrame([ (month, len(d.loc[(-2 <= months - month) & (months - month <= 0), "Name"].unique())) for month in months.unique()])
Q: Rolling Unique Sum for 3 previous months in python The following is the dataset I am looking at. Input:- Date Name 01/01/2017 A 01/03/2017 B 02/05/2017 A 03/17/2017 C 04/08/2017 D 05/10/2017 B 06/12/2017 D Output:- Date Unique Count Jan 2017 2 Feb 2017 2 Mar 2017 3 Apr 2017 3 May 2017 3 Jun 2017 2 I want to get unique counts of "Name" in previous 3 months on rolling basis. For example for date 06/12/2017 the previous 3 months including itself is april, May, June. So April had "D", May had "B" and June had "D". So the unique count of June Month is 2. Similarly for all the other months as well. I am looking for a pandas function that could help me achieve this. Or any custom code that could implement this. Any help is appreciated. A: Try: months = pd.to_datetime(d.loc[:, "Date"]).dt.to_period("M") out = pd.DataFrame([ (month, len(d.loc[(-2 <= months - month) & (months - month <= 0), "Name"].unique())) for month in months.unique()]) A: Let's start by creating the DataFrame and setting the dates as the index: df= pd.DataFrame({'Date': ['01-01-2017', '01-03-2017', '02-05-2017', '03-17-2017', '04-08-2017', '05-10-2017', '06-12-2017'], 'Name': ['A','B', 'A', 'C', 'D', 'B', 'D']}) df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date') First, we group by month so that later we can do rolling counts per month: groups = df.groupby(pd.TimeGrouper(freq='M')) Now, we need a way to retain all names we've seen each month. We can put them into a list. all_names_per_month = groups['Name'].apply(list) This looks like: Date 2017-01-31 [A, B] 2017-02-28 [A] 2017-03-31 [C] 2017-04-30 [D] 2017-05-31 [B] 2017-06-30 [D] Freq: M, Name: Name, dtype: object Next, ideally, we would want to use all_names_per_month.rolling(3).apply(...), but unfortunately, apply doesn't work with non-numeric values, so we can instead define a custom rolling function to get us the values we want: def get_values(window_len, df): values = [] for i in range(1, len(df)+1): if i < window_len: values.append(len(set(itertools.chain.from_iterable(all_names_per_month.iloc[0: i])))) else: values.append(len(set(itertools.chain.from_iterable(all_names_per_month.iloc[i-3:i])))) return values values = get_values(3, all_names_per_month) This gives us: [2, 2, 3, 3, 3, 2] Finally, we can put these values into a DataFrame with the appropriate index, which we then modify to look the way you specified above: result = pd.DataFrame(data=values, columns=['Unique Count'], index=all_names_per_month.index) result.index = result.index.strftime('%B %Y') result Unique Count January 2017 2 February 2017 2 March 2017 3 April 2017 3 May 2017 3 June 2017 2
stackoverflow
{ "language": "en", "length": 388, "provenance": "stackexchange_0000F.jsonl.gz:844476", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478781" }
14e9257d2351bfe7ea8ccd10640b56a78b59daa7
Stackoverflow Stackexchange Q: Getting the default font in Tkinter I'm running Python 3.6 and was wondering if there is a way to get the default font that Tkinter uses, more specifically the default font that the Canvas object uses when canvas.create_text is called. A: idlelib/help.py has this line: normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica']) where findfont is defined thusly: def findfont(self, names): "Return name of first font family derived from names." for name in names: if name.lower() in (x.lower() for x in tkfont.names(root=self)): font = tkfont.Font(name=name, exists=True, root=self) return font.actual()['family'] elif name.lower() in (x.lower() for x in tkfont.families(root=self)): return name (I did not write this.) https://www.tcl.tk/man/tcl8.6/TkCmd/font.htm is the ultimate doc on font functions.
Q: Getting the default font in Tkinter I'm running Python 3.6 and was wondering if there is a way to get the default font that Tkinter uses, more specifically the default font that the Canvas object uses when canvas.create_text is called. A: idlelib/help.py has this line: normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica']) where findfont is defined thusly: def findfont(self, names): "Return name of first font family derived from names." for name in names: if name.lower() in (x.lower() for x in tkfont.names(root=self)): font = tkfont.Font(name=name, exists=True, root=self) return font.actual()['family'] elif name.lower() in (x.lower() for x in tkfont.families(root=self)): return name (I did not write this.) https://www.tcl.tk/man/tcl8.6/TkCmd/font.htm is the ultimate doc on font functions. A: From the documentaion here: Tk 8.0 automatically maps Courier, Helvetica, and Times to their corresponding native family names on all platforms. I cannot find documentation that says what the default font for canvas.create_text would be but it should be one of the 3 listed in the above quote. A: I believe this will solve your problem. from tkinter import * janela = Tk() label = Label(janela) print(label["font"]) A: Yes. The default font used to create a text object on a canvas is "TkDefaultFont" from tkinter import * r = Tk() c = Canvas(r) c.pack() id = c.create_text(10, 10, text='c') def_font = c.itemconfig(id, 'font')[-2] # [-2] is default, [-1] is current print(def_font, c.itemconfig(id)) # to see all the config info If you wanted to modify that default font in place, you would use nametofont() to get access to the underlying font object and then manipulate it: from tkinter import font def_font_obj = font.nametofont(def_font) def_font_obj.config(...) If you don't want to customize a default font, you can create a new named font based on the current font and then modify that with current_font = c.itemconfig(id, 'font')[-1] # or just c.itemcget(id, 'font') new_named_font = font.Font(font=current_font).config(...) then pass in the new_named_font as a font option to any widget config.
stackoverflow
{ "language": "en", "length": 315, "provenance": "stackexchange_0000F.jsonl.gz:844485", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478807" }
4ae196d69796031fb89664e9d5d09893a9a6a0d2
Stackoverflow Stackexchange Q: Python - Find the number of duplicates in a string text I want to write a function that returns the number of alphabetic characters and numeric digits that occur more than once in an input string. Sample example: "aabbccd" should return 3 since "a","b" and "c" all have duplicates. Same for "aaabbccd", that would return 3 as well. Here is what I did, but it seems that there's something wrong with my code. It worked on some cases but apparently it does not on others. def duplicate_count(text): count=0 for i in range(len(text)-1): for j in range(i+1,len(text)): if text[i]==text[j]: count+=1 break break return count A: One simple way of doing it is : def duplicate_count(s): return len([x for x in set(s) if s.count(x) > 1])
Q: Python - Find the number of duplicates in a string text I want to write a function that returns the number of alphabetic characters and numeric digits that occur more than once in an input string. Sample example: "aabbccd" should return 3 since "a","b" and "c" all have duplicates. Same for "aaabbccd", that would return 3 as well. Here is what I did, but it seems that there's something wrong with my code. It worked on some cases but apparently it does not on others. def duplicate_count(text): count=0 for i in range(len(text)-1): for j in range(i+1,len(text)): if text[i]==text[j]: count+=1 break break return count A: One simple way of doing it is : def duplicate_count(s): return len([x for x in set(s) if s.count(x) > 1]) A: This one would be more concise: import numpy as np def duplicate_count(text): #elem is an array of the unique elements in a string #and count is its corresponding frequency elem, count = np.unique(tuple(text), return_counts=True) return np.sum(count>1) A: Here's a native approach without resorting to expensive str.count() (although performance depends on the length of the string and the duplicate characters) in pure O(N) time: def duplicate_count(text): seen = set() return len({char for char in text if char in seen or seen.add(char) is not None}) print(duplicate_count("aabbccd")) # 3 A: The problem is that you're not keeping track of letters you've already counted. Consider the input aaa. The code takes the first a and searches for another a. It finds one, so it increments count. Then the code moves on to the 2nd a. It searches for another a (again), finds one, and increments count (again). Use a set to keep track of which letters you've already counted. A: Another one line solution: import collections def duplicate_count(text): return len(list(filter(lambda x:x[1]>1,collections.Counter(text).items()))) A: Here is a approach using dict. import collections your_string='aabbssesd' d = collections.defaultdict(int) for c in your_string: d[c] += 1 d = {k: v for k, v in d.items() if v>1} print(len(d)) The defaultdict will simply create any items that you try to access (provided they don't exist yet). d = collections.defaultdict(int) This will output a key value pair for number of occurences of characters in the string like. {'e': 1, 'a': 2, 'r': 1, 's': 2} Use dict comprehension to store only key k,value v pair from dict and if value v is greater than 1. (more than one occurence) d = {k: v for k, v in d.items() if v>1} It's output {'a': 2, 's': 2} Then print(len(d)) to get number of duplicates
stackoverflow
{ "language": "en", "length": 418, "provenance": "stackexchange_0000F.jsonl.gz:844563", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479052" }
84a5348c9d738ab6372a2e5da007521875293fd0
Stackoverflow Stackexchange Q: Custom Relative Path In Asp.Net Core MVC Is there any possibility to have a custom relative path same as example at below: In Razor: <script src="%/scripts/theme.js" type="text/javascript"></script> And Result: <script src="/themes/default/scripts/theme.js" type="text/javascript"></script> Define New PATH style same as %/ or */ or $/ Attention: I KNOW ABOUT ~/ (default relative path). I'm talking about how can I Define NEW ONE? A: Finally I found the solution. Please take a looks how Microsoft had implement it at link below: https://github.com/aspnet/Mvc/blob/1c4b0fcdf38320b2f02c0bb7c31df5bd391ace07/src/Microsoft.AspNetCore.Mvc.Razor/TagHelpers/UrlResolutionTagHelper.cs#L47 I had take a copy of this class and I renamed that to this: [HtmlTargetElement("link", Attributes = "[href^='%/']", TagStructure = TagStructure.WithoutEndTag)] [HtmlTargetElement("script", Attributes = "[src^='%/']")] .... public class ThemeUrlResolutionTagHelper : TagHelper { /*Implement tag helper here*/ } And before creating trimmed string I insert my Theme URL url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/"); var trimmedUrl = CreateTrimmedString(url, start); And I changed the ~ to % in FindRelativeStart method // Before doing more work, ensure that the URL we're looking at is app-relative. if (url[start] != '%' || url[start + 1] != '/') { return -1; } And Done!
Q: Custom Relative Path In Asp.Net Core MVC Is there any possibility to have a custom relative path same as example at below: In Razor: <script src="%/scripts/theme.js" type="text/javascript"></script> And Result: <script src="/themes/default/scripts/theme.js" type="text/javascript"></script> Define New PATH style same as %/ or */ or $/ Attention: I KNOW ABOUT ~/ (default relative path). I'm talking about how can I Define NEW ONE? A: Finally I found the solution. Please take a looks how Microsoft had implement it at link below: https://github.com/aspnet/Mvc/blob/1c4b0fcdf38320b2f02c0bb7c31df5bd391ace07/src/Microsoft.AspNetCore.Mvc.Razor/TagHelpers/UrlResolutionTagHelper.cs#L47 I had take a copy of this class and I renamed that to this: [HtmlTargetElement("link", Attributes = "[href^='%/']", TagStructure = TagStructure.WithoutEndTag)] [HtmlTargetElement("script", Attributes = "[src^='%/']")] .... public class ThemeUrlResolutionTagHelper : TagHelper { /*Implement tag helper here*/ } And before creating trimmed string I insert my Theme URL url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/"); var trimmedUrl = CreateTrimmedString(url, start); And I changed the ~ to % in FindRelativeStart method // Before doing more work, ensure that the URL we're looking at is app-relative. if (url[start] != '%' || url[start + 1] != '/') { return -1; } And Done! A: You need to use ~ (tilde). There is no % operator for paths: <script src="~/scripts/theme.js" type="text/javascript"></script>
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:844585", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479154" }
f44029857ca047fe5151f87a5057207b0fa5aee5
Stackoverflow Stackexchange Q: How do I find percentages of a column using Hive/Presto Let's say I have a table that looks like: Reason | Duration Eating 40 Drinking 60 Everything Else 100 How do I get a table like this: Reason | Duration | Duration Percent Eating 40 20 Drinking 60 30 Everything Else 100 50 A: You can use a window function to compute the total: SELECT reason, duration, (duration * 100.0) / sum(duration) OVER () pct FROM ( VALUES ('eating', 40), ('drinking', 60), ('other', 100) ) AS t (reason, duration) Note that Presto (per the SQL standard) performs integer division, so it is necessary to convert one of the values to a double or decimal (otherwise the result will be zero). reason | duration | pct ----------+----------+------ eating | 40 | 20.0 drinking | 60 | 30.0 other | 100 | 50.0 (3 rows)
Q: How do I find percentages of a column using Hive/Presto Let's say I have a table that looks like: Reason | Duration Eating 40 Drinking 60 Everything Else 100 How do I get a table like this: Reason | Duration | Duration Percent Eating 40 20 Drinking 60 30 Everything Else 100 50 A: You can use a window function to compute the total: SELECT reason, duration, (duration * 100.0) / sum(duration) OVER () pct FROM ( VALUES ('eating', 40), ('drinking', 60), ('other', 100) ) AS t (reason, duration) Note that Presto (per the SQL standard) performs integer division, so it is necessary to convert one of the values to a double or decimal (otherwise the result will be zero). reason | duration | pct ----------+----------+------ eating | 40 | 20.0 drinking | 60 | 30.0 other | 100 | 50.0 (3 rows)
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:844603", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479204" }
21b262abf82e35204241c474bb13dbec7c8aab56
Stackoverflow Stackexchange Q: Groovy @Grab causing "No suitable ClassLoader found for grab" in Intellij I'm just starting to edit my (already working) groovy scripts in Intellij and am running in a wired problem. I could not find a solution using google. I have the following code: @Grapes([ @Grab('org.codehaus.groovy.modules.http-builder:http-builder:+'), @Grab('log4j:log4j:1.2.17'), @Grab(group='com.sun.jersey', module='jersey-client', version='1.9.1'), @Grab(group='com.sun.jersey', module='jersey-core', version='1.9.1'), @Grab(group='com.sun.jersey.contribs', module='jersey-multipart', version='1.8'), ]) @Log4j class DevTest{ static void main(String[] args) { println "TEST" } } When I run it in the commandline it works. In Intellij pressing first CTRL+Shift+F9 and afterwards CTRL+Shift+F10 I get the following error: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: No suitable ClassLoader found for grab I also tried to add @GrabConfig( systemClassLoader=true ) as it was suggested in other posts, however the result stayed the same. What could be the problem?
Q: Groovy @Grab causing "No suitable ClassLoader found for grab" in Intellij I'm just starting to edit my (already working) groovy scripts in Intellij and am running in a wired problem. I could not find a solution using google. I have the following code: @Grapes([ @Grab('org.codehaus.groovy.modules.http-builder:http-builder:+'), @Grab('log4j:log4j:1.2.17'), @Grab(group='com.sun.jersey', module='jersey-client', version='1.9.1'), @Grab(group='com.sun.jersey', module='jersey-core', version='1.9.1'), @Grab(group='com.sun.jersey.contribs', module='jersey-multipart', version='1.8'), ]) @Log4j class DevTest{ static void main(String[] args) { println "TEST" } } When I run it in the commandline it works. In Intellij pressing first CTRL+Shift+F9 and afterwards CTRL+Shift+F10 I get the following error: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: No suitable ClassLoader found for grab I also tried to add @GrabConfig( systemClassLoader=true ) as it was suggested in other posts, however the result stayed the same. What could be the problem?
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:844618", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479230" }
1ca69bc733fd264514bee4378633e53ab5208de9
Stackoverflow Stackexchange Q: How to convert PCollection> to PCollection in dataflow/beam I have a use case in which I need to output multiple T from a DoFn. So DoFn function is returning a PCollection<List<T>>. I want to convert it to PCollection<T> so that later in pipeline I can just filter like: PCollection<T> filteredT = filterationResult.apply(Filter.byPredicate(p -> p.equals(T) == T)); Currently the best method I can think of is, instead returning List<T> from the ParDo function I return KV<String,List<T>> with same key for every item. Then in pipeline I can do below to combine result: filterationResult.apply("Group", GroupByKey.<String, List<T>>create()) Or can I call c.output(T) from DoFn (where c is the ProcessContext object passed in) multiple times? A: You can call c.output(T) from a DoFn multiple times. There is also a library transform Flatten.iterables() but you don't need it in this case.
Q: How to convert PCollection> to PCollection in dataflow/beam I have a use case in which I need to output multiple T from a DoFn. So DoFn function is returning a PCollection<List<T>>. I want to convert it to PCollection<T> so that later in pipeline I can just filter like: PCollection<T> filteredT = filterationResult.apply(Filter.byPredicate(p -> p.equals(T) == T)); Currently the best method I can think of is, instead returning List<T> from the ParDo function I return KV<String,List<T>> with same key for every item. Then in pipeline I can do below to combine result: filterationResult.apply("Group", GroupByKey.<String, List<T>>create()) Or can I call c.output(T) from DoFn (where c is the ProcessContext object passed in) multiple times? A: You can call c.output(T) from a DoFn multiple times. There is also a library transform Flatten.iterables() but you don't need it in this case.
stackoverflow
{ "language": "en", "length": 137, "provenance": "stackexchange_0000F.jsonl.gz:844625", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479254" }
20595c12ea2c474ce04a754c1af6c63957f40ace
Stackoverflow Stackexchange Q: How to implement AVCam using Swift 3? This sample code covers implementation only for ios11. Can someone provide some example and/or hints for me to understand and code further? A: I found a repo where version 6.1 of AVCam was commited before 7.1 https://github.com/Lax/iOS-Swift-Demos here's the state of the repo on the commit for version 6.1 (Xcode 8.0, iOS 10.0) https://github.com/Lax/iOS-Swift-Demos/tree/2a92c00b6d800165f29be6a525b5e98424bc5843 It's a shame Apple doesn't make it easier to access previous versions of their code examples.
Q: How to implement AVCam using Swift 3? This sample code covers implementation only for ios11. Can someone provide some example and/or hints for me to understand and code further? A: I found a repo where version 6.1 of AVCam was commited before 7.1 https://github.com/Lax/iOS-Swift-Demos here's the state of the repo on the commit for version 6.1 (Xcode 8.0, iOS 10.0) https://github.com/Lax/iOS-Swift-Demos/tree/2a92c00b6d800165f29be6a525b5e98424bc5843 It's a shame Apple doesn't make it easier to access previous versions of their code examples.
stackoverflow
{ "language": "en", "length": 78, "provenance": "stackexchange_0000F.jsonl.gz:844662", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479362" }
84d41e95e76a3b064ad5ffb0ac150c02be27bf05
Stackoverflow Stackexchange Q: Detecting near-by phone numbers Trying to figure out some sort of method in which it would be possible to detect nearby phone numbers e.g. within a private premises. My only lead so far is to build a mini mobile base station that would let phones connect to it - even then my theory for this has many holes and blanks. The above may be completely off or possibly I may be on to something, either way if someone could give me a rough idea of what direction to take it in that would be much appreciated - I do not require any kind of code as I would much rather figure it out myself via a finger pointed in the right direction. Even if you do not have any solid answers but some tips that could possibly help me piece this together, that'd be great. A: This link might be useful. It feature some code and instructions for a personal cell tower. https://julianoliver.com/output/stealth-cell-tower
Q: Detecting near-by phone numbers Trying to figure out some sort of method in which it would be possible to detect nearby phone numbers e.g. within a private premises. My only lead so far is to build a mini mobile base station that would let phones connect to it - even then my theory for this has many holes and blanks. The above may be completely off or possibly I may be on to something, either way if someone could give me a rough idea of what direction to take it in that would be much appreciated - I do not require any kind of code as I would much rather figure it out myself via a finger pointed in the right direction. Even if you do not have any solid answers but some tips that could possibly help me piece this together, that'd be great. A: This link might be useful. It feature some code and instructions for a personal cell tower. https://julianoliver.com/output/stealth-cell-tower A: After a lot of searching, I came across something called an IMSI-catcher, which is a telephone eavesdropping device used for intercepting mobile phone traffic and tracking location data of mobile phone users. Now, this does not give the MSISDN (the phone number) but does give the unique IMSI number of the user, so maybe that could help. Ref: https://en.wikipedia.org/wiki/IMSI-catcher Also, accroding to this article (https://en.wikipedia.org/wiki/Talk%3AIMSI-catcher), it is not possible to get the MSISDN with this method since mobile phones send the IMSI when connecting to towers which internally is converted by the provider to the mobile number (MSISDN). A: I looked into the same idea but, at only a theoretical level. I found that whenever someones WiFi is turned on, they will ~constantly broadcast a signal. A signal that contains there MAC address. You can use this to identify who is there. Most people either forget, or are just lazy to turn of there WiFi when they leave home/work, and you can exploit this. So all you have to do is passively listen for these signals. The best thing is that you don't broadcast any signals at all, so they have no idea you know that they are there. More information at: https://www.crc.id.au/tracking-people-via-wifi-even-when-not-connected/. I hope I could help, please comment if you have any questions.
stackoverflow
{ "language": "en", "length": 380, "provenance": "stackexchange_0000F.jsonl.gz:844663", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479369" }
4406c302949bf29f8386e7badc164c9659434b1f
Stackoverflow Stackexchange Q: Python, how to fill nulls in a data frame using a dictionary I have a dataframe df something like this A B C 1 'x' 15.0 2 'y' NA 3 'z' 25.0 and a dictionary dc something like dc = {'x':15,'y':35,'z':25} I want to fill all nulls in column C of the dataframe using values of column B from the dictionary. So that my dataframe will become A B C 1 'x' 15 2 'y' 35 3 'z' 25 Could anyone help me how to do that please? thanks, Manoj A: You can use fillna with map: dc = {'x':15,'y':35,'z':25} df['C'] = df.C.fillna(df.B.map(dc)) df # A B C #0 1 x 15.0 #1 2 y 35.0 #2 3 z 25.0
Q: Python, how to fill nulls in a data frame using a dictionary I have a dataframe df something like this A B C 1 'x' 15.0 2 'y' NA 3 'z' 25.0 and a dictionary dc something like dc = {'x':15,'y':35,'z':25} I want to fill all nulls in column C of the dataframe using values of column B from the dictionary. So that my dataframe will become A B C 1 'x' 15 2 'y' 35 3 'z' 25 Could anyone help me how to do that please? thanks, Manoj A: You can use fillna with map: dc = {'x':15,'y':35,'z':25} df['C'] = df.C.fillna(df.B.map(dc)) df # A B C #0 1 x 15.0 #1 2 y 35.0 #2 3 z 25.0 A: df['C'] = np.where(df['C'].isnull(), df['B'].apply(lambda x: dc[x]), df['C'])
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:844667", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479389" }
756477e42407d6b01adf3ccca9b39c135b399027
Stackoverflow Stackexchange Q: Schema-validation: missing table [game] I think it may be possible dupplicate of this: Schema-validation: missing table [hibernate_sequences] but I can't figure it out. So in my application.properties file I have this option: spring.jpa.hibernate.ddl-auto=validate and I receive this error: Schema-validation: missing table [game] Why I am receiving this? Here is my Game class and User class: Game: @Entity public class Game { @Id @Column(name = "GAME_NUMBER") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long gameNumber; private int playerScore; private int NPCScore; private Date datetime; @ManyToOne @JoinColumn(name="USER_ID") private User user; public Game() {} public Game(int playerScore, int nPCScore, Date datetime) { super(); this.playerScore = playerScore; this.NPCScore = nPCScore; this.datetime = datetime; } public User getUser() { return user; } } + getters & setters User: @Entity public class User { @Id @Column(name = "USER_ID") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long userId; private String username; private String password; @OneToMany(mappedBy="user",cascade=CascadeType.ALL) private List<Game> games; @ElementCollection private List<Date> startSessions; public User() {} public User(String username, String password, List<Game> games, List<Date> startSessions) { super(); this.username = username; this.password = password; this.games = games; this.startSessions = startSessions; } } A: Don't forget permissions: GRANT select, insert, update, delete, alter ON table_name TO usr_name;
Q: Schema-validation: missing table [game] I think it may be possible dupplicate of this: Schema-validation: missing table [hibernate_sequences] but I can't figure it out. So in my application.properties file I have this option: spring.jpa.hibernate.ddl-auto=validate and I receive this error: Schema-validation: missing table [game] Why I am receiving this? Here is my Game class and User class: Game: @Entity public class Game { @Id @Column(name = "GAME_NUMBER") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long gameNumber; private int playerScore; private int NPCScore; private Date datetime; @ManyToOne @JoinColumn(name="USER_ID") private User user; public Game() {} public Game(int playerScore, int nPCScore, Date datetime) { super(); this.playerScore = playerScore; this.NPCScore = nPCScore; this.datetime = datetime; } public User getUser() { return user; } } + getters & setters User: @Entity public class User { @Id @Column(name = "USER_ID") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long userId; private String username; private String password; @OneToMany(mappedBy="user",cascade=CascadeType.ALL) private List<Game> games; @ElementCollection private List<Date> startSessions; public User() {} public User(String username, String password, List<Game> games, List<Date> startSessions) { super(); this.username = username; this.password = password; this.games = games; this.startSessions = startSessions; } } A: Don't forget permissions: GRANT select, insert, update, delete, alter ON table_name TO usr_name; A: This error can appear while using spring boot with flywayDB. The issue might be due to the wrong naming convention of script files, which were used by flywayDB. https://flywaydb.org/documentation/migrations#naming A: validate validates that the entities are compatible against the target, to a degree it's not foolproof. Anyway, whatever database you are trying to validate against does not have a table called game in which to store the entities. This answer goes into more detail about what validate does. Hibernate - hibernate.hbm2ddl.auto = validate specifically, checks the presence of tables, columns, id generators Without knowing your database/expectations (are you expecting it to be created, or using Flyway/Liquibase to create/update the database etc.) I can't answer if validate is correct for your use case. You could try create-drop to create and drop the table on startup/shutdown, but this isn't a solution for any production control over a database. A: I got the same as I changed to Hibernate 5.4.0.Final. Either Hibernate suddenly has problems to recognize the default schema or the driver does not return the schema properly. I was able to bypass it by either adding the schema definition to the table definition. @Table(name = "GAME", schema = "PUBLIC") or by adding a default schema in persistence.xml. <property name="hibernate.default_schema" value="PUBLIC" /> A: The SQL standard requires names stored in uppercase. If you named the table/fields in lowercase - JPA can automatically convert case to upper and trying to search names in this case, but write to logs in lower ¯\_(ツ)_/¯ A: Add this in application.yml: spring: jpa: properties: hibernate: default_schema: game A: Hibernate version 5.6.9, Case-sensitive implementation: hibernate: physical_naming_strategy: 'org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl'
stackoverflow
{ "language": "en", "length": 462, "provenance": "stackexchange_0000F.jsonl.gz:844673", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479406" }
a613f100f0d09573d0a3039480ba1cd357ec75ab
Stackoverflow Stackexchange Q: Which is faster : defaultdict in python or libcpp.map in cython? I am trying to optimize a function which store words and its count. Python implementation is quite slow as of now. I am trying to cythonize the function. What other alternatives do we have in cython corresponding to defaultdict ?
Q: Which is faster : defaultdict in python or libcpp.map in cython? I am trying to optimize a function which store words and its count. Python implementation is quite slow as of now. I am trying to cythonize the function. What other alternatives do we have in cython corresponding to defaultdict ?
stackoverflow
{ "language": "en", "length": 52, "provenance": "stackexchange_0000F.jsonl.gz:844683", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479434" }
9ad782cedad66d4e6fcca4a070b76ee5279631d6
Stackoverflow Stackexchange Q: Angular 2/4 set focus on input element How can I set focus on an input by (click) event? I have this function in place but I'm clearly missing something (angular newbie here) sTbState: string = 'invisible'; private element: ElementRef; toggleSt() { this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible'); if (this.sTbState === 'visible') { (this.element.nativeElement).find('#mobileSearch').focus(); } } A: You can use the @ViewChild decorator for this. Documentation is at https://angular.io/api/core/ViewChild. Here's a working plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F This gist of the code comes down to, giving a name to your input element and wiring up a click event in your template. <input #myInput /> <button (click)="focusInput()">Click</button> In your component, implement @ViewChild or @ViewChildren to search for the element(s), then implement the click handler to perform the function you need. export class App implements AfterViewInit { @ViewChild("myInput") inputEl: ElementRef; focusInput() { this.inputEl.nativeElement.focus() } Now, click on the button and then the blinking caret will appear inside the input field. Use of ElementRef is not recommended as a security risk, like XSS attacks (https://angular.io/api/core/ElementRef) and because it results in less-portable components. Also beware that, the inputEl variable will be first available, when ngAfterViewInit event fires.
Q: Angular 2/4 set focus on input element How can I set focus on an input by (click) event? I have this function in place but I'm clearly missing something (angular newbie here) sTbState: string = 'invisible'; private element: ElementRef; toggleSt() { this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible'); if (this.sTbState === 'visible') { (this.element.nativeElement).find('#mobileSearch').focus(); } } A: You can use the @ViewChild decorator for this. Documentation is at https://angular.io/api/core/ViewChild. Here's a working plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F This gist of the code comes down to, giving a name to your input element and wiring up a click event in your template. <input #myInput /> <button (click)="focusInput()">Click</button> In your component, implement @ViewChild or @ViewChildren to search for the element(s), then implement the click handler to perform the function you need. export class App implements AfterViewInit { @ViewChild("myInput") inputEl: ElementRef; focusInput() { this.inputEl.nativeElement.focus() } Now, click on the button and then the blinking caret will appear inside the input field. Use of ElementRef is not recommended as a security risk, like XSS attacks (https://angular.io/api/core/ElementRef) and because it results in less-portable components. Also beware that, the inputEl variable will be first available, when ngAfterViewInit event fires. A: Get input element as native elements in ts file. //HTML CODE <input #focusTrg /> <button (click)="onSetFocus()">Set Focus</button> //TS CODE @ViewChild("focusTrg") trgFocusEl: ElementRef; onSetFocus() { setTimeout(()=>{ this.trgFocusEl.nativeElement.focus(); },100); } we need to put this.trgFocusEl.nativeElement.focus(); in setTimeout() then it'll work fine otherwise it will throw undefined error. A: try this : in you HTML file: <button type="button" (click)="toggleSt($event, toFocus)">Focus</button> <!-- Input to focus --> <input #toFocus> in your ts File : sTbState: string = 'invisible'; toggleSt(e, el) { this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible'); if (this.sTbState === 'visible') { el.focus(); } } A: try this. //on .html file <button (click)=keyDownFunction($event)>click me</button> // on .ts file // navigate to form elements automatically. keyDownFunction(event) { // specify the range of elements to navigate let maxElement = 4; if (event.keyCode === 13) { // specify first the parent of container of elements let container = document.getElementsByClassName("myForm")[0]; // get the last index from the current element. let lastIndex = event.srcElement.tabIndex ; for (let i=0; i<maxElement; i++) { // element name must not equal to itself during loop. if (container[i].id !== event.srcElement.id && lastIndex < i) { lastIndex = i; const tmp = document.getElementById(container[i].id); (tmp as HTMLInputElement).select(); tmp.focus(); event.preventDefault(); return true; } } } }
stackoverflow
{ "language": "en", "length": 395, "provenance": "stackexchange_0000F.jsonl.gz:844690", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479457" }
78973f8438650038a2e0e600ac7adfcc55d1464a
Stackoverflow Stackexchange Q: Paypal subscriptions using client side js only Is it possible to create PayPal subscriptions using only a client side javascript (and Firebase if needed)? I'm a bit confused with PayPal; there are so many frameworks/options to do same thing that I don't know where to look exactly. https://developer.paypal.com/demo/checkout/#/pattern/client This seems similar what I'm looking for except it's only for payments, and I need subscriptions. A: Just an update on this ticket. Paypal do now have a javascript client-side API that works very well. Here is the link: https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/
Q: Paypal subscriptions using client side js only Is it possible to create PayPal subscriptions using only a client side javascript (and Firebase if needed)? I'm a bit confused with PayPal; there are so many frameworks/options to do same thing that I don't know where to look exactly. https://developer.paypal.com/demo/checkout/#/pattern/client This seems similar what I'm looking for except it's only for payments, and I need subscriptions. A: Just an update on this ticket. Paypal do now have a javascript client-side API that works very well. Here is the link: https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/ A: You can use PayPal WPS Subscription Buttons https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#recurring-payment-variables This is a button integration so you can use JS and HTML to create a plan and redirect buyers to paypal.com. You can specify your subscription terms and PayPal will take care of making recurring payments. You can also maintain inventory, profile & loss tracking. For any API integration its highly risky to use client side JS.
stackoverflow
{ "language": "en", "length": 155, "provenance": "stackexchange_0000F.jsonl.gz:844704", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479515" }
94c283209de48461fd196b14945e07ed175102b3
Stackoverflow Stackexchange Q: How can I return nil instead of an error from a missing hash key? I have a hash, and I'm looking for a certain key inside it. But sometimes hash itself can be nil. In this event, I don't want hash["key"] to return an undefined method '[]' for nil:NilClass error. I want it to return nil instead. With other similar situations, I can use try, like this: nil.try(:key) => nil but I can't get the same method to work with my hash. In other words, I'm looking for a method that results in something like this: > @hash = nil > @hash.try(:["key"]) => nil A: The various to_X methods are often convenient ways to quietly convert nils to empty instances of what you're really interested in without complicated your logic with explicit conditionals. In your case, you could take advantage of Hash#to_h returning the hash itself and NilClass#to_h returning an empty Hash: > hash = nil > hash.to_h['key'] => nil > hash = { 'key' => 11 } > hash.to_h['key'] => 11 Sometimes this is less noisy than an explicit if, sometimes it isn't.
Q: How can I return nil instead of an error from a missing hash key? I have a hash, and I'm looking for a certain key inside it. But sometimes hash itself can be nil. In this event, I don't want hash["key"] to return an undefined method '[]' for nil:NilClass error. I want it to return nil instead. With other similar situations, I can use try, like this: nil.try(:key) => nil but I can't get the same method to work with my hash. In other words, I'm looking for a method that results in something like this: > @hash = nil > @hash.try(:["key"]) => nil A: The various to_X methods are often convenient ways to quietly convert nils to empty instances of what you're really interested in without complicated your logic with explicit conditionals. In your case, you could take advantage of Hash#to_h returning the hash itself and NilClass#to_h returning an empty Hash: > hash = nil > hash.to_h['key'] => nil > hash = { 'key' => 11 } > hash.to_h['key'] => 11 Sometimes this is less noisy than an explicit if, sometimes it isn't. A: The situation you describe (hash = nil) is not a "missing hash key", it's not a hash at all. In addition to the other answers, another way could be this in Ruby (2.3) hash&.fetch("key", nil) Or: (hash || {})["key"] Both these will return nil if the hash is nil or if it's missing the key. A: You could check if @hash is nil before using @hash["key"], like this: @hash = nil @hash["key"] unless @hash.nil? #=> nil A: To use try, you can do @hash.try(:[], 'key') or even @hash&.[]('key') if you are in ruby 2.3+
stackoverflow
{ "language": "en", "length": 280, "provenance": "stackexchange_0000F.jsonl.gz:844713", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479547" }
dd9c21cc3310a755b08aeff001e403b52654cf23
Stackoverflow Stackexchange Q: How to implicitly return object from arrow function? I swa this arrow function in a Redux example: export const addTodo = (text) => { return { type: 'ADD_TODO', id: nextTodoId++, text } } I was wondering whether I can get rid of the extra layer of { return ...; }, essentially getting rid of the block? For illustration, the following two arrow functions are the same: const fn = (a) => a + 1; const fn = (a) => { return a+1; }; and I can strip the return from the second, more verbose version. But when I do the same to the Redux example and strip the return layer, I get an error: SyntaxError: repl, unexpected token, expected ; ... It seems that there is some confusion between the {} in the object literal and code blocks. Is there a way to remove this this extra layer of return here? A: you can prevent the confusion by adding extra parentheses like this - export const addTodo = (text) => ( { type: 'ADD_TODO', id: nextTodoId++, text }) hope that helped :)
Q: How to implicitly return object from arrow function? I swa this arrow function in a Redux example: export const addTodo = (text) => { return { type: 'ADD_TODO', id: nextTodoId++, text } } I was wondering whether I can get rid of the extra layer of { return ...; }, essentially getting rid of the block? For illustration, the following two arrow functions are the same: const fn = (a) => a + 1; const fn = (a) => { return a+1; }; and I can strip the return from the second, more verbose version. But when I do the same to the Redux example and strip the return layer, I get an error: SyntaxError: repl, unexpected token, expected ; ... It seems that there is some confusion between the {} in the object literal and code blocks. Is there a way to remove this this extra layer of return here? A: you can prevent the confusion by adding extra parentheses like this - export const addTodo = (text) => ( { type: 'ADD_TODO', id: nextTodoId++, text }) hope that helped :) A: Also you can use more explicit Object.assign for (arguably) better readability: const addTodo = text => Object.assign({ type: 'ADD_TODO', id: nextTodoId++, text })
stackoverflow
{ "language": "en", "length": 207, "provenance": "stackexchange_0000F.jsonl.gz:844724", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479570" }
3cdbe02ec59ef8a48a5f193467ff5968d6ceac12
Stackoverflow Stackexchange Q: Why Supplier instead of Producer? This is a really simple question, but someone here must know, so here's an easy way for them to get some points. In Java 8, there are four categories of functional interfaces in the java.util.function package: Consumer, Supplier, Function, and Predicate. A Function converts a single input into a single output. A Predicate converts an input into a boolean. The signatures for the single abstract methods in Consumer and Supplier are essentially opposites of each other: For Consumer<T>: void accept(T t) And for Supplier<T>: T get() Since a Consumer takes an input and returns nothing and a Supplier takes nothing and returns a value, they feel like opposites. If someone was to ask me what the opposite of a Consumer was, my natural thought would have been Producer, as in Producer-Consumer problem. So my (admittedly somewhat silly) question is, why isn't Supplier called Producer? Is there an obvious reason I'm missing?
Q: Why Supplier instead of Producer? This is a really simple question, but someone here must know, so here's an easy way for them to get some points. In Java 8, there are four categories of functional interfaces in the java.util.function package: Consumer, Supplier, Function, and Predicate. A Function converts a single input into a single output. A Predicate converts an input into a boolean. The signatures for the single abstract methods in Consumer and Supplier are essentially opposites of each other: For Consumer<T>: void accept(T t) And for Supplier<T>: T get() Since a Consumer takes an input and returns nothing and a Supplier takes nothing and returns a value, they feel like opposites. If someone was to ask me what the opposite of a Consumer was, my natural thought would have been Producer, as in Producer-Consumer problem. So my (admittedly somewhat silly) question is, why isn't Supplier called Producer? Is there an obvious reason I'm missing?
stackoverflow
{ "language": "en", "length": 157, "provenance": "stackexchange_0000F.jsonl.gz:844732", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479594" }
a3279cbfc54a94d764a29b18da4c568074ec0a87
Stackoverflow Stackexchange Q: Pass array to async library eachSeries - expects 'Dictionary<{}>' I have the following TypeScript code: const allDescribeBlocks: Array<ITestSuite> = suman.allDescribeBlocks; async.eachSeries(allDescribeBlocks, function (block: ITestSuite, cb: Function) { //.... }, cb); this will transpile with warnings: Argument of type ITestSuite[] is not assignable to parameter of type Dictionary<{}>. Index signature is missing in ITestSuite[]. How to fix? Here is the exact warning: A: Have you installed the latest type definition for async library? npm install --save @types/async I just checked their source and it should accept both array and collection: export function each<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void; export function each<T, E>(arr: Dictionary<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void; export const eachSeries: typeof each; I think if you install the type definition module and add the definition directory to your tsconfig.json using "typeRoots": ["node_modules/@types"], it should solve the issue. Edit - Also, you should avoid Array<T> definition for simple types and use T[] instead.
Q: Pass array to async library eachSeries - expects 'Dictionary<{}>' I have the following TypeScript code: const allDescribeBlocks: Array<ITestSuite> = suman.allDescribeBlocks; async.eachSeries(allDescribeBlocks, function (block: ITestSuite, cb: Function) { //.... }, cb); this will transpile with warnings: Argument of type ITestSuite[] is not assignable to parameter of type Dictionary<{}>. Index signature is missing in ITestSuite[]. How to fix? Here is the exact warning: A: Have you installed the latest type definition for async library? npm install --save @types/async I just checked their source and it should accept both array and collection: export function each<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void; export function each<T, E>(arr: Dictionary<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void; export const eachSeries: typeof each; I think if you install the type definition module and add the definition directory to your tsconfig.json using "typeRoots": ["node_modules/@types"], it should solve the issue. Edit - Also, you should avoid Array<T> definition for simple types and use T[] instead.
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:844751", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479657" }
6582d590913d8d13854e3049a96666b2341e2120
Stackoverflow Stackexchange Q: How to edit with multiple-selections in RStudio? names(mydata)[names(mydata)=="q1"] <- "q01" I want to select 2 mydata at the same time and then can edit them at the same time. Some advanced text editors let you have multiple cursors, so that, for example, if I select both "mydata" in this line, and then hit delete and type "otherdata", I end up with: names(otherdata)[names(otherdata)=="q1"] <- "q01" Although this can be done here with a simple search and replace, sometimes having multiple selection and multiple cursors is possibly easier. The Sublime Text editor can do this, as can Atom and Emacs. A: From Rstudio conf-2017 * *place your cursor on one of the mydata terms *Press Ctrl + Alt + Shift + M: "Rename in scope. Refactoring" This will select all the matching terms in your code *Use the arrow keys to move the multi-cursor to the position you want to start editing. *Press esc when you are finished
Q: How to edit with multiple-selections in RStudio? names(mydata)[names(mydata)=="q1"] <- "q01" I want to select 2 mydata at the same time and then can edit them at the same time. Some advanced text editors let you have multiple cursors, so that, for example, if I select both "mydata" in this line, and then hit delete and type "otherdata", I end up with: names(otherdata)[names(otherdata)=="q1"] <- "q01" Although this can be done here with a simple search and replace, sometimes having multiple selection and multiple cursors is possibly easier. The Sublime Text editor can do this, as can Atom and Emacs. A: From Rstudio conf-2017 * *place your cursor on one of the mydata terms *Press Ctrl + Alt + Shift + M: "Rename in scope. Refactoring" This will select all the matching terms in your code *Use the arrow keys to move the multi-cursor to the position you want to start editing. *Press esc when you are finished A: names(mydata)[names(mydata) %in% c("q1", "q2")] for multiple selection A: It's not clear what you are attempting, but if what you want is to change all column names of the for "q" followed by a single digit to "q0" followed by the digit (i.e. q1->q01, q2->q02, etc) just use gsub > mydata<-data.frame(1,2,3,4,5) > names(mydata) <-c('q1','q2','something','q3','q23') > names(mydata) [1] "q1" "q2" "something" "q3" "q23" > names(mydata)<-gsub("^q(\\d)$","q0\\1",names(mydata)) > names(mydata) [1] "q01" "q02" "something" "q03" "q23"
stackoverflow
{ "language": "en", "length": 229, "provenance": "stackexchange_0000F.jsonl.gz:844769", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479718" }
c3086184307a0073afef293a4760a0ece765f776
Stackoverflow Stackexchange Q: django rest swagger nested serializers not rendered properly The swagger ui doesn't render the detail fields in Title object, how can i fix this?
Q: django rest swagger nested serializers not rendered properly The swagger ui doesn't render the detail fields in Title object, how can i fix this?
stackoverflow
{ "language": "en", "length": 25, "provenance": "stackexchange_0000F.jsonl.gz:844780", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479754" }
6297a74c51300ee94c609783077e0f09a773d8b7
Stackoverflow Stackexchange Q: Get a place from the Places here-api using the id Although there is a place lookup from the ID of other Here Services (https://developer.here.com/rest-apis/documentation/places/topics_api/resource-lookup.html)... I can't find a way to lookup place details using the actual placeID... I'd like to be able to cache the id and give my user recent places they've viewed. Is this possible... in the detailed response or the searches all provide the ID... but is it useable as I describe? Sample output from Autocomplete for the Atlanta Airport is below: { "title": "ATL", "highlightedTitle": "<b>ATL</b>", "vicinity": "6000 N Terminal Pkwy<br/>College Park, GA 30320", "highlightedVicinity": "6000 N Terminal Pkwy<br/>College Park, GA 30320", "position": [ 33.640397, -84.450922 ], "category": "airport", "href": "https://places.api.here.com/places/v1/places/840djgzq-aea3f677bbd744ab855203f2ba20281b;context=Zmxvdy1pZD05MmE2ZDVkNS05MDZiLTU3YTQtOGM3NC00MTMxYjY5YzllNDlfMTQ5NzE0NTc4ODAwNl83OTUzXzcwMjEmcmFuaz0w?app_id=eo36dAgbCSxzcLGxzyjZ&app_code=jDJSp_MrBeF6jbuZXUSQqw", "type": "urn:nlp-types:place", "resultType": "place", "id": "840djgzq-aea3f677bbd744ab855203f2ba20281b" } A: To get details of particular place you need to use URL from href attribute. If you want, then you can create a map with key as a value of id attribute and value as URL from href attribute.
Q: Get a place from the Places here-api using the id Although there is a place lookup from the ID of other Here Services (https://developer.here.com/rest-apis/documentation/places/topics_api/resource-lookup.html)... I can't find a way to lookup place details using the actual placeID... I'd like to be able to cache the id and give my user recent places they've viewed. Is this possible... in the detailed response or the searches all provide the ID... but is it useable as I describe? Sample output from Autocomplete for the Atlanta Airport is below: { "title": "ATL", "highlightedTitle": "<b>ATL</b>", "vicinity": "6000 N Terminal Pkwy<br/>College Park, GA 30320", "highlightedVicinity": "6000 N Terminal Pkwy<br/>College Park, GA 30320", "position": [ 33.640397, -84.450922 ], "category": "airport", "href": "https://places.api.here.com/places/v1/places/840djgzq-aea3f677bbd744ab855203f2ba20281b;context=Zmxvdy1pZD05MmE2ZDVkNS05MDZiLTU3YTQtOGM3NC00MTMxYjY5YzllNDlfMTQ5NzE0NTc4ODAwNl83OTUzXzcwMjEmcmFuaz0w?app_id=eo36dAgbCSxzcLGxzyjZ&app_code=jDJSp_MrBeF6jbuZXUSQqw", "type": "urn:nlp-types:place", "resultType": "place", "id": "840djgzq-aea3f677bbd744ab855203f2ba20281b" } A: To get details of particular place you need to use URL from href attribute. If you want, then you can create a map with key as a value of id attribute and value as URL from href attribute.
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:844790", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479772" }
d4892254b8b9efdfb1397309d3cd85ff551bc985
Stackoverflow Stackexchange Q: How do you set a string of bytes from an environment variable in Python? Say that you have a string of bytes generated via os.urandom(24), b'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' and you'd like to store that in an environment variable, export FOO='\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' and retrieve the value from within a Python program using os.environ. foo = os.environ['FOO'] The problem is that, here, foo has the string literal value '\\x1b\\xba\\x94... instead of the byte sequence b'\x1b\xba\x94.... What is the proper export value to use, or means of using os.environ to treat FOO as a string of bytes? A: You can 'unescape' your bytes in Python with: import os import sys if sys.version_info[0] < 3: # sadly, it's done differently in Python 2.x vs 3.x foo = os.environ["FOO"].decode('string_escape') # since already in bytes... else: foo = bytes(os.environ["FOO"], "utf-8").decode('unicode_escape')
Q: How do you set a string of bytes from an environment variable in Python? Say that you have a string of bytes generated via os.urandom(24), b'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' and you'd like to store that in an environment variable, export FOO='\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' and retrieve the value from within a Python program using os.environ. foo = os.environ['FOO'] The problem is that, here, foo has the string literal value '\\x1b\\xba\\x94... instead of the byte sequence b'\x1b\xba\x94.... What is the proper export value to use, or means of using os.environ to treat FOO as a string of bytes? A: You can 'unescape' your bytes in Python with: import os import sys if sys.version_info[0] < 3: # sadly, it's done differently in Python 2.x vs 3.x foo = os.environ["FOO"].decode('string_escape') # since already in bytes... else: foo = bytes(os.environ["FOO"], "utf-8").decode('unicode_escape') A: With zwer's answer I tried the following first from bash (this is the same binary literal given by ybakos) export FOO='\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' then I launched the python shell (I have python 3.5.2) >>> import os >>> # ybakos's original binary literal >>> foo = b'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v' >>> # ewer's python 3.x solution >>> FOO = bytes(os.environ["FOO"], "utf-8").decode('unicode_escape') >>> foo == FOO False >>> ^D The last line of foo == FOO should return true, so the solution does not appear to work correctly. I noticed that there is an os.envirnb dictionary, but I couldn't figure out to set an Environment Variable to a binary literal, so I tried the following alternative which uses base64 encoding to get an ASCII version of the binary literal. First launch python shell >>> import os >>> import base64 >>> foo = os.urandom(24) >>> foo b'{\xd9q\x90\x8b\xba\xecv\xb3\xcb\x1e<\xd7\xba\xf1\xb4\x99\xf056\x90U\x16\xae' >>> foo_base64 = base64.b64encode(foo) >>> foo_base64 b'e9lxkIu67Hazyx4817rxtJnwNTaQVRau' >>> ^D Then in the bash shell export FOO_BASE64='e9lxkIu67Hazyx4817rxtJnwNTaQVRau' Then back in the python shell >>> import os >>> import base64 >>> # the original binary value from the first python shell session >>> foo = b'{\xd9q\x90\x8b\xba\xecv\xb3\xcb\x1e<\xd7\xba\xf1\xb4\x99\xf056\x90U\x16\xae' >>> dec_foo = base64.b64decode(bytes(os.environ.get('FOO_BASE64'), "utf-8")) >>> # the values match! >>> foo == dec_foo True >>> ^D The last line shows that the 2 results are the same!! What we are doing, is first getting a binary value from os.urandom() and Base64 encoding it. We then use the Base64 encoded value to set the environment variable. Note: base64.b64encode() returns a binary value, but it will only contain printable ASCII characters. Then in our program we read in the Base64 encode string value from the environment variable, convert the string into it's binary form, and finally Base64 decode it back to its original value. A: The easiest option is to simply set it as binary data in Bash. This uses ANSI string quoting and avoids the need for any sort of conversion on the Python side. export FOO=$'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'
stackoverflow
{ "language": "en", "length": 453, "provenance": "stackexchange_0000F.jsonl.gz:844807", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479826" }
840221ca581133e2f76e317b135af482e7180169
Stackoverflow Stackexchange Q: F# FS0039 namespace is not defined Here's a pic of the problem in VS2017: The compiler throws: FS0039 The namespace 'Web' is not defined. But it was ok with 'Web' in the line before it!! Of course, I have referenced System.Web.Mvc.dll. In fact the open references (and code) compiles correctly if I put it in a particular file in the same project (in this case Global.asax.fs). Update: TLDR; the problem mysteriously went away... After multiple recompiles, restarts & reboots the problem still persisted. Finally, I manually edited the file order in .fsproj (moving myfile.fs after Global.asax.fs) and it compiled! Then to check, I moved the file order back to the original order...and it still worked !?! Not sure what to say. If anyone has the same problem, know that you're not alone. Fiddle with it, wait and fiddle some more and the problem will go away ... I think...
Q: F# FS0039 namespace is not defined Here's a pic of the problem in VS2017: The compiler throws: FS0039 The namespace 'Web' is not defined. But it was ok with 'Web' in the line before it!! Of course, I have referenced System.Web.Mvc.dll. In fact the open references (and code) compiles correctly if I put it in a particular file in the same project (in this case Global.asax.fs). Update: TLDR; the problem mysteriously went away... After multiple recompiles, restarts & reboots the problem still persisted. Finally, I manually edited the file order in .fsproj (moving myfile.fs after Global.asax.fs) and it compiled! Then to check, I moved the file order back to the original order...and it still worked !?! Not sure what to say. If anyone has the same problem, know that you're not alone. Fiddle with it, wait and fiddle some more and the problem will go away ... I think...
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:844836", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44479927" }
236b3299afbb284aebd94c856d49903069043629
Stackoverflow Stackexchange Q: Wrapping a HTML element in Visual Studio Code using Emmet I am using VSC for developing html pages. It's been a great experience using emmet with VSC, but often I find in a situation where I have to wrap a set of elements with a div, but have to use emmet on a single line and then cut paste the end tag at the end of the set of elements I want to map. Is there any way where I can use emmet and automatically wrap the output of emmet around a set of selected elements? A: The easiest way is to use a key binding, you can assign your own key for this. file > preference > keyboard shortcuts > editkeybindings and assign your own [{ "key": "ctrl+shift+g", "command":"editor.emmet.action.wrapWithAbbreviation", "when": "editorTextFocus && !editorReadonly" }]
Q: Wrapping a HTML element in Visual Studio Code using Emmet I am using VSC for developing html pages. It's been a great experience using emmet with VSC, but often I find in a situation where I have to wrap a set of elements with a div, but have to use emmet on a single line and then cut paste the end tag at the end of the set of elements I want to map. Is there any way where I can use emmet and automatically wrap the output of emmet around a set of selected elements? A: The easiest way is to use a key binding, you can assign your own key for this. file > preference > keyboard shortcuts > editkeybindings and assign your own [{ "key": "ctrl+shift+g", "command":"editor.emmet.action.wrapWithAbbreviation", "when": "editorTextFocus && !editorReadonly" }] A: Try the Emmet: Wrap with Abbreviation command:
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:844876", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480051" }
f10568bbdd2bed03609a3d2a62936cc3102cd717
Stackoverflow Stackexchange Q: How to detect if screen size has changed to mobile in React? I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state. Specifically I need my sidenav to be collapsed when the user enters mobile mode and that is controlled with a boolean stored in the state within the component. A: This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount constructor() { super(); this.state = { screenWidth: null }; this.updateWindowDimensions = this.updateWindowDimensions.bind(this); } componentDidMount() { window.addEventListener("resize", this.updateWindowDimensions()); } componentWillUnmount() { window.removeEventListener("resize", this.updateWindowDimensions) } updateWindowDimensions() { this.setState({ screenWidth: window.innerWidth }); }
Q: How to detect if screen size has changed to mobile in React? I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state. Specifically I need my sidenav to be collapsed when the user enters mobile mode and that is controlled with a boolean stored in the state within the component. A: This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount constructor() { super(); this.state = { screenWidth: null }; this.updateWindowDimensions = this.updateWindowDimensions.bind(this); } componentDidMount() { window.addEventListener("resize", this.updateWindowDimensions()); } componentWillUnmount() { window.removeEventListener("resize", this.updateWindowDimensions) } updateWindowDimensions() { this.setState({ screenWidth: window.innerWidth }); } A: hey I just published a npm package for this issue. Check it out https://www.npmjs.com/package/react-getscreen import React, { Component } from 'react'; import {withGetScreen} from 'react-getscreen' class Test extends Component { render() { if (this.props.isMobile()) return <div>Mobile</div>; if (this.props.isTablet()) return <div>Tablet</div>; return <div>Desktop</div>; } } export default withGetScreen(Test); //or you may set your own breakpoints by providing an options object const options = {mobileLimit: 500, tabletLimit: 800} export default withGetScreen(Test, options); A: const [isMobile, setIsMobile] = useState(false) //choose the screen size const handleResize = () => { if (window.innerWidth < 720) { setIsMobile(true) } else { setIsMobile(false) } } // create an event listener useEffect(() => { window.addEventListener("resize", handleResize) }) // finally you can render components conditionally if isMobile is True or False A: There are multiple ways to archive this first way is with CSS using this class @media screen and (max-width: 576px) {} any class inside this tag will only be visible when the screen is equal or less than 576px the second way is to use the event listener something like this constructor(props) { super(props); this.state = { isToggle: null } this.resizeScreen = this.resizeScreen.bind(this); } componentDidMount() { window.addEventListener("resize", this.resizeScreen()); } resizeScreen() { if(window.innerWidth === 576) { this.setState({isToggle:'I was resized'}); } } even with the event listener I still prefer the CSS way since we can use multiple screen sizes without further js coding. I hope this helps! A: The react-screentype-hook library allows you to do this out of the box. https://www.npmjs.com/package/react-screentype-hook You could use the default breakpoints it provides as follows const screenType = useScreenType(); screenType has the following shape { isLargeDesktop: Boolean, isDesktop: Boolean, isMobile: Boolean, isTablet: Boolean } Or you could even configure your custom breakpoints like this const screenType = useScreenType({ mobile: 400, tablet: 800, desktop: 1000, largeDesktop: 1600 }); A: For Next.js Here is a custom hook import { useState, useEffect } from 'react'; export default function useScreenWidth() { const [windowWidth, setWindowWidth] = useState(null); const isWindow = typeof window !== 'undefined'; const getWidth = () => isWindow ? window.innerWidth : windowWidth; const resize = () => setWindowWidth(getWidth()); useEffect(() => { if (isWindow) { setWindowWidth(getWidth()); window.addEventListener('resize', resize); return () => window.removeEventListener('resize', resize); } //eslint-disable-next-line }, [isWindow]); return windowWidth; } In a component, it returns the width size of the viewport, which can then be compared with a given numeric value const widthSize = useScreenWidth() const mobileWidth = 400 if(widthSize > mobileWidth){ //logic for desktop } if(widthSize <= mobileWidth){ //logic for mobile } A: Using hooks in React(16.8.0+) refering to: https://stackoverflow.com/a/36862446/1075499 import { useState, useEffect } from 'react'; function getWindowDimensions() { const { innerWidth: width, innerHeight: height } = window; return { width, height }; } export default function useWindowDimensions() { const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions()); useEffect(() => { function handleResize() { setWindowDimensions(getWindowDimensions()); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowDimensions; } A: What I did is adding an event listener after component mount: componentDidMount() { window.addEventListener("resize", this.resize.bind(this)); this.resize(); } resize() { this.setState({hideNav: window.innerWidth <= 760}); } componentWillUnmount() { window.removeEventListener("resize", this.resize.bind(this)); } EDIT: To save state updates, I changed the "resize" a bit, just to be updated only when there is a change in the window width. resize() { let currentHideNav = (window.innerWidth <= 760); if (currentHideNav !== this.state.hideNav) { this.setState({hideNav: currentHideNav}); } } UPDATE: Time to use hooks! If you're component is functional, and you use hooks - then you can use the useMediaQuery hook, from react-responsive package. import { useMediaQuery } from 'react-responsive'; ... const isMobile = useMediaQuery({ query: `(max-width: 760px)` }); After using this hook, "isMobile" will be update upon screen resize, and will re-render the component. Much nicer! A: In Functional Component, we can detect screen size by useTheme and useMediaQuery. const theme = useTheme(); const xs = useMediaQuery(theme.breakpoints.only('xs')); const sm = useMediaQuery(theme.breakpoints.only('sm')); const md = useMediaQuery(theme.breakpoints.only('md')); const lg = useMediaQuery(theme.breakpoints.only('lg')); const xl = useMediaQuery(theme.breakpoints.only('xl'));
stackoverflow
{ "language": "en", "length": 757, "provenance": "stackexchange_0000F.jsonl.gz:844877", "question_score": "54", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480053" }
a6b6a7ae8a7f27d4d82ee16bb33ce3ff31e7af5d
Stackoverflow Stackexchange Q: How can I look up file name with specific characters I have hundreds of text files with names like: D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1 and D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3 as shown in the picture below: I would like to select files which name contain BAPN as a group and NOBAPN as another group. But BAPN and NOBAPN contain the same characters as BAPN. How can I achieve this? A: Simple regex aughta do what you're looking for: (BAPN)|(NOBAPN) can check it out here - regex101 BAPN This will capture those exact strings as separate captures without overlapping.
Q: How can I look up file name with specific characters I have hundreds of text files with names like: D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1 and D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3 as shown in the picture below: I would like to select files which name contain BAPN as a group and NOBAPN as another group. But BAPN and NOBAPN contain the same characters as BAPN. How can I achieve this? A: Simple regex aughta do what you're looking for: (BAPN)|(NOBAPN) can check it out here - regex101 BAPN This will capture those exact strings as separate captures without overlapping. A: Easy if you can use the hyphen. Select[{"D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3"}, StringMatchQ[#, "*-BAPN*"] &] {"D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1"} Otherwise use Complement to obtain the less specific case. stringlist = { "D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 1"}; posnobapn = Position[stringlist , _?(StringContainsQ[#, "NOBAPN"] &), Heads -> False]; posbapn = Position[stringlist , _?(StringContainsQ[#, "BAPN"] &), Heads -> False]; listbapn = Extract[stringlist , Complement[posbapn, posnobapn]] {"D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1"} listnobapn = Extract[stringlist , posnobapn] {"D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 1"} Also, an application of Nieminen's regular expression. regexcases = StringCases[stringlist, RegularExpression["(BAPN)|(NOBAPN)"]]; Pick[stringlist, regexcases /. {"BAPN"} -> True] {"D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N4-BAPN_633nm_20x_100%_30accu_10s_point 1"} Pick[stringlist, regexcases /. {"NOBAPN"} -> True] {"D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 3", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 2", "D14 J4N5-NOBAPN_633nm_20x_100%_30accu_10s_point 1"} A: You can also use dir command to sort the files you want. To get the file names with BAPN: set1 = dir('*-BAPN*.txt') ; To get the file names with NOBAPN set2 = dir('*-NOBAPN*.txt') ; set1 and set2 will be structures.
stackoverflow
{ "language": "en", "length": 267, "provenance": "stackexchange_0000F.jsonl.gz:844901", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480122" }
6394e86b8a122d8d4f2e670ecdfad0c4c6f6799a
Stackoverflow Stackexchange Q: How can I fit a gaussian curve in python? I'm given an array and when I plot it I get a gaussian shape with some noise. I want to fit the gaussian. This is what I already have but when I plot this I do not get a fitted gaussian, instead I just get a straight line. I've tried this many different ways and I just can't figure it out. random_sample=norm.rvs(h) parameters = norm.fit(h) fitted_pdf = norm.pdf(f, loc = parameters[0], scale = parameters[1]) normal_pdf = norm.pdf(f) plt.plot(f,fitted_pdf,"green") plt.plot(f, normal_pdf, "red") plt.plot(f,h) plt.show() A: You can use fit from scipy.stats.norm as follows: import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt data = np.random.normal(loc=5.0, scale=2.0, size=1000) mean,std=norm.fit(data) norm.fit tries to fit the parameters of a normal distribution based on the data. And indeed in the example above mean is approximately 5 and std is approximately 2. In order to plot it, you can do: plt.hist(data, bins=30, density=True) xmin, xmax = plt.xlim() x = np.linspace(xmin, xmax, 100) y = norm.pdf(x, mean, std) plt.plot(x, y) plt.show() The blue boxes are the histogram of your data, and the green line is the Gaussian with the fitted parameters.
Q: How can I fit a gaussian curve in python? I'm given an array and when I plot it I get a gaussian shape with some noise. I want to fit the gaussian. This is what I already have but when I plot this I do not get a fitted gaussian, instead I just get a straight line. I've tried this many different ways and I just can't figure it out. random_sample=norm.rvs(h) parameters = norm.fit(h) fitted_pdf = norm.pdf(f, loc = parameters[0], scale = parameters[1]) normal_pdf = norm.pdf(f) plt.plot(f,fitted_pdf,"green") plt.plot(f, normal_pdf, "red") plt.plot(f,h) plt.show() A: You can use fit from scipy.stats.norm as follows: import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt data = np.random.normal(loc=5.0, scale=2.0, size=1000) mean,std=norm.fit(data) norm.fit tries to fit the parameters of a normal distribution based on the data. And indeed in the example above mean is approximately 5 and std is approximately 2. In order to plot it, you can do: plt.hist(data, bins=30, density=True) xmin, xmax = plt.xlim() x = np.linspace(xmin, xmax, 100) y = norm.pdf(x, mean, std) plt.plot(x, y) plt.show() The blue boxes are the histogram of your data, and the green line is the Gaussian with the fitted parameters. A: There are many ways to fit a gaussian function to a data set. I often use astropy when fitting data, that's why I wanted to add this as additional answer. I use some data set that should simulate a gaussian with some noise: import numpy as np from astropy import modeling m = modeling.models.Gaussian1D(amplitude=10, mean=30, stddev=5) x = np.linspace(0, 100, 2000) data = m(x) data = data + np.sqrt(data) * np.random.random(x.size) - 0.5 data -= data.min() plt.plot(x, data) Then fitting it is actually quite simple, you specify a model that you want to fit to the data and a fitter: fitter = modeling.fitting.LevMarLSQFitter() model = modeling.models.Gaussian1D() # depending on the data you need to give some initial values fitted_model = fitter(model, x, data) And plotted: plt.plot(x, data) plt.plot(x, fitted_model(x)) However you can also use just Scipy but you have to define the function yourself: from scipy import optimize def gaussian(x, amplitude, mean, stddev): return amplitude * np.exp(-((x - mean) / 4 / stddev)**2) popt, _ = optimize.curve_fit(gaussian, x, data) This returns the optimal arguments for the fit and you can plot it like this: plt.plot(x, data) plt.plot(x, gaussian(x, *popt))
stackoverflow
{ "language": "en", "length": 387, "provenance": "stackexchange_0000F.jsonl.gz:844908", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480137" }
00e98d4bebbe22a1b4d0c408de5da56763cc235b
Stackoverflow Stackexchange Q: android signing tool PEPK lnk for download is there any link to download the PEPK tool? Currently searching for it but unable to find it out. I searched a lot, as I am new, I am little bit confused as well not able to find any secure source to download it A: When you opt in to use Google Play App Signing, you export and encrypt your app signing key using the Play Encrypt Private Key tool provided by Google Play, and then upload it to Google's infrastructure App Signing You download it from the app signing dashboard of Google Play How to enable Google Play App Signing
Q: android signing tool PEPK lnk for download is there any link to download the PEPK tool? Currently searching for it but unable to find it out. I searched a lot, as I am new, I am little bit confused as well not able to find any secure source to download it A: When you opt in to use Google Play App Signing, you export and encrypt your app signing key using the Play Encrypt Private Key tool provided by Google Play, and then upload it to Google's infrastructure App Signing You download it from the app signing dashboard of Google Play How to enable Google Play App Signing A: Download link: https://www.gstatic.com/play-apps-publisher-rapid/signing-tool/prod/pepk.jar I don't know why Google doesn't make the download link available in the development documentation, instead you have to enter to the Google Play Console, and act like you are going to opt-in to the signing process to see the link above:
stackoverflow
{ "language": "en", "length": 155, "provenance": "stackexchange_0000F.jsonl.gz:844939", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480234" }
f623bfda7d02717796788f87db90568238caa221
Stackoverflow Stackexchange Q: How to open Android Studio on Kali Linux I have installed Android Studio successfully but I don't know how to open it. I give hard effort for open it on its own folder but i didn't find anything in its destination I tried every file to open it, but it did not work. A: sudo sh /path_installed/android/bin/studio.sh
Q: How to open Android Studio on Kali Linux I have installed Android Studio successfully but I don't know how to open it. I give hard effort for open it on its own folder but i didn't find anything in its destination I tried every file to open it, but it did not work. A: sudo sh /path_installed/android/bin/studio.sh A: If you are new, I recommend install synaptic: sudo apt-get install synaptic after install it run it: sudo synaptic and then type there android, and the program will be listed A: You could add an alias for android, to run it from the terminal. Open the .bashrc file and type in alias android="sh path/to/studio.sh" and save it. Restart the terminal or source the bash by typing source .bashrc. When you want to start android, just type in android from the terminal.
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:844947", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480258" }
f95a98242780d6bdd0f7f10667af13930cc4c4e6
Stackoverflow Stackexchange Q: python dataframe to dictionary, key value issue I am creating a dataframe and then converting to a dictionary as below data = {'ID': [1,2,3,4,5], 'A':['1','2','1','3','2'], 'B':[4,6,8,2,4]} frame = pd.DataFrame(data) dict_obj = dict(frame[['A','B']].groupby('A').median().sort_values(by='B')) My problem is that I want column A as Key and column B as values but somehow I am getting a weird dictionary dict_obj {'B': A 3 2 2 5 1 6 Name: B, dtype: int64} i want dictionary object as {1:6,2:5,3:2} Could someone help please? A: Use the pd.Series.to_dict method frame.groupby('A').B.median().to_dict() {'1': 6, '2': 5, '3': 2}
Q: python dataframe to dictionary, key value issue I am creating a dataframe and then converting to a dictionary as below data = {'ID': [1,2,3,4,5], 'A':['1','2','1','3','2'], 'B':[4,6,8,2,4]} frame = pd.DataFrame(data) dict_obj = dict(frame[['A','B']].groupby('A').median().sort_values(by='B')) My problem is that I want column A as Key and column B as values but somehow I am getting a weird dictionary dict_obj {'B': A 3 2 2 5 1 6 Name: B, dtype: int64} i want dictionary object as {1:6,2:5,3:2} Could someone help please? A: Use the pd.Series.to_dict method frame.groupby('A').B.median().to_dict() {'1': 6, '2': 5, '3': 2}
stackoverflow
{ "language": "en", "length": 91, "provenance": "stackexchange_0000F.jsonl.gz:844962", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480313" }
64ed5a27baff7b5ed788b30945fb47d40d10ef25
Stackoverflow Stackexchange Q: How to add overlay on AVCaptureVideoPreviewLayer? I am building an iOS app using Swift which requires QR code scanner functionality. I have implemented a QR code scanner using AVFoundation, right now my capture screen looks same as a video recording screen i.e. AVCaptureVideoPreviewLayer shows what is being captured by the camera. But since it is a QR code scanner and not a regular image or video capture, I would like my VideoPreviewLayer to look like this: I understand this can be achieved by adding another VideoPreviewLayer on top of one VideoPreviewLayer. My questions are: * *How do I add the borders only to the edges in the upper (or smaller) preview layer? *How do I change the brightness level for the VideoPreviewLayer in the background? *How to ignore media captured by the the background layer? A: You shouldn't use another VideoPreviewLayer. Instead you should add two sublayers - one for the masked background area and one for the corners. Have a look at the source code in this repo for an example. To limit the video capturing to the masked area you have to set the rectOfInterest of your AVCaptureMetadataOutput. let rectOfInterest = videoPreviewLayer.metadataOutputRectConverted(fromLayerRect: rect) metadataOutput.rectOfInterest = rectOfInterest
Q: How to add overlay on AVCaptureVideoPreviewLayer? I am building an iOS app using Swift which requires QR code scanner functionality. I have implemented a QR code scanner using AVFoundation, right now my capture screen looks same as a video recording screen i.e. AVCaptureVideoPreviewLayer shows what is being captured by the camera. But since it is a QR code scanner and not a regular image or video capture, I would like my VideoPreviewLayer to look like this: I understand this can be achieved by adding another VideoPreviewLayer on top of one VideoPreviewLayer. My questions are: * *How do I add the borders only to the edges in the upper (or smaller) preview layer? *How do I change the brightness level for the VideoPreviewLayer in the background? *How to ignore media captured by the the background layer? A: You shouldn't use another VideoPreviewLayer. Instead you should add two sublayers - one for the masked background area and one for the corners. Have a look at the source code in this repo for an example. To limit the video capturing to the masked area you have to set the rectOfInterest of your AVCaptureMetadataOutput. let rectOfInterest = videoPreviewLayer.metadataOutputRectConverted(fromLayerRect: rect) metadataOutput.rectOfInterest = rectOfInterest A: Long story short: you can use AVCaptureVideoPreviewLayer for video capturing, create another CALayer() and use layer.insertSublayer(..., above: ...) to insert your "custom" layer above the video layer, and by custom I mean just yet another CALayer with let say layer.contents = spinner.cgImage Here's a bit more detailed instructions
stackoverflow
{ "language": "en", "length": 248, "provenance": "stackexchange_0000F.jsonl.gz:844979", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480378" }
67608e0548d7b02e9f8bae6127a4cdd61f030cd3
Stackoverflow Stackexchange Q: Where is the "Reverse Engineering" feature in Hibernate5? I'm upgrading an old project from hibernate3 to hibernate5. The project has a dependency on hbm2java (the so-called reverse engineering tool). In the old project this was executed with mvn hibernate3:hbm2java. Unfortunately, hbm2java is nowhere to be found in Hibernate5 - not in the code, not in the documentation. What is the Hibernate5 equivalent of the old hbm2java? Or in case it's no longer supported, what's the closest alternative? I'm willing to get out of Hibernate entirely, if that's what it takes to get out of Hibernate 3. A: The latest version of the hibernate-maven-plugin is 4.3.1. You would get out of hibernate 3 by using hibernate 4.3.1 naturally. It looks like the hbm2java task exists in the sources of the latest hibernate release: https://github.com/hibernate/hibernate-tools/blob/master/main/src/java/org/hibernate/tool/ant/Hbm2JavaExporterTask.java. That is what your were looking for isn't it? So it should also be possible to build the hibernate5 github project in your local maven repo and then bind the dependencies in your projects pom. At last add the appropriate task and goal in your execution section.
Q: Where is the "Reverse Engineering" feature in Hibernate5? I'm upgrading an old project from hibernate3 to hibernate5. The project has a dependency on hbm2java (the so-called reverse engineering tool). In the old project this was executed with mvn hibernate3:hbm2java. Unfortunately, hbm2java is nowhere to be found in Hibernate5 - not in the code, not in the documentation. What is the Hibernate5 equivalent of the old hbm2java? Or in case it's no longer supported, what's the closest alternative? I'm willing to get out of Hibernate entirely, if that's what it takes to get out of Hibernate 3. A: The latest version of the hibernate-maven-plugin is 4.3.1. You would get out of hibernate 3 by using hibernate 4.3.1 naturally. It looks like the hbm2java task exists in the sources of the latest hibernate release: https://github.com/hibernate/hibernate-tools/blob/master/main/src/java/org/hibernate/tool/ant/Hbm2JavaExporterTask.java. That is what your were looking for isn't it? So it should also be possible to build the hibernate5 github project in your local maven repo and then bind the dependencies in your projects pom. At last add the appropriate task and goal in your execution section. A: Suggestion#1: You can use maven ant runner. It may help. mvn antrun:run@hbm2java If you have modified templates (see the documentation) then, in pom.xml, modify the hibernate tool tag to look like: <hibernatetool templatepath="src/the/path/to/the/directory/containing/pojo/directory"> The above path must point to the parent of the directory named pojo, containing your templates. Also, if you have a custom reverse engineering strategy class the, in pom.xml add this attribute to jdbcconfiguration tag. reversestrategy="fully.qualified.name.CustomDelegatingReverseEngineeringStrategy" Resource Link: Hibernate tools reverse engineering using Maven I haven't checked it but you can try with this procedure using Hibernate 5.X version. Suggestion#2: This issue seems critical in Hibernate 5.x version. All recommendation is to use 4.3 version for reverse engineering instead of 5.x Resource Link: https://stackoverflow.com/a/37577315 Step by step tutorial to use 4.3 instead of 5.1 with pictorial view is given here: http://o7planning.org/en/10125/using-hibernate-tools-generate-entity-classes-from-tables Some issues are given below: * *Database case-sensitive issue *type mapping *table filtering *no <schema-selection> tag is specified This issues is required to resolve by hand (it's just basic XML) or you can use the Hibernate plugins, which provides a specialized editor. http://www.hibernate.org/30.html For reverse engineering rule, you can go through this tutorial: Chapter 6. Controlling reverse engineering
stackoverflow
{ "language": "en", "length": 374, "provenance": "stackexchange_0000F.jsonl.gz:844993", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480415" }
a8e4748771ea70ec26170b95216f106721f636e6
Stackoverflow Stackexchange Q: Copying code from Visual Studio Code to OneNote loses tab indentations even though syntax highlighting is retained This is how the code is copied to onenote with paste option : keep source formatting If I select paste option : "keep text only", the indentations are preserved (and syntax highlighting is gone as expected) If I copy the code to word with paste option : keep source formatting, it is copied perfectly preserving both indentation and syntax highlight. Why is indentation lost in oneNote only? Office version - 2013 VS code version - May 2017 (version 1.13) OS - Windows 10 Pro A: If you copy   fourspaces fourspaces from vscode to onenote ,onenote will show fourspaces fourspaces The code   fourspaces fourspaces in vscode is stored at clipboard like this <meta http-equiv="content-type" content="text/html; charset=utf-8"><div style="color: #bbbbbb;background-color: #282c34;font-family: Fira Code;font-weight: normal;font-size: 15px;line-height: 20px;white-space: pre;"><div><span style="color: #bbbbbb;"> fourspaces fourspaces</span></div></div> Onenote ignore spaces, but tab are formatted to &nbsp;&nbsp;&nbsp One solution is convert all indentation to tabs in your file Generally, you could add "editor.insertSpaces": false,in your user setting; VSCode - How do I set tab-space style? Or there is a vscode plugin named S.T.O.N.E, you can use it.
Q: Copying code from Visual Studio Code to OneNote loses tab indentations even though syntax highlighting is retained This is how the code is copied to onenote with paste option : keep source formatting If I select paste option : "keep text only", the indentations are preserved (and syntax highlighting is gone as expected) If I copy the code to word with paste option : keep source formatting, it is copied perfectly preserving both indentation and syntax highlight. Why is indentation lost in oneNote only? Office version - 2013 VS code version - May 2017 (version 1.13) OS - Windows 10 Pro A: If you copy   fourspaces fourspaces from vscode to onenote ,onenote will show fourspaces fourspaces The code   fourspaces fourspaces in vscode is stored at clipboard like this <meta http-equiv="content-type" content="text/html; charset=utf-8"><div style="color: #bbbbbb;background-color: #282c34;font-family: Fira Code;font-weight: normal;font-size: 15px;line-height: 20px;white-space: pre;"><div><span style="color: #bbbbbb;"> fourspaces fourspaces</span></div></div> Onenote ignore spaces, but tab are formatted to &nbsp;&nbsp;&nbsp One solution is convert all indentation to tabs in your file Generally, you could add "editor.insertSpaces": false,in your user setting; VSCode - How do I set tab-space style? Or there is a vscode plugin named S.T.O.N.E, you can use it. A: As mentioned by @rambler OneNote ignores pasted spaces, the solution is converting all spaces to tabs in your document using: ctrl+shift+p then enter convert indentation to tabs now you can copy your code without problem, if you want to make the tab indentation default you can change the setting by going to preferences and adding the following line: "editor.insertSpaces": false, A: You can use Outlook email or Microsoft Word as a placeholder. Steps: * *Copy and paste from VS Code into Outlook email or Microsoft Word document. *Copy and paste from Outlook email or Microsoft Word into OneNote.
stackoverflow
{ "language": "en", "length": 294, "provenance": "stackexchange_0000F.jsonl.gz:845002", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480438" }
9b15b2eadaf8c83bda4167e7c2da8b94785abdec
Stackoverflow Stackexchange Q: Export default const with Typescript I have this in a TS file: exports.default = module.exports; (This is to support both Node style and TS style imports.) Is there a way to create the above line of code with pure TS instead of JS? I tried this: export default const = module.exports; and that does not transpile. A: Somewhat counterintuitively, the answer appears to be: export default module.exports; that's it. however, in order to get any .d.ts files to behave correctly, you actually are best off doing this: let $exports = module.exports; export default $exports; you can read about this here: https://github.com/Microsoft/TypeScript/issues/16442
Q: Export default const with Typescript I have this in a TS file: exports.default = module.exports; (This is to support both Node style and TS style imports.) Is there a way to create the above line of code with pure TS instead of JS? I tried this: export default const = module.exports; and that does not transpile. A: Somewhat counterintuitively, the answer appears to be: export default module.exports; that's it. however, in order to get any .d.ts files to behave correctly, you actually are best off doing this: let $exports = module.exports; export default $exports; you can read about this here: https://github.com/Microsoft/TypeScript/issues/16442
stackoverflow
{ "language": "en", "length": 102, "provenance": "stackexchange_0000F.jsonl.gz:845010", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480457" }
1b54be2b8bf4806e0362d8ece04391fd712f52d0
Stackoverflow Stackexchange Q: Register and Login by Phone Number in Asp.net Core Identity Is it possible to don't use Email to register and login in asp.net core identity? Users just register by mobile number and login by SMS verification. A: If you don't rely in Username in your application, (Like you don't show it to user ever), then you can set Username to a guid and skip the email part. For registration, var identityUser = new User { Username= Guid.NewGuid(), PhoneNumber= phoneNumber }; var result = await _signInManager.UserManager.CreateAsync(identityUser, user.Password); For Login, var user = await _signInManager.UserManager.Users .SingleOrDefaultAsync(x => x.NormalizedEmail == usernameParam || x.PhoneNumber== usernameParam); if (user == null) { return Forbid(); } var result = await _signInManager.CheckPasswordSignInAsync(user, passwordParam, false); if (result.Succeeded) { // return new TokenResponse(token, refreshToken); }
Q: Register and Login by Phone Number in Asp.net Core Identity Is it possible to don't use Email to register and login in asp.net core identity? Users just register by mobile number and login by SMS verification. A: If you don't rely in Username in your application, (Like you don't show it to user ever), then you can set Username to a guid and skip the email part. For registration, var identityUser = new User { Username= Guid.NewGuid(), PhoneNumber= phoneNumber }; var result = await _signInManager.UserManager.CreateAsync(identityUser, user.Password); For Login, var user = await _signInManager.UserManager.Users .SingleOrDefaultAsync(x => x.NormalizedEmail == usernameParam || x.PhoneNumber== usernameParam); if (user == null) { return Forbid(); } var result = await _signInManager.CheckPasswordSignInAsync(user, passwordParam, false); if (result.Succeeded) { // return new TokenResponse(token, refreshToken); } A: One possible way is to setup identity as two factor authentication. Instead of email use username to store the mobile number. To do this set RequireUniqueEmail = false in ApplicationUserManager.Create. You'll need to add your own code to retrieve the number and validate it. Make sure it always has the same format as it should match the username. In the code where the username is verified skip the password check (since password is null), but do check the number. Send an SMS with code and continue with the flow. You can add your own logic to create and verify the code and how long it is valid.
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:845074", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480653" }
c81d851f721e57d12958023a6fc995783d09e12f
Stackoverflow Stackexchange Q: StackOverFlow , Twitter, ... IOS App... how they handle Scrolling in their Pages How They Handle ScrollView and SubTable? when parent scrollview is at top, scrolling up, move it to bottom and then child tableview scroll... StackOverFlow IOS APP : https://aorb.ir/content/sackoverflow.mp4 Twitter IOS APP : https://aorb.ir/content/twitter.mp4
Q: StackOverFlow , Twitter, ... IOS App... how they handle Scrolling in their Pages How They Handle ScrollView and SubTable? when parent scrollview is at top, scrolling up, move it to bottom and then child tableview scroll... StackOverFlow IOS APP : https://aorb.ir/content/sackoverflow.mp4 Twitter IOS APP : https://aorb.ir/content/twitter.mp4
stackoverflow
{ "language": "en", "length": 47, "provenance": "stackexchange_0000F.jsonl.gz:845085", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480677" }
40bd7b6d13833ba9c07b50a6bb81ae0707cc251b
Stackoverflow Stackexchange Q: Android recyclerview remove all item decorators I did this: dividerItemDecoration = new DividerItemDecoration( recyclerView.getContext(), DividerItemDecoration.VERTICAL ); recyclerView.addItemDecoration(dividerItemDecoration); Then i change devices orientation, so now i dont have that dividerItemDecoration, and i want to delete divider from recyclerView. Is it possible? A: To delete a ItemDecoration, you need to use removeItemDecoration. For your case, the code will be: recyclerView.removeItemDecoration(dividerItemDecoration);
Q: Android recyclerview remove all item decorators I did this: dividerItemDecoration = new DividerItemDecoration( recyclerView.getContext(), DividerItemDecoration.VERTICAL ); recyclerView.addItemDecoration(dividerItemDecoration); Then i change devices orientation, so now i dont have that dividerItemDecoration, and i want to delete divider from recyclerView. Is it possible? A: To delete a ItemDecoration, you need to use removeItemDecoration. For your case, the code will be: recyclerView.removeItemDecoration(dividerItemDecoration); A: adding to Szymon Chaber answer here is a kotlin extension to make it reusable: fun <T : RecyclerView> T.removeItemDecorations() { while (itemDecorationCount > 0) { removeItemDecorationAt(0) } } A: You could do it like this: while (recyclerView.getItemDecorationCount() > 0) { recyclerView.removeItemDecorationAt(0); } A: If you are using Kotlin, you can use this extension function used in Google I/O Android app fun RecyclerView.clearDecorations() { if (itemDecorationCount > 0) { for (i in itemDecorationCount - 1 downTo 0) { removeItemDecorationAt(i) } } } A: Here's the Kotlin extension function I created to remove all of a recyclerView's item decorations. /** * removes all recyclerview item decorations * */ fun RecyclerView.removeItemDecorations() { while (this.itemDecorationCount > 0) { this.removeItemDecorationAt(0) } } I use it by calling the following: recyclerView.removeItemDecorations() Don't forget to import <path to extensions file>._KotlinExtensions.removeItemDecorations at the top of whatever class you plan to use the extension function in. A: Try this, works for me: RecyclerView.ItemDecoration itemDecoration; while (recyclerView.getItemDecorationCount() > 0 &&(itemDecoration = recyclerView.getItemDecorationAt(0)) != null) { recyclerView.removeItemDecoration(itemDecoration); } A: This works for me in Kotlin: var itemDecoration: RecyclerView.ItemDecoration? = null while (recycler_view.itemDecorationCount > 0 && (recycler_view.getItemDecorationAt(0)?.let { itemDecoration = it }) != null) { recycler_view.removeItemDecoration(itemDecoration) }
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:845093", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480704" }
d06a0a8c6f8fe5c01cc86d672c1eb44c0f92ae0b
Stackoverflow Stackexchange Q: ngrx : how the reducers function are invoked, when it is invoked? I am trying my hands on ngrx library for managing the state of my application. I have gone through many ngrx documents and git pages. I understand that there are three important concept: * *Store *Reducer and *Action Store is the single source of data for our application. So any modification or retrieval of data is done through Actions. My question here is what exactly happens when an action is dispatched to the store? How does it know which reducers is to be invoked? Does it parses all the reducers registered to the store? There can be multiple actions with the same name in that case what happens? Thanks in advance. A: A picture is worth a thousand words... Source: Building a Redux Application with Angular2 Example Code: ngrx-todo-app Demo: Todo App using @ngrx/store and @ngrx/effects
Q: ngrx : how the reducers function are invoked, when it is invoked? I am trying my hands on ngrx library for managing the state of my application. I have gone through many ngrx documents and git pages. I understand that there are three important concept: * *Store *Reducer and *Action Store is the single source of data for our application. So any modification or retrieval of data is done through Actions. My question here is what exactly happens when an action is dispatched to the store? How does it know which reducers is to be invoked? Does it parses all the reducers registered to the store? There can be multiple actions with the same name in that case what happens? Thanks in advance. A: A picture is worth a thousand words... Source: Building a Redux Application with Angular2 Example Code: ngrx-todo-app Demo: Todo App using @ngrx/store and @ngrx/effects A: My question here is what exactly happens when an action is dispatched to the store? All of the registered reducers get a chance to handle the action How does it know which reducers is to be invoked? All of the registered reducers get invoked. Try putting console.logs into all the reducers and you can see for yourself. Does it parses all the reducers registered to the store? Yes There can be multiple actions with the same name in that case what happens? If you have multiple actions with the same name they would be treated the same. For example if I dispatched type "ADD" with payload 3 and then dispatched a different action called type "ADD" with payload 3 it would be the same thing. Ngrx isn't that smart. Let's say we have the following reducers: const reducers = { blog: BlogReducer, post: PostReducer, comment: CommentReducer } Say I dispatch 'ADD_COMMENT'. Basically BlogReducer will first try to handle it, followed by PostReducer, and finally by CommentReducer. The ordering is determined by how you specified the reducers object above. So if I did this: const reducers = { comment: CommentReducer, blog: BlogReducer, post: PostReducer } CommentReducer would be the first one to try and handle the 'ADD_COMMENT'.
stackoverflow
{ "language": "en", "length": 356, "provenance": "stackexchange_0000F.jsonl.gz:845097", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480712" }
ebbd37589bc00c276069a2a308962775a4904074
Stackoverflow Stackexchange Q: How can I draw a use case diagram for the report type? How can I draw a use case diagram for the following? Teachers are able to see Exam reports and administrators are able to see Entire report in The reports of my program. Actors are able to Search Reports ,save and print their reports. A: this link answer my Question. According to the Use case <<view reports>>, can we say that the diagram is correct? I need to add a constraint to describe that the admin can view all reports. This could simply be a textual note in curly brackets like { admin can view all reports} attached to the association between actor and UC.
Q: How can I draw a use case diagram for the report type? How can I draw a use case diagram for the following? Teachers are able to see Exam reports and administrators are able to see Entire report in The reports of my program. Actors are able to Search Reports ,save and print their reports. A: this link answer my Question. According to the Use case <<view reports>>, can we say that the diagram is correct? I need to add a constraint to describe that the admin can view all reports. This could simply be a textual note in curly brackets like { admin can view all reports} attached to the association between actor and UC.
stackoverflow
{ "language": "en", "length": 117, "provenance": "stackexchange_0000F.jsonl.gz:845101", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480720" }
049e429c7fa721b4188ed764873c4f1dafa1ecdb
Stackoverflow Stackexchange Q: How to set a location to be validated through GPS on Ionic 2? I'm developing an app on Ionic 2 and I would like to implement a restriction where a certain functionally can only be used if the user is GPS located on a location, or within a range, I have set on my database. For example: The user can click on the item only if he is at X. I am recently new to Ionic 2 and how GPS validation work. What would be the best approach to accomplish this restriction? A: What you're trying to accomplish is called "geofencing". Generally, your application will obtain a location and then check if the coordinates of the last known location are withing a set of predefined regions, usually in a radius around some other coordintate. Some mobile sdks provide implementation for geofencing, however since you are using ionic2 you may have to look into cordova implementations. Luckly enough, someone put an example of geofencing with ionic2 and you should definetly take a look.
Q: How to set a location to be validated through GPS on Ionic 2? I'm developing an app on Ionic 2 and I would like to implement a restriction where a certain functionally can only be used if the user is GPS located on a location, or within a range, I have set on my database. For example: The user can click on the item only if he is at X. I am recently new to Ionic 2 and how GPS validation work. What would be the best approach to accomplish this restriction? A: What you're trying to accomplish is called "geofencing". Generally, your application will obtain a location and then check if the coordinates of the last known location are withing a set of predefined regions, usually in a radius around some other coordintate. Some mobile sdks provide implementation for geofencing, however since you are using ionic2 you may have to look into cordova implementations. Luckly enough, someone put an example of geofencing with ionic2 and you should definetly take a look.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:845104", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480731" }
538abe591f6e5e95fa64ae921971aa1e0773a6bd
Stackoverflow Stackexchange Q: How to save a Docker container state I'm trying to learn the ins and outs of Docker, and I'm confused by the prospect of saving an image. I ran the basic Ubuntu image, installed Anaconda Python and a few other things...so now what's the best way to save my progress? Save, commit, export? None of these seem to work the same way as VirtualBox, which presents an obvious save-state file for your virtual machine. A: It's possible (but not recommended) by using docker commit command. You can check the following clear example: https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image
Q: How to save a Docker container state I'm trying to learn the ins and outs of Docker, and I'm confused by the prospect of saving an image. I ran the basic Ubuntu image, installed Anaconda Python and a few other things...so now what's the best way to save my progress? Save, commit, export? None of these seem to work the same way as VirtualBox, which presents an obvious save-state file for your virtual machine. A: It's possible (but not recommended) by using docker commit command. You can check the following clear example: https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image A: The usual way is at least through a docker commit: that will freeze the state of your container into a new image. But know that there is no reliable way to "save state" of container unlike virtual machine save state in Hyper-V or VMware. This is a downside also to docker. It seems it only saves the changes made to the persistent file changes. So when you spin up the container again from new images, the dependencies and all the run commands executed will not have same effect. That's why its ideal to have to changes in docker file and in short, there is no save state feature in docker system like we have in virtual machines. The memory contents are always lost. A: The usual way is at least through a docker commit: that will freeze the state of your container into a new image. Note: As commented by anchovylegend, this is not the best practice, and using a Dockerfile allows you to formally modeling the image content and ensure you can rebuild/reproduce its initial state. You can then list that image locally with docker images, and run it again. Example: $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3f279d17e0a ubuntu:12.04 /bin/bash 7 days ago Up 25 hours desperate_dubinsky 197387f1b436 ubuntu:12.04 /bin/bash 7 days ago Up 25 hours focused_hamilton $ docker commit c3f279d17e0a svendowideit/testimage:version3 f5283438590d $ docker images REPOSITORY TAG ID CREATED SIZE svendowideit/testimage version3 f5283438590d 16 seconds ago 335.7 MB After that, if you have deployed a registry server, you can push your image to said server. A: Use a Docker file for these kind of scenarios. An example case for an Ubuntu image with MongoDB: FROM ubuntu MAINTAINER Author name RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list RUN apt-get update RUN apt-get -y install apt-utils RUN apt-get -y install mongodb-10gen #RUN echo "" >> /etc/mongodb.conf CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"] Also see Best practices for writing Dockerfiles.
stackoverflow
{ "language": "en", "length": 427, "provenance": "stackexchange_0000F.jsonl.gz:845108", "question_score": "126", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480740" }
9a2646e1795344a02e18967c957f1dd24f98611e
Stackoverflow Stackexchange Q: How to load assemblies from file in dotnet core 1.1 My project was on dotnet core 1.0 and I used the below line to load assemblies from files, and it was working fine. assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName); Now I update my project to dotnet core 1.1,and I get below exception System.IO.FileLoadException: Could not load file or assembly 'PartyManagement, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly) at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath) at Tuba.Framework.Builder.MetaDataDirector.Build() in C:\projects\Tuba\Tuba\src\Framework\Tuba.Framework\Builder\MetaDataDirector.cs:line 36
Q: How to load assemblies from file in dotnet core 1.1 My project was on dotnet core 1.0 and I used the below line to load assemblies from files, and it was working fine. assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName); Now I update my project to dotnet core 1.1,and I get below exception System.IO.FileLoadException: Could not load file or assembly 'PartyManagement, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly) at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath) at Tuba.Framework.Builder.MetaDataDirector.Build() in C:\projects\Tuba\Tuba\src\Framework\Tuba.Framework\Builder\MetaDataDirector.cs:line 36
stackoverflow
{ "language": "en", "length": 78, "provenance": "stackexchange_0000F.jsonl.gz:845144", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480865" }
c2ca6069f2e54e47ec3f41d1e85895766eca1b4a
Stackoverflow Stackexchange Q: I want to use bootstrap's cdn in my react project. Where and how do I insert the cdn? I am currently working on a React single page application and I cannot figure out where and how to place the Bootstrap CDN in my project for my bootstrap to work. Also if somebody could suggest how to npm install bootstrap for your project. A: If you use create-react-app there is a file in public/index.html or let's say in your index html page which you first render use cdn there like <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"> <title>React App</title> </head>
Q: I want to use bootstrap's cdn in my react project. Where and how do I insert the cdn? I am currently working on a React single page application and I cannot figure out where and how to place the Bootstrap CDN in my project for my bootstrap to work. Also if somebody could suggest how to npm install bootstrap for your project. A: If you use create-react-app there is a file in public/index.html or let's say in your index html page which you first render use cdn there like <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"> <title>React App</title> </head> A: CDN <HTML> <head> <!-- YOU CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body></body> </HTML> npm npm install bootstrap@3 require('bootstrap') will load all of Bootstrap's jQuery plugins onto the jQuery object. The bootstrap module itself does not export anything. You can manually load Bootstrap's jQuery plugins individually by loading the /js/*.js files under the package's top-level directory. Bootstrap's package.json contains some additional metadata under the following keys: less - path to Bootstrap's main Less source file style - path to Bootstrap's non-minified CSS that's been precompiled using the default settings (no customization) A: npm install --save bootstrap after this import this in App.js import 'bootstrap/dist/css/bootstrap.min.css';
stackoverflow
{ "language": "en", "length": 236, "provenance": "stackexchange_0000F.jsonl.gz:845162", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480910" }
7d3cf23dbdf8552332c319c9efb48b677c264e9b
Stackoverflow Stackexchange Q: Listening to menu opening I have a RelativeLayout. In that I create several ToggleButton views. The user can set those ToggleButtons on and off. When the user opens the Activity's OptionMenu I want all those ToggleButtons to become OFF. To do this I am setting programmatically the ToggleButtons to OFF in the onPrepareOptionsMenu code. I have also a PopupMenu registered to a Imagebutton. I want also when the users opens the PopupMenu by clicking the Imagebutton all the ToggleButtons to become OFF. So, I am turning the togglebuttons to off in the Imagebutton's setOnClickListener code. My issue is that the updates to the Togglebuttons' state (to Off) are shown only after the OptionsMenu or the PopupMenu is closed. Instead I want all the ToggleButtons become Off as soon the user opens the menus. I thought I have to use some OnFocusChangeListener on some view. I tried to use it on the Activity's top layout but it doesn't work. How could I get the result I want? A: I found the solution myself by overriding the onWindowFocusChanged method, like this: @Override public void onWindowFocusChanged(boolean hasFocus) { if (!hasFocus) { //code to turn off togglebuttons goes here } }
Q: Listening to menu opening I have a RelativeLayout. In that I create several ToggleButton views. The user can set those ToggleButtons on and off. When the user opens the Activity's OptionMenu I want all those ToggleButtons to become OFF. To do this I am setting programmatically the ToggleButtons to OFF in the onPrepareOptionsMenu code. I have also a PopupMenu registered to a Imagebutton. I want also when the users opens the PopupMenu by clicking the Imagebutton all the ToggleButtons to become OFF. So, I am turning the togglebuttons to off in the Imagebutton's setOnClickListener code. My issue is that the updates to the Togglebuttons' state (to Off) are shown only after the OptionsMenu or the PopupMenu is closed. Instead I want all the ToggleButtons become Off as soon the user opens the menus. I thought I have to use some OnFocusChangeListener on some view. I tried to use it on the Activity's top layout but it doesn't work. How could I get the result I want? A: I found the solution myself by overriding the onWindowFocusChanged method, like this: @Override public void onWindowFocusChanged(boolean hasFocus) { if (!hasFocus) { //code to turn off togglebuttons goes here } }
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:845176", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44480949" }
cb3c59fff5602bb2ac67a65d038aa1c915bd24c0
Stackoverflow Stackexchange Q: Delete git LFS files not in repo I uploaded some files to git LFS and I went over my storage limit. Now, the files I uploaded don't show up in the repo, but I'm still over my data limit and I can't upload anything. A: Deleting local Git LFS files You can delete files from your local Git LFS cache with the git lfs prune command: $ git lfs prune ✔ 4 local objects, 33 retained Pruning 4 files, (2.1 MB) ✔ Deleted 4 files This will delete any local Git LFS files that are considered old. An old file is any file not referenced by: * *the currently checked out commit *a commit that has not yet been pushed (to origin, or whatever lfs.pruneremotetocheck is set to) *a recent commit for details please go through this link https://www.atlassian.com/git/tutorials/git-lfs
Q: Delete git LFS files not in repo I uploaded some files to git LFS and I went over my storage limit. Now, the files I uploaded don't show up in the repo, but I'm still over my data limit and I can't upload anything. A: Deleting local Git LFS files You can delete files from your local Git LFS cache with the git lfs prune command: $ git lfs prune ✔ 4 local objects, 33 retained Pruning 4 files, (2.1 MB) ✔ Deleted 4 files This will delete any local Git LFS files that are considered old. An old file is any file not referenced by: * *the currently checked out commit *a commit that has not yet been pushed (to origin, or whatever lfs.pruneremotetocheck is set to) *a recent commit for details please go through this link https://www.atlassian.com/git/tutorials/git-lfs A: Currently that is not possible via lfs command line. From the Atlassian Git LFS tutorial: The Git LFS command-line client doesn't support pruning files from the server, so how you delete them depends on your hosting provider. In Bitbucket Cloud, you can view and delete Git LFS files via Repository Settings > Git LFS GitHub even suggest recreating the repo: To remove Git LFS objects from a repository, delete and recreate the repository. When you delete a repository, any associated issues, stars, and forks are also deleted. But it is still good idea to use tools like BFG to clear out large files in history before moving around.
stackoverflow
{ "language": "en", "length": 249, "provenance": "stackexchange_0000F.jsonl.gz:845258", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481198" }
0ea7c3950b2bbae2b53e0c96a1a8a5bda9adbb73
Stackoverflow Stackexchange Q: Call super class constructor in Kotlin, Super is not an expression I have two classes Entity and Account as abstract class Entity( var id: String? = null, var created: Date? = Date()) { constructor(entity: Entity?) : this() { fromEntity(entity) } fun fromEntity(entity: Entity?): Entity { id = entity?.id created = entity?.created return this; } } and data class Account( var name: String? = null, var accountFlags: Int? = null ) : Entity() { constructor(entity: Entity) : this() { super(entity) } } Which gives me the error Super is not an expression, it can be only used in the left-hand side of a dot '.' Why cannot I do that? The following will pass the compilation error, but I am not sure if it is correct. constructor(entity: Entity) : this() { super.fromEntity(entity) } A: You can also move your primary constructor down into the class like this: data class Account: Entity { constructor(): super() constructor(var name: String? = null, var accountFlags: Int? = null): super() constructor(entity: Entity) : super(entity) } Advantage of this is, compiler will not require your secondary constructor to call primary constructor.
Q: Call super class constructor in Kotlin, Super is not an expression I have two classes Entity and Account as abstract class Entity( var id: String? = null, var created: Date? = Date()) { constructor(entity: Entity?) : this() { fromEntity(entity) } fun fromEntity(entity: Entity?): Entity { id = entity?.id created = entity?.created return this; } } and data class Account( var name: String? = null, var accountFlags: Int? = null ) : Entity() { constructor(entity: Entity) : this() { super(entity) } } Which gives me the error Super is not an expression, it can be only used in the left-hand side of a dot '.' Why cannot I do that? The following will pass the compilation error, but I am not sure if it is correct. constructor(entity: Entity) : this() { super.fromEntity(entity) } A: You can also move your primary constructor down into the class like this: data class Account: Entity { constructor(): super() constructor(var name: String? = null, var accountFlags: Int? = null): super() constructor(entity: Entity) : super(entity) } Advantage of this is, compiler will not require your secondary constructor to call primary constructor. A: You have a couple of problems in your code. First, this is the correct syntax, to call a super constructor from a secondary constructor: constructor(entity: Entity) : super(entity) Second, you can't call a super constructor from a secondary constructor if your class has a primary constructor (which your class does). Solution 1 abstract class Entity( var id: String, var created: Date ) class Account( var name: String, var accountFlags: Int, id: String, created: Date ) : Entity(id, created) { constructor(account: Account) : this(account.name, account.accountFlags, account.id, account.created) } Here, the copy constructor is in the child class which just delegates to the primary constructor. Solution 2 abstract class Entity( var id: String, var created: Date ) { constructor(entity: Entity) : this(entity.id, entity.created) } class Account : Entity { var name: String var accountFlags: Int constructor(name: String, accountFlags: Int, id: String, created: Date) : super(id, created) { this.name = name this.accountFlags = accountFlags } constructor(account: Account) : super(account) { this.name = account.name this.accountFlags = account.accountFlags } } Here I'm only using secondary constructors in the child class which lets me delegate them to individual super constructors. Notice how the code is pretty long. Solution 3 (most idiomatic) abstract class Entity { abstract var id: String abstract var created: Date } data class Account( var name: String, var accountFlags: Int, override var id: String, override var created: Date ) : Entity() Here I omitted the copy constructors and made the properties abstract so the child class has all the properties. I also made the child class a data class. If you need to clone the class, you can simply call account.copy(). A: Another option is to create companion object and provide factory method e.g. class Account constructor( var name: String? = null, var accountFlags: Int? = null, id: String?, created: Date? ) : Entity(id, created) { companion object { fun fromEntity(entity: Entity): Account { return Account(null, null, entity.id, entity.created) } } } A: Use this super<Entity>.fromEntity(entity) to call super class methods. As Documentation says: In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits many implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation (perhaps, using one of the inherited ones). To denote the supertype from which the inherited implementation is taken, we use super qualified by the supertype name in angle brackets, e.g. super. constructor(entity: Entity) : this() { super<Entity>.fromEntity(entity) } To know more read Overriding Rules
stackoverflow
{ "language": "en", "length": 595, "provenance": "stackexchange_0000F.jsonl.gz:845282", "question_score": "83", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481268" }
e39bd80ed962939e087493a74ad88a6845bf196e
Stackoverflow Stackexchange Q: Difference between removeFirstOccurrence and remove Is there any difference between the remove(Object o) method (of List interface) and removeFirstOccurrence(Object o) method (of LinkedList class) in the collections api? I could see that both does the same i.e remove first occurrence of the object in the list. A: No, there is no difference. If you look at source of removeFirstOccurrence(), you'll see: public boolean removeFirstOccurrence(Object o) { return remove(o); } The reason LinkedList has both is given in the javadoc of each: remove(Object o) Specified by: remove in interface Collection<E> Specified by: remove in interface Deque<E> Specified by: remove in interface List<E> removeFirstOccurrence(Object o) Specified by: removeFirstOccurrence in interface Deque<E>
Q: Difference between removeFirstOccurrence and remove Is there any difference between the remove(Object o) method (of List interface) and removeFirstOccurrence(Object o) method (of LinkedList class) in the collections api? I could see that both does the same i.e remove first occurrence of the object in the list. A: No, there is no difference. If you look at source of removeFirstOccurrence(), you'll see: public boolean removeFirstOccurrence(Object o) { return remove(o); } The reason LinkedList has both is given in the javadoc of each: remove(Object o) Specified by: remove in interface Collection<E> Specified by: remove in interface Deque<E> Specified by: remove in interface List<E> removeFirstOccurrence(Object o) Specified by: removeFirstOccurrence in interface Deque<E> A: Is there any difference between remove(Object o) method (of List interface) and removeFirstOccurrence(Object o) method (of LinkedList class) in collections framework? These are two distinct methods, coming from two distinct interfaces. The first one (remove(Object o)) is defined in the java.util.Collection interface. The other one (removeFirstOccurrence(Object o) is defined in the java.util.Deque interface. The first one (remove(Object o)) has a contract rather general in the Collection interface : Removes a single instance of the specified element from this collection, if it is present... But the List interface that extends Collection has a more specific contract : Removes the first occurrence of the specified element from this list, if it is present (optional operation).... One the other hand, the removeFirstOccurrence(Object o) defined in the Deque interface specifies a similar contract : Removes the first occurrence of the specified element from this deque... It turns out that the LinkedList implements both directly List and Deque. And as List.remove(Object o) and Deque.removeFirstOccurrence(Object o) specify a similar contract, it is really not surprising that the behavior and the implementation of these two methods in the LinkedList class be the same. A: No I do not think any difference is there both remove the first occurrence of element and return.More formally, removes the element with the lowest index i Java API ArrayList remove. public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } LinkedList removeFirstOccurrence if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false;
stackoverflow
{ "language": "en", "length": 435, "provenance": "stackexchange_0000F.jsonl.gz:845288", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481291" }
bdc9a17fc964c221caa086646e09f7bf0975db9d
Stackoverflow Stackexchange Q: Export Visual Studio Solution I want to export the entire solution in visual studio , so i can import that on other computer ? i searched in the net and didn't find answer to that question , also "you cant to that" is an answer. i don't want to copy and paste the entire folder , because I have several things on that folder that i don't want to copy them or start delete each file i don't need , i want to export only the things that solution used. tools or other external apps also will be welcomed thanks A: You can easily export your project files as template to reuse later but not the entire solution. So press Save All button every time you make changes to your solution projects. Than close the solution file. Go to where they are saved by default and copy entire project solution folder.
Q: Export Visual Studio Solution I want to export the entire solution in visual studio , so i can import that on other computer ? i searched in the net and didn't find answer to that question , also "you cant to that" is an answer. i don't want to copy and paste the entire folder , because I have several things on that folder that i don't want to copy them or start delete each file i don't need , i want to export only the things that solution used. tools or other external apps also will be welcomed thanks A: You can easily export your project files as template to reuse later but not the entire solution. So press Save All button every time you make changes to your solution projects. Than close the solution file. Go to where they are saved by default and copy entire project solution folder. A: Second answer would be to use cloud services or use git with visual studio else sign in and share your files to the location where ever you want.
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:845301", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481331" }
92ae2945d6a40b6ad7338480b418700b265b653b
Stackoverflow Stackexchange Q: Multiple Spring boot CommandLineRunner based on command line argument I have created spring boot application with spring cloud task which should executes a few commands(tasks). Each task/command is shorted-lived task, and all tasks are start from command line, do some short ETL job and finish execution. There is one spring boot jar which contain all the commands/tasks. Each task is CommandLineRunner, and I like to decide which tasks (one or more) will be executed based on the params from command line. What is the best practice to do so? I don't like to have dirty code which ask "if else" or something like this. A: Strangely there is not a built-in mechanism to select a set of CommandLineRunner. By default all of them are executed. I have reused - maybe improperly - the Profile mechanism, that is I have annotated each CommandLineRunner with @org.springframework.context.annotation.Profile("mycommand"), and I select the one I want to execute with the System property -Dspring.profiles.active=mycommand For more information on the Profile mechanism, please refer to https://www.baeldung.com/spring-profiles
Q: Multiple Spring boot CommandLineRunner based on command line argument I have created spring boot application with spring cloud task which should executes a few commands(tasks). Each task/command is shorted-lived task, and all tasks are start from command line, do some short ETL job and finish execution. There is one spring boot jar which contain all the commands/tasks. Each task is CommandLineRunner, and I like to decide which tasks (one or more) will be executed based on the params from command line. What is the best practice to do so? I don't like to have dirty code which ask "if else" or something like this. A: Strangely there is not a built-in mechanism to select a set of CommandLineRunner. By default all of them are executed. I have reused - maybe improperly - the Profile mechanism, that is I have annotated each CommandLineRunner with @org.springframework.context.annotation.Profile("mycommand"), and I select the one I want to execute with the System property -Dspring.profiles.active=mycommand For more information on the Profile mechanism, please refer to https://www.baeldung.com/spring-profiles A: Similar to this answer https://stackoverflow.com/a/44482525/986160 but using injection and less configuration. Having a similar requirement, what has worked for me is to have one CommandLineApps class implementing CommandLineRunner, then inject all my other command line runners as @Component and use the first argument to delegate to one of the injected runners. Please note that the injected ones should not extend CommandLineRunner and not be annotated as @SpringBootAppplication. Important: be careful though if you put the call in a crontab one call will destroy the previous one if it is not done. Here is an example: @SpringBootApplication public class CommandLineApps implements CommandLineRunner { @Autowired private FetchSmsStatusCmd fetchSmsStatusCmd; @Autowired private OffersFolderSyncCmd offersFolderSyncCmd; public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(CommandLineApps.class, args); ctx.close(); } @Override public void run(String... args) { if (args.length == 0) { return; } List<String> restOfArgs = Arrays.asList(args).subList(1, args.length); switch (args[0]) { case "fetch-sms-status": fetchSmsStatusCmd.run(restOfArgs.toArray(new String[restOfArgs.size()])); break; case "offers-folder-sync": offersFolderSyncCmd.run(restOfArgs.toArray(new String[restOfArgs.size()])); break; } } } @Component public class FetchSmsStatusCmd { [...] @Autowired dependencies public void run(String[] args) { if (args.length != 1) { logger.error("Wrong number of arguments"); return; } [...] } } A: You can also make your CommandLineRunner implementations @Component and @ConditionalOnExpression("${someproperty:false}") then have multiple profiles, that set someproperty to true to include those CommandLineRunners in the Context. @Component @Slf4j @ConditionalOnExpression("${myRunnerEnabled:false}") public class MyRunner implements CommandLineRunner { @Override public void run(String ... args) throws Exception { log.info("this ran"); } } and in the yml application-myrunner.yml myRunnerEnabled: true @SpringBootApplication public class SpringMain { public static void main(String ... args) { SpringApplication.run(SpringMain.class, args); } } A: Spring Boot runs all the CommandLineRunner or ApplicationRunner beans from the application context. You cannot select one by any args. So basically you have two possibiities: * *You have different CommandLineRunner implementations and in each you check the arguments to determine if this special CommandLineRunner should run. *You implement only one CommandLineRunner which acts as a dispatcher. Code might look something like this: This is the new Interface that your runners will implement: public interface MyCommandLineRunner { void run(String... strings) throws Exception; } You then define implementations and identify them with a name: @Component("one") public class MyCommandLineRunnerOne implements MyCommandLineRunner { private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerOne.class); @Override public void run(String... strings) throws Exception { log.info("running"); } } and @Component("two") public class MyCommandLineRunnerTwo implements MyCommandLineRunner { private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerTwo.class); @Override public void run(String... strings) throws Exception { log.info("running"); } } Then in your single CommandLineRunner implementation you get hold of the application context and resolve the required bean by name, my example uses just the first argument, and call it's MyCommandLineRunner.run()method: @Component public class CommandLineRunnerImpl implements CommandLineRunner, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void run(String... strings) throws Exception { if (strings.length < 1) { throw new IllegalArgumentException("no args given"); } String name = strings[0]; final MyCommandLineRunner myCommandLineRunner = applicationContext.getBean(name, MyCommandLineRunner.class); myCommandLineRunner.run(strings); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } A: You can have multiple CommandLineRunner in single file or application. Which one needs to be executed ( calling "run" method) decided by the one and only - Order (@Order annotation). If you need to execute multiple CommandLineRunner, write them, pass the value to Order annotation. @Bean @Order(value = 1) public CommandLineRunner demo1(CustomerRepository customerRepository){ return (args) ->{ customerRepository.save(new Customer("Viji", "Veerappan")); customerRepository.save(new Customer("Dhinesh", "Veerappan")); customerRepository.save(new Customer("Senbagavalli", "Veerappan")); }; } @Order(value = 2) public CommandLineRunner demo(CustomerRepository customerRepository){ return (args) ->{ // Save all the customers customerRepository.save(new Customer("Mahith", "Saravanan")); customerRepository.save(new Customer("Pooshi", "Saravanan")); customerRepository.save(new Customer("Dharma", "Saravanan")); customerRepository.save(new Customer("Mookayee", "Veerayandi")); customerRepository.save(new Customer("Chellammal", "Kandasamy")); //fetch all customer log.info("Fetching all the customers by findAll()"); log.info("----------------------------------------"); for(Customer customer : customerRepository.findAll()){ log.info(customer.toString()); } log.info(""); //fetch one customer by Id log.info("Fetch one customer Id by findById(1L)"); log.info("----------------------------------------"); log.info(customerRepository.findById(1L).toString()); log.info(""); //fetch by last name log.info("Fetch all customers that have lastname = Saravanan"); log.info("---------------------------------------------------"); for(Customer customer: customerRepository.findByLastName("Saravanan")){ log.info(customer.toString()); } /*customerRepository.findByLastName("Saravanan").forEach( saravanan ->{ saravanan.toString(); });*/ }; }
stackoverflow
{ "language": "en", "length": 812, "provenance": "stackexchange_0000F.jsonl.gz:845304", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481342" }
54ea34c2dd57aa58d98a90d0439ca0fb4def6816
Stackoverflow Stackexchange Q: Where to find Identity Pool Id in Cognito Where is Identity Pool in Cognito Console. In the docs mentioned: IdentityPoolId An identity pool ID in the format REGION:GUID. But I see only Pool Id and Pool ARN in the console. Which have different formats. A: If you've navigated to the dashboard, you can also pull the identity pool ID from the URL:
Q: Where to find Identity Pool Id in Cognito Where is Identity Pool in Cognito Console. In the docs mentioned: IdentityPoolId An identity pool ID in the format REGION:GUID. But I see only Pool Id and Pool ARN in the console. Which have different formats. A: If you've navigated to the dashboard, you can also pull the identity pool ID from the URL: A: After creating the user pool, If you did not create associated Identity pool, Create a new one (Identity pool) and while creating it, set it as below (or as per your needs) Once you click create, click Allow on the following screen then you will see the identity pool id like below If you already have one, The from Cognito main screen, click Manage Identity Pools, click on the pool you want to get its Id then from side menu click "Sample Code" you will see the same screen as in the above image. A: I can manage to get the IdentityPooId by aws cli: aws cognito-identity list-identity-pools --max-results 10 The command returns all of the Cognito identity pools registered for your account. { "IdentityPools": [ { "IdentityPoolId": "XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab", "IdentityPoolName": "<some custom name>" } ] } A: For folks working with AWS CloudFormation: The documentation for AWS::Cognito::IdentityPool says you can obtain the IdentityPoolId from the return value, via Ref: Return Values > Ref: When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns the IdentityPoolId, such as us-east-2:0d01f4d7-1305-4408-b437-12345EXAMPLE. With AWS CDK, you can output the IdentityPoolId this way (Python): core.CfnOutput(self, id='IdentityPoolId', value=idp.ref) Where idp is an instance of CfnIdentityPool. A: You can find Identity pool ID if you select Manage Federated Identities on the page https://eu-west-1.console.aws.amazon.com/cognito/home?region=eu-west-1 and create an Federated Identity. A: Just ran into this trying to fill out amplifyconfiguration.json. Trying to figure out which identity pool was connect to the user pool. In the management console, the name top under "User Pools | Federated Identities" is the name of the identity pool. In Federated Identities, I can find the identity pool with the same name. On the dashboard, I can see the user pool id listed as one of the authentication methods. Grab the identity pool id out of the url or from the sample code like others have mentioned. A: You can find here: Amazon Cognito -> Federated identities:
stackoverflow
{ "language": "en", "length": 392, "provenance": "stackexchange_0000F.jsonl.gz:845354", "question_score": "51", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481490" }
962e5f0ae2b80308e7d86c02f5b4a16196545d81
Stackoverflow Stackexchange Q: Difference between Int and Uint8 swift What are the differences between the data types Int & UInt8 in swift. Looks like UInt8 is used for binary data, i need to convert UInt8 to Int is this possible. A: That U in UInt stands for unsigned int. It is not just using for binary data. Uint is used for positive numbers only, like natural numbers. I recommend you to get to know how negative numbers are understood from a computer.
Q: Difference between Int and Uint8 swift What are the differences between the data types Int & UInt8 in swift. Looks like UInt8 is used for binary data, i need to convert UInt8 to Int is this possible. A: That U in UInt stands for unsigned int. It is not just using for binary data. Uint is used for positive numbers only, like natural numbers. I recommend you to get to know how negative numbers are understood from a computer. A: Int8 is an Integer type which can store positive and negative values. UInt8 is an unsigned integer which can store only positive values. You can easily convert UInt8 to Int8 but if you want to convert Int8 to UInt8 then make sure value should be positive. A: UInt8 is an 8bit store, while Int not hardly defined or defined by the compiler: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html Int could be 32 or 64 bits A: Updated for swift: Operation Output Range Bytes per Element uint8 0 to 255 1 Int - 9223372036854775808 to 9223372036854775807 2 or 4 If you want to find the max and min range of Int or UInt8: let maxIntValue = Int.max let maxUInt8Value = UInt8.max let minIntValue = Int.min let minUInt8Value = UInt8.min If you want to convert UInt8 to Int, used below simple code: func convertToInt(unsigned: UInt) -> Int { let signed = (unsigned <= UInt(Int.max)) ? Int(unsigned) : Int(unsigned - UInt(Int.max) - 1) + Int.min return signed }
stackoverflow
{ "language": "en", "length": 241, "provenance": "stackexchange_0000F.jsonl.gz:845393", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481618" }
4422880382652e5518718ce096259bbe6be5dc90
Stackoverflow Stackexchange Q: How to get feed of Telegram channel I need to show telegram channel posts in a website. but I don't know how to export telegram channel into xml. I need to have both texts and images and also other files and media like mp4 - pdf or other things. Is there any way to do that? A: In three steps: * *First you need create a bot with @botfather. Then add bot to channel. (There is no need to make bot admin.) *Second use a programming language and write a program that receives message from channel and send it to server. *Third you must provide a way in site back-end to receive posts that your program sends. For second step i suggest you to use python. there are some modules that can deal with bots.i think in your case telepot can be simplest module that do everything you need. For third step you must add more details about your site back-end. anyway i suggest you to write a Restful API for back-end and send posts to site with python requests module.
Q: How to get feed of Telegram channel I need to show telegram channel posts in a website. but I don't know how to export telegram channel into xml. I need to have both texts and images and also other files and media like mp4 - pdf or other things. Is there any way to do that? A: In three steps: * *First you need create a bot with @botfather. Then add bot to channel. (There is no need to make bot admin.) *Second use a programming language and write a program that receives message from channel and send it to server. *Third you must provide a way in site back-end to receive posts that your program sends. For second step i suggest you to use python. there are some modules that can deal with bots.i think in your case telepot can be simplest module that do everything you need. For third step you must add more details about your site back-end. anyway i suggest you to write a Restful API for back-end and send posts to site with python requests module. A: You need to use telegram API to access the content of a channel. Telegram API is fairly complicated. There are clients in different languages that makes it easier to interact with the API. I personally worked with Telethon and it's relatively simple to get it work. If you follow the directions on the home page, there is also an interactive client you can play around to get yourself familiar with how it works. If you are familiar with other languages there are clients for those languages as well. If you prefer any specific language please comment.
stackoverflow
{ "language": "en", "length": 279, "provenance": "stackexchange_0000F.jsonl.gz:845399", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481634" }
0b494ab8917bb82519e774c88308b7df02e15a9e
Stackoverflow Stackexchange Q: Enable "show_touches" via appium or adb on android emulator Is it possible to enable the "show_touches" options on android from appium? Or via adb? I have a appium test-script, which misbehaves. I have no Idea why, and I want to see where exactly it clicks. A: adb shell settings put system show_touches 1
Q: Enable "show_touches" via appium or adb on android emulator Is it possible to enable the "show_touches" options on android from appium? Or via adb? I have a appium test-script, which misbehaves. I have no Idea why, and I want to see where exactly it clicks. A: adb shell settings put system show_touches 1
stackoverflow
{ "language": "en", "length": 54, "provenance": "stackexchange_0000F.jsonl.gz:845423", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481713" }
b322aa47665b818427fbd28ea4c48ddbd3564a55
Stackoverflow Stackexchange Q: Java type inference differences between javac 1.8.0_45 and javac 1.8.0_92? I have some code that compiles with javac 1.8.0_92: public final class Either<L, R> { // ... private final L l; private final R r; // ... public <T> T join(final Function<L, T> f, final Function<R, T> g) { Preconditions.checkNotNull(f); Preconditions.checkNotNull(g); return which == LeftOrRight.LEFT ? f.apply(l) : g.apply(r); } public Optional<L> left() { return join(Optional::of, x -> Optional.empty()); } // ... } However, with javac 1.8.0_45, some extra types are required (L): public Optional<L> left() { return join(Optional::<L>of, x -> Optional.<L>empty()); } As you can imagine, this causes issues for packages that a user builds from source. * *Why is this? *Is this a bug with that particular build of Java? A: Yes, this is the JDK bug where type inference fails with nested invocations. If you set either one of the arguments to null, the code compiles. https://bugs.openjdk.java.net/browse/JDK-8055963 A fix was committed for Java 9, but they also backported it to 8u60: https://bugs.openjdk.java.net/browse/JDK-8081020
Q: Java type inference differences between javac 1.8.0_45 and javac 1.8.0_92? I have some code that compiles with javac 1.8.0_92: public final class Either<L, R> { // ... private final L l; private final R r; // ... public <T> T join(final Function<L, T> f, final Function<R, T> g) { Preconditions.checkNotNull(f); Preconditions.checkNotNull(g); return which == LeftOrRight.LEFT ? f.apply(l) : g.apply(r); } public Optional<L> left() { return join(Optional::of, x -> Optional.empty()); } // ... } However, with javac 1.8.0_45, some extra types are required (L): public Optional<L> left() { return join(Optional::<L>of, x -> Optional.<L>empty()); } As you can imagine, this causes issues for packages that a user builds from source. * *Why is this? *Is this a bug with that particular build of Java? A: Yes, this is the JDK bug where type inference fails with nested invocations. If you set either one of the arguments to null, the code compiles. https://bugs.openjdk.java.net/browse/JDK-8055963 A fix was committed for Java 9, but they also backported it to 8u60: https://bugs.openjdk.java.net/browse/JDK-8081020
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:845445", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481795" }
ae96df314e1bf624a6e2bf7fad8377f181baa9d5
Stackoverflow Stackexchange Q: Does ES6 import/export need ".js" extension? I installed chrome beta - Version 60.0.3112.24 (Official Build) beta (64-bit) In chrome://flags/ I enabled 'Experimental Web Platform features' (see https://jakearchibald.com/2017/es-modules-in-browsers) I then tried: <script type="module" src='bla/src/index.js'></script> where index.js has a line like: export { default as drawImage } from './drawImage'; This refer to an existing file drawImage.js what I get in the console is error in GET http://localhost/bla/src/drawImage If I change the export and add ".js" extension it works fine. Is this a chrome bug or does ES6 demands the extension in this case ? Also webpack builds it fine without the extension ! A: ES6 import/export need “.js” extension. There are clear instructions in node document: * *Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these. *This behavior matches how import behaves in browser environments, assuming a typically configured server. https://nodejs.org/api/esm.html#esm_import_expressions
Q: Does ES6 import/export need ".js" extension? I installed chrome beta - Version 60.0.3112.24 (Official Build) beta (64-bit) In chrome://flags/ I enabled 'Experimental Web Platform features' (see https://jakearchibald.com/2017/es-modules-in-browsers) I then tried: <script type="module" src='bla/src/index.js'></script> where index.js has a line like: export { default as drawImage } from './drawImage'; This refer to an existing file drawImage.js what I get in the console is error in GET http://localhost/bla/src/drawImage If I change the export and add ".js" extension it works fine. Is this a chrome bug or does ES6 demands the extension in this case ? Also webpack builds it fine without the extension ! A: ES6 import/export need “.js” extension. There are clear instructions in node document: * *Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these. *This behavior matches how import behaves in browser environments, assuming a typically configured server. https://nodejs.org/api/esm.html#esm_import_expressions A: No, modules don't care about extensions. It just needs to be a name that resolves to a source file. In your case, http://localhost/bla/src/drawImage is not a file while http://localhost/bla/src/drawImage.js is, so that's where there error comes from. You can either add the .js in all your import statements, or configure your server to ignore the extension, for example. Webpack does the same. A browser doesn't, because it's not allowed to rewrite urls arbitrarily. A: The extension is part of the filename. You have to put it in. As proof of this, please try the following: * *rename file to drawImage.test *edit index.js to contain './drawImage.test' Reload, and you'll see the extension js or test will be completely arbitrary, as long as you specify it in the export. Obviously, after the test revert to the correct/better js extension.
stackoverflow
{ "language": "en", "length": 296, "provenance": "stackexchange_0000F.jsonl.gz:845468", "question_score": "44", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481851" }
582132a6f92297432c5aa28384c6725aa7248be1
Stackoverflow Stackexchange Q: How to abort Jenkins build from shell script? I see that returning a non-zero integer in shell script executing on Jenkins will make the result marked as a failure. How do I make it change to Aborted? Is there a plugin to do this? Can I avoid having to use GroovyScript? A: Instead of returning a non-zero integer and having the build fail, you could trigger an Abort on the build using its Rest API within the shell build step. Example using curl: curl -XPOST $BUILD_URL/stop Example using wget: wget --post-data="" $BUILD_URL/stop
Q: How to abort Jenkins build from shell script? I see that returning a non-zero integer in shell script executing on Jenkins will make the result marked as a failure. How do I make it change to Aborted? Is there a plugin to do this? Can I avoid having to use GroovyScript? A: Instead of returning a non-zero integer and having the build fail, you could trigger an Abort on the build using its Rest API within the shell build step. Example using curl: curl -XPOST $BUILD_URL/stop Example using wget: wget --post-data="" $BUILD_URL/stop
stackoverflow
{ "language": "en", "length": 93, "provenance": "stackexchange_0000F.jsonl.gz:845498", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481928" }
aaecc592e40ad82fa3e0168b646093bea5ce0996
Stackoverflow Stackexchange Q: How to implement an abstract getter with property I have java code: public abstract class A { abstract int getA() } I tried: class B : A() { val a = 0 } Doesn't compile. class B : A() { override val a = 0 } Still doesn't compile. class B : A() { override val a: Int get () = 1 } Still doesn't compile. class B : A() { override val a: Int override get () = 1 } Still doesn't compile. class B : A() { val a: Int override get () = 1 } None of them are working. Does that mean I can only use class B : A() { override fun getA() = 1 } ? I think the last one(overriding the method) is ugly. This could be worse when you have a getter-setter pair. It's expected to override getter-setter pair with a var property, but you have to write two methods. A: According to @Miha_x64 , functions can be overriden only with a function. Seems that I was trying something impossible.
Q: How to implement an abstract getter with property I have java code: public abstract class A { abstract int getA() } I tried: class B : A() { val a = 0 } Doesn't compile. class B : A() { override val a = 0 } Still doesn't compile. class B : A() { override val a: Int get () = 1 } Still doesn't compile. class B : A() { override val a: Int override get () = 1 } Still doesn't compile. class B : A() { val a: Int override get () = 1 } None of them are working. Does that mean I can only use class B : A() { override fun getA() = 1 } ? I think the last one(overriding the method) is ugly. This could be worse when you have a getter-setter pair. It's expected to override getter-setter pair with a var property, but you have to write two methods. A: According to @Miha_x64 , functions can be overriden only with a function. Seems that I was trying something impossible.
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:845510", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44481959" }
0d45b2b11456e6f63d27379aefec0c68794390be
Stackoverflow Stackexchange Q: Deserialize array of object using jms/serializer I want to deserialize something like this: [ { "id": 42 }, { "id": 43 } ] Any idea how to do this? A: It would be $serializer->deserialize($json, 'array<T>', 'json') where T is the name of the class with the id property.
Q: Deserialize array of object using jms/serializer I want to deserialize something like this: [ { "id": 42 }, { "id": 43 } ] Any idea how to do this? A: It would be $serializer->deserialize($json, 'array<T>', 'json') where T is the name of the class with the id property. A: Let's say you have a class foo, that has an attribute with an array of bar objects. In your foo class use JMS\Serializer\Annotation\Type as Type; and annotate the attribute like this: use JMS\Serializer\Annotation\Type as Type; class foo { /** * * @Type("array<int,Namespace\To\Class\Bar>") * private $bars = array(); */ } JMS Serializer will serialize/deserialize the contents of foo automagically. This use of @Type should be utilized for all attributes of any classes you will be serializing/deserializing. This also works in situations where you are using string keys (ie. associative array structure). Just substitute "string" for int. @Type("array<string,Namespace\To\Class\Bar>")
stackoverflow
{ "language": "en", "length": 146, "provenance": "stackexchange_0000F.jsonl.gz:845536", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482033" }
d0af5bfdf237780ecb66d6720a2fff9f171a0b10
Stackoverflow Stackexchange Q: UnableToResolveError : unable to resolve module `merge` from Libraries/ART/React Native ART.js I am new to React-native. I am stuck with this error : UnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js dependencies I have used are : "dependencies": { "apsl-react-native-button": "^3.0.2", "react": "16.0.0-alpha.6", "react-native": "0.44.2", "react-native-deprecated-custom-components": "^0.1.0", ..................... }, in node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available. When I run react-native run-android command, I am facing this error. Can anyone help me in this ? A: Just need to install this module npm i --save merge
Q: UnableToResolveError : unable to resolve module `merge` from Libraries/ART/React Native ART.js I am new to React-native. I am stuck with this error : UnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js dependencies I have used are : "dependencies": { "apsl-react-native-button": "^3.0.2", "react": "16.0.0-alpha.6", "react-native": "0.44.2", "react-native-deprecated-custom-components": "^0.1.0", ..................... }, in node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available. When I run react-native run-android command, I am facing this error. Can anyone help me in this ? A: Just need to install this module npm i --save merge
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:845538", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482037" }
d8ed2e60b8fcf25add113c88cf403f2a5196648d
Stackoverflow Stackexchange Q: Removing trailing spaces with clang-format As the title says, I'm trying to get clang-format to remove the trailing white spaces of my files, but I fail to find the relevant option name. Could anyone point me to the obvious? A: clang-format does remove trailing whitespaces automatically. You can test this by e.g. clang-format -style=Google file.cpp -i. It is also useful to know most modern editors do have built-in options to do this and even more for you on save. Here are a few: * *In Sublime text settings set trim_trailing_white_space_on_save to true. *In VScode set files.trimTrailingWhitespace to true. *In Vim you need a vimrc file as described here. *etc.
Q: Removing trailing spaces with clang-format As the title says, I'm trying to get clang-format to remove the trailing white spaces of my files, but I fail to find the relevant option name. Could anyone point me to the obvious? A: clang-format does remove trailing whitespaces automatically. You can test this by e.g. clang-format -style=Google file.cpp -i. It is also useful to know most modern editors do have built-in options to do this and even more for you on save. Here are a few: * *In Sublime text settings set trim_trailing_white_space_on_save to true. *In VScode set files.trimTrailingWhitespace to true. *In Vim you need a vimrc file as described here. *etc.
stackoverflow
{ "language": "en", "length": 110, "provenance": "stackexchange_0000F.jsonl.gz:845546", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482062" }
b5ecd8c5f66feec54f0f472aa4be2ecc77338028
Stackoverflow Stackexchange Q: Create PostgreSQL dump with ONE INSERT statement instead of INSERT per row I try to do a table data dump using pg_dump, something like this: pg96\bin\pg_dump ... --format plain --section data --column-inserts --file obj.account.backup --table obj.account database_xyz Instead of getting INSERT INTO obj.account(name, email, password) VALUES ('user1','email1','password1'); INSERT INTO obj.account(name, email, password) VALUES ('user2','email2','password2'); I would like to get INSERT INTO obj.account (name, email, password) VALUES ('user1','email1','password1'), ('user2','email2','password2'); Is there a way for this without any Non-PostgreSQL postprocessing? A: There is no way to get INSERT statements like that with pg_dump.
Q: Create PostgreSQL dump with ONE INSERT statement instead of INSERT per row I try to do a table data dump using pg_dump, something like this: pg96\bin\pg_dump ... --format plain --section data --column-inserts --file obj.account.backup --table obj.account database_xyz Instead of getting INSERT INTO obj.account(name, email, password) VALUES ('user1','email1','password1'); INSERT INTO obj.account(name, email, password) VALUES ('user2','email2','password2'); I would like to get INSERT INTO obj.account (name, email, password) VALUES ('user1','email1','password1'), ('user2','email2','password2'); Is there a way for this without any Non-PostgreSQL postprocessing? A: There is no way to get INSERT statements like that with pg_dump. A: Since PostgreSQL 12 you can use pg_dump with --rows-per-insert=nrows, see https://www.postgresql.org/docs/12/app-pgdump.html I'm aware that this is an old question but I wanted to mention it in case somebody else (like me) finds this while searching for a solution. There are cases where COPY can't be used and for bigger data sets using a single INSERT statement is much faster when importing.
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:845548", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482070" }
b8514e23ca2f9baf6e29d86090858055a722dcc2
Stackoverflow Stackexchange Q: Remove lines from CSV file using Powershell I have a CSV file with logging information. Date/time info in the file is written in UNIX time-stamp format. I want to remove all lines older than 5 minutes. I use the following code to do this: $FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300 $Content = Import-Csv "logfile.csv" | where {$_.DateCompleted -gt $FiveMinutesAgo} $Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv' The CSV file looks like this: "DateInitiated";"DateStarted";"DateCompleted";"InitiatedBy";"Action";"Status" "1496659208";"1496659264";"1496752840";"administrator";"Reboot server";"Completed" No matter whether the five minutes have already passed or not, my CSV file ends up completely empty after executing the script lines above. A: I couldn't replicate it in testing (but potentially need the actual source file). I think the issue is that you need to specify both the encoding and delimiter on the Import-CSV as well (as you already have on Export). Try this: $FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300 $Content = Import-Csv "test.csv" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo} $Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'
Q: Remove lines from CSV file using Powershell I have a CSV file with logging information. Date/time info in the file is written in UNIX time-stamp format. I want to remove all lines older than 5 minutes. I use the following code to do this: $FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300 $Content = Import-Csv "logfile.csv" | where {$_.DateCompleted -gt $FiveMinutesAgo} $Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv' The CSV file looks like this: "DateInitiated";"DateStarted";"DateCompleted";"InitiatedBy";"Action";"Status" "1496659208";"1496659264";"1496752840";"administrator";"Reboot server";"Completed" No matter whether the five minutes have already passed or not, my CSV file ends up completely empty after executing the script lines above. A: I couldn't replicate it in testing (but potentially need the actual source file). I think the issue is that you need to specify both the encoding and delimiter on the Import-CSV as well (as you already have on Export). Try this: $FiveMinutesAgo=(Get-Date ((get-date).toUniversalTime()) -UFormat +%s).SubString(0,10)-300 $Content = Import-Csv "test.csv" -Delimiter ';' -Encoding UTF8 | where {$_.DateCompleted -gt $FiveMinutesAgo} $Content | Export-Csv -delimiter ";" -NoTypeInformation -encoding UTF8 -Path 'logfile.csv'
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:845550", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482074" }
e7f9a718483669030cd3a3eb6b6e58b4f89e90b0
Stackoverflow Stackexchange Q: Dataframe filtering rows by column values I have a Dataframe df Num1 Num2 one 1 0 two 3 2 three 5 4 four 7 6 five 9 8 I want to filter rows that have value bigger than 3 in Num1 and smaller than 8 in Num2. I tried this df = df[df['Num1'] > 3 and df['Num2'] < 8] but the error occurred. ValueError: The truth value of a Series is ambiguous. so I used df = df[df['Num1'] > 3] df = df[df['Num2'] < 8] I think the code can be shorter. Is there any other way? A: Yes, you can use the & operator: df = df[(df['Num1'] > 3) & (df['Num2'] < 8)] # ^ & operator This is because and works on the truthiness value of the two operands, whereas the & operator can be defined on arbitrary data structures. The brackets are mandatory here, because & binds shorter than > and <, so without brackets, Python would read the expression as df['Num1'] > (3 & df['Num2']) < 8. Note that you can use the | operator as a logical or.
Q: Dataframe filtering rows by column values I have a Dataframe df Num1 Num2 one 1 0 two 3 2 three 5 4 four 7 6 five 9 8 I want to filter rows that have value bigger than 3 in Num1 and smaller than 8 in Num2. I tried this df = df[df['Num1'] > 3 and df['Num2'] < 8] but the error occurred. ValueError: The truth value of a Series is ambiguous. so I used df = df[df['Num1'] > 3] df = df[df['Num2'] < 8] I think the code can be shorter. Is there any other way? A: Yes, you can use the & operator: df = df[(df['Num1'] > 3) & (df['Num2'] < 8)] # ^ & operator This is because and works on the truthiness value of the two operands, whereas the & operator can be defined on arbitrary data structures. The brackets are mandatory here, because & binds shorter than > and <, so without brackets, Python would read the expression as df['Num1'] > (3 & df['Num2']) < 8. Note that you can use the | operator as a logical or. A: You need add () because operator precedence with bit-wise operator &: df1 = df[(df['Num1'] > 3) & (df['Num2'] < 8)] print (df1) Num1 Num2 three 5 4 four 7 6 Better explanation is here. Or if need shortest code use query: df1 = df.query("Num1 > 3 and Num2 < 8") print (df1) Num1 Num2 three 5 4 four 7 6 df1 = df.query("Num1 > 3 & Num2 < 8") print (df1) Num1 Num2 three 5 4 four 7 6
stackoverflow
{ "language": "en", "length": 264, "provenance": "stackexchange_0000F.jsonl.gz:845554", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482095" }
ae42913d24733cbca0cd803d15f2a4ff55d28317
Stackoverflow Stackexchange Q: False error by eslint-plugin-import for webpack aliases I am using webpack's aliases in my project. Everything works fine in my original project, but when I clone the project, I get error from import/no-unresolved for my webpack aliases: Casing of $js/Controller does not match the underlying filesystem import/no-unresolved what makes it more interesting is that my project works fine. import/no-unresolved seems to send show false error. For more details, I am adding few links: .eslintrc.js, webpack.config.babel.js, Link to my Repo please let me know if you need anything else. A: I found the solution. I installed eslint-import-resolver-webpack in order to make Webpack aliases work with eslint resolver. Here is the command to install the plugin: npm install eslint-import-resolver-webpack --save-dev Here is the link to the repo
Q: False error by eslint-plugin-import for webpack aliases I am using webpack's aliases in my project. Everything works fine in my original project, but when I clone the project, I get error from import/no-unresolved for my webpack aliases: Casing of $js/Controller does not match the underlying filesystem import/no-unresolved what makes it more interesting is that my project works fine. import/no-unresolved seems to send show false error. For more details, I am adding few links: .eslintrc.js, webpack.config.babel.js, Link to my Repo please let me know if you need anything else. A: I found the solution. I installed eslint-import-resolver-webpack in order to make Webpack aliases work with eslint resolver. Here is the command to install the plugin: npm install eslint-import-resolver-webpack --save-dev Here is the link to the repo
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:845556", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482102" }
2c364ea5781122103c138ce8b9eed5750ef7f016
Stackoverflow Stackexchange Q: Git - How to remove one of two folders with the same name in remote repo I have a repository on github with two folders with the same name but different content. I would like to remove one of these folders. The problem is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep). Obviously something went wrong in an earlier commit. Any ideas how I remove one of these folder without removing the other? A: is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep). Then it is possible that a git status shows you the second one, deleted. Or that your OS was not able to load it, because it is case insensitive Register that deletion to the index, commit and push: git rm --cached -r secondFolder/ git add -A . git commit -m "delete folder" git push
Q: Git - How to remove one of two folders with the same name in remote repo I have a repository on github with two folders with the same name but different content. I would like to remove one of these folders. The problem is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep). Obviously something went wrong in an earlier commit. Any ideas how I remove one of these folder without removing the other? A: is that if I list the data in the repo locally, there is only one folder (with the content I would like to keep). Then it is possible that a git status shows you the second one, deleted. Or that your OS was not able to load it, because it is case insensitive Register that deletion to the index, commit and push: git rm --cached -r secondFolder/ git add -A . git commit -m "delete folder" git push
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:845569", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482128" }
56605cf566b07dab951e6d89715fae3b97c2568d
Stackoverflow Stackexchange Q: How to use $this in closure in php I have function like this: class Service { function delete_user($username) { ... $sessions = $this->config->sessions; $this->config->sessions = array_filter($sessions, function($session) use ($this){ return $this->get_username($session->token) != $username; }); } } but this don't work because you can't use $this inside use, is it possible to execute function which is member of class Service inside a callback? Or do I need to use for or foreach loop? A: $this is always available in (non-static) closures since PHP 5.4, no need to use it. class Service { function delete_user($username) { ... $sessions = $this->config->sessions; $this->config->sessions = array_filter($sessions, function($session) { return $this->get_username($session->token) != $username; }); } } See PHP manual - Anonymous functions - Automatic binding of $this
Q: How to use $this in closure in php I have function like this: class Service { function delete_user($username) { ... $sessions = $this->config->sessions; $this->config->sessions = array_filter($sessions, function($session) use ($this){ return $this->get_username($session->token) != $username; }); } } but this don't work because you can't use $this inside use, is it possible to execute function which is member of class Service inside a callback? Or do I need to use for or foreach loop? A: $this is always available in (non-static) closures since PHP 5.4, no need to use it. class Service { function delete_user($username) { ... $sessions = $this->config->sessions; $this->config->sessions = array_filter($sessions, function($session) { return $this->get_username($session->token) != $username; }); } } See PHP manual - Anonymous functions - Automatic binding of $this A: You can just cast it to something else: $a = $this; $this->config->sessions = array_filter($sessions, function($session) use ($a, $username){ return $a->get_username($session->token) != $username; }); You'll also need to pass $username through otherwise it'll always be true.
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:845579", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482168" }
60ffaee5d2ce4e5f4d012dcd059ce886ad3613b9
Stackoverflow Stackexchange Q: How to slice the file path in Python I am very new to Python as well a programming, and I would like to slice the folder path. For example, if my original path is: C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/ I would like to get the path like this: C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/ What are the methods of doing this in Python? A: You could use the pathlib module: from pathlib import Path pth = Path('C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/') print(pth) print(pth.parent) print(pth.parent.parent) # C:/Users/arul/Desktop/jobs/project_folder The module has a lot more of very convenient methods for handling paths: your problem could also be solved using parts like this: print('/'.join(pth.parts[:-2])) In Python 2.7 you could build your own parts function using os.path: from os import path pth = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/' def parts(pth): ret = [] head, tail = path.split(pth) if tail != '': ret.append(tail) while head != '': head, tail = path.split(head) ret.append(tail) return ret[::-1] ret = path.join(*parts(pth)[:-2]) print(ret) # C:/Users/arul/Desktop/jobs/project_folder
Q: How to slice the file path in Python I am very new to Python as well a programming, and I would like to slice the folder path. For example, if my original path is: C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/ I would like to get the path like this: C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/ What are the methods of doing this in Python? A: You could use the pathlib module: from pathlib import Path pth = Path('C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/') print(pth) print(pth.parent) print(pth.parent.parent) # C:/Users/arul/Desktop/jobs/project_folder The module has a lot more of very convenient methods for handling paths: your problem could also be solved using parts like this: print('/'.join(pth.parts[:-2])) In Python 2.7 you could build your own parts function using os.path: from os import path pth = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/' def parts(pth): ret = [] head, tail = path.split(pth) if tail != '': ret.append(tail) while head != '': head, tail = path.split(head) ret.append(tail) return ret[::-1] ret = path.join(*parts(pth)[:-2]) print(ret) # C:/Users/arul/Desktop/jobs/project_folder A: If you just want to split on elements, then use this. >>> path = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/' >>> path.split('elements')[0] 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/' One drawback of this approach is that it'll fail if you encounter the word elements in your path multiple times. In that case, you can do something like: >>> '/'.join(path.split('/')[:-3]) + '/' 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/' Assuming you know the depth of the path you need. A: You can do something like this: folder = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/' folder.rsplit('/', 3)[0] str.rsplit() basically returns a list of the words in the string, separated by the delimiter string (starting from right). Please have a look at documentation for more details on this method.
stackoverflow
{ "language": "en", "length": 253, "provenance": "stackexchange_0000F.jsonl.gz:845584", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482190" }
52dbbb8141fd4ac843643bd06e11149b9bffa57b
Stackoverflow Stackexchange Q: Add ARM system image to Android Studio AVD manager I have a 64 bit OS, unfortunately my CPU is not supporting VT-x (as it is an Intel CPU it is not supporting also SVM). It means that normal system image is not usable in Android Studio. Help in Android Studio mentions that one may use Android Virtual Device based on an ARM system image Armeabi-v7a from "other images" is mentioned in Android Studio - How Can I Make an AVD With ARM Instead of HAXM? as one that should work, unfortunately also system images with "Armeabi-v7a" ABI are listed as requiring VT-x How one may add ARM system image to this list? versions: Ubuntu 16.04 64 bit, Android Studio 2.3.3, Intel(R) Core(TM)2 Duo CPU T6600 @ 2.20GHz CPU (according to /proc/cpuinfo)
Q: Add ARM system image to Android Studio AVD manager I have a 64 bit OS, unfortunately my CPU is not supporting VT-x (as it is an Intel CPU it is not supporting also SVM). It means that normal system image is not usable in Android Studio. Help in Android Studio mentions that one may use Android Virtual Device based on an ARM system image Armeabi-v7a from "other images" is mentioned in Android Studio - How Can I Make an AVD With ARM Instead of HAXM? as one that should work, unfortunately also system images with "Armeabi-v7a" ABI are listed as requiring VT-x How one may add ARM system image to this list? versions: Ubuntu 16.04 64 bit, Android Studio 2.3.3, Intel(R) Core(TM)2 Duo CPU T6600 @ 2.20GHz CPU (according to /proc/cpuinfo)
stackoverflow
{ "language": "en", "length": 132, "provenance": "stackexchange_0000F.jsonl.gz:845609", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482279" }
5fcc08877f6225076da40908eb7683a004981b4d
Stackoverflow Stackexchange Q: Composer branch aliases in different branches I was wondering if the branch-alias property of a composer package differs in different branches. e.g: composer.json of the master branch contains: "branch-alias": { "dev-master": "3.0.x-dev", "dev-foo": "3.1.x-dev } and for the foo branch, composer.json contains: "branch-alias": { "dev-master": 3.0.x-dev, "dev-foo": "3.2.x-dev, "dev-bar": "3.3.x-dev } Now the following questions need to be answered: * *What version will the foo branch be aliased as, since the aliases are different in the master and the foo branch? *Will the bar branch's alias take effect since it is not included in the master branch?
Q: Composer branch aliases in different branches I was wondering if the branch-alias property of a composer package differs in different branches. e.g: composer.json of the master branch contains: "branch-alias": { "dev-master": "3.0.x-dev", "dev-foo": "3.1.x-dev } and for the foo branch, composer.json contains: "branch-alias": { "dev-master": 3.0.x-dev, "dev-foo": "3.2.x-dev, "dev-bar": "3.3.x-dev } Now the following questions need to be answered: * *What version will the foo branch be aliased as, since the aliases are different in the master and the foo branch? *Will the bar branch's alias take effect since it is not included in the master branch?
stackoverflow
{ "language": "en", "length": 98, "provenance": "stackexchange_0000F.jsonl.gz:845653", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482389" }
35e8bed7f4e9148aff3de0b6e2b6c2ed06e6bf2e
Stackoverflow Stackexchange Q: AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 on Windows I have this problem after upgrade AndroidStudio to 3.0 Canary 1 Error:D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:911 invalid drawable Error:java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed: Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed: aapt2 compile -o D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\res\merged\debug D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml Issues: - ERROR: D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:911 invalid drawable It look same AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 but I can not find the way to make it work on Window Any help or suggestion would be great appreciated. A: did you see this https://www.reddit.com/r/androiddev/comments/4u0gw1/support_library_2411_released/ If you are using support libraries on version 24.x (you or even your dependencies), this is incompatible with AAPT2 and you should : * *disbale aapt2 in your gradle.properties file :android.enableAapt2=false *or upgrade google libraries to version 25 or 26
Q: AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 on Windows I have this problem after upgrade AndroidStudio to 3.0 Canary 1 Error:D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:911 invalid drawable Error:java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed: Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed: aapt2 compile -o D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\res\merged\debug D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml Issues: - ERROR: D:\Project\Freelance\Andoid\sosokan-android\sosokan-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:911 invalid drawable It look same AAPT2 compile failed: invalid dimen on Android 3.0 Canary 1 but I can not find the way to make it work on Window Any help or suggestion would be great appreciated. A: did you see this https://www.reddit.com/r/androiddev/comments/4u0gw1/support_library_2411_released/ If you are using support libraries on version 24.x (you or even your dependencies), this is incompatible with AAPT2 and you should : * *disbale aapt2 in your gradle.properties file :android.enableAapt2=false *or upgrade google libraries to version 25 or 26 A: @Phan Van Linh, can you please check the line from "values.xml:911" where you are getting the invalid drawable issue & google it exactly? I had the same issue with one of my project and the problematic line was: <item name="crop_image_menu_crop" type="drawable"/> It was from an image library I had used in my project. The issue was that I was using an older version of the library. Once I updated to newer version, the error was gone. Hopefully, your issue might get fixed like mine. Happy Hunting!
stackoverflow
{ "language": "en", "length": 222, "provenance": "stackexchange_0000F.jsonl.gz:845661", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482431" }
860fba478702792b0a1152294c0cc55cd2fa2f34
Stackoverflow Stackexchange Q: How does a function call give a compile-time type? #include <range/v3/all.hpp> using namespace ranges; template<typename I, typename O> tagged_pair<tag::in(I), tag::out(O)> f(I i, O o) { return { i, o }; } int main() { char buf[8]{}; f(std::begin(buf), std::end(buf)); } The code uses range-v3 and can be compiled with clang. However, I cannot understand why the line tagged_pair<tag::in(I), tag::out(O)> is legal. I is a type, tag::in(I) is also a type, and tag::in is not a macro, how does tag::in(I) give a type at compile-time? See also http://en.cppreference.com/w/cpp/experimental/ranges/algorithm/copy A: It is a type of a function accepting I and returning tag::in, which is also a type. This is used, for example in std::function, like std::function<void(int)>.
Q: How does a function call give a compile-time type? #include <range/v3/all.hpp> using namespace ranges; template<typename I, typename O> tagged_pair<tag::in(I), tag::out(O)> f(I i, O o) { return { i, o }; } int main() { char buf[8]{}; f(std::begin(buf), std::end(buf)); } The code uses range-v3 and can be compiled with clang. However, I cannot understand why the line tagged_pair<tag::in(I), tag::out(O)> is legal. I is a type, tag::in(I) is also a type, and tag::in is not a macro, how does tag::in(I) give a type at compile-time? See also http://en.cppreference.com/w/cpp/experimental/ranges/algorithm/copy A: It is a type of a function accepting I and returning tag::in, which is also a type. This is used, for example in std::function, like std::function<void(int)>.
stackoverflow
{ "language": "en", "length": 114, "provenance": "stackexchange_0000F.jsonl.gz:845688", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482513" }
077cb642bae913a76343bc05359b1c2e2a09df38
Stackoverflow Stackexchange Q: IBM MobileFirst Platform Installation in Windows 8.1 64Bit I am using my office laptop (Lenovo vV310 - 8GB RAM - 64 Bit OS - Windows 8.1). I have been trying to fix an installation issue with IBM Mobile First Platform for the past few days. I downloaded the IBM Mobile First Developer Kit from link http://public.dhe.ibm.com/ibmdl/export/pub/software/products/en/MobileFirstPlatform/mobilefirst-deved-devkit-windows-8.0.0.0.exe The problem is the installation software InstallAnywhere is not installing and gives the below warning. Windows error 2 occured while loading the Java VM I have JDK 1.8 installed in my notebook and I couldn't fix the issue. I have the java JDK and JRE bin paths set in the environment variables. If any of you have fixed the issue, please share the solution. A: Open command line as Administrator and type following command. [path of mobilefirst-devkit.exe] LAX_VM ["path of java.exe"] Usage C:\Users\gaurab\Downloads\mobilefirst-deved-devkit-windows-8.0.0.0.exe LAX_VM "C:\Program Files\Java\jdk1.8.0_112\bin\java.exe"
Q: IBM MobileFirst Platform Installation in Windows 8.1 64Bit I am using my office laptop (Lenovo vV310 - 8GB RAM - 64 Bit OS - Windows 8.1). I have been trying to fix an installation issue with IBM Mobile First Platform for the past few days. I downloaded the IBM Mobile First Developer Kit from link http://public.dhe.ibm.com/ibmdl/export/pub/software/products/en/MobileFirstPlatform/mobilefirst-deved-devkit-windows-8.0.0.0.exe The problem is the installation software InstallAnywhere is not installing and gives the below warning. Windows error 2 occured while loading the Java VM I have JDK 1.8 installed in my notebook and I couldn't fix the issue. I have the java JDK and JRE bin paths set in the environment variables. If any of you have fixed the issue, please share the solution. A: Open command line as Administrator and type following command. [path of mobilefirst-devkit.exe] LAX_VM ["path of java.exe"] Usage C:\Users\gaurab\Downloads\mobilefirst-deved-devkit-windows-8.0.0.0.exe LAX_VM "C:\Program Files\Java\jdk1.8.0_112\bin\java.exe"
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:845740", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482679" }
7847e1b6949a8671014e94e133e668643e736b7a
Stackoverflow Stackexchange Q: Cloud Functions for Firebase - write to database when a new user created I am pretty new Cloud Functions for Firebase and the javascript language. I am trying to add a function every time a user created to write into the database. This is my code: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.addAccount = functions.auth.user().onCreate(event => { const user = event.data; // The firebase user const id = user.uid; const displayName = user.displayName; const photoURL = user.photoURL; return admin.database().ref.child("/users/${id}/info/status").set("ok");} ); what I am trying to do is every time a user signup to my app, the functions wil write into the database that his status is "OK". But my code dosn't work. what am I doing wrong? A: I found the problem. The problem is that shouldn't use the ${id}, and I shouldn't have use the child. So the code should look like this: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.addAccount = functions.auth.user().onCreate(event => { const user = event.data; // The firebase user const id = user.uid; const displayName = user.displayName; const photoURL = user.photoURL; return admin.database().ref("/users/"+id+"/info/status").set("ok"); });
Q: Cloud Functions for Firebase - write to database when a new user created I am pretty new Cloud Functions for Firebase and the javascript language. I am trying to add a function every time a user created to write into the database. This is my code: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.addAccount = functions.auth.user().onCreate(event => { const user = event.data; // The firebase user const id = user.uid; const displayName = user.displayName; const photoURL = user.photoURL; return admin.database().ref.child("/users/${id}/info/status").set("ok");} ); what I am trying to do is every time a user signup to my app, the functions wil write into the database that his status is "OK". But my code dosn't work. what am I doing wrong? A: I found the problem. The problem is that shouldn't use the ${id}, and I shouldn't have use the child. So the code should look like this: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.addAccount = functions.auth.user().onCreate(event => { const user = event.data; // The firebase user const id = user.uid; const displayName = user.displayName; const photoURL = user.photoURL; return admin.database().ref("/users/"+id+"/info/status").set("ok"); });
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:845773", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482792" }
b86868f1e8dd02282362945fab7d80fe1a7f27b5
Stackoverflow Stackexchange Q: NoUiSlider not visible I am truing to use noUiSlider in my react application. I have done the initialization in my componentDidMount method but noUiSlider is not visibble. I am not getting any error in console. The element list also shows that nouislider is present on page, but I cannot see it. import noUiSlider from 'nouislider' class AppBarComponent extends Component { componentDidMount(){ var noUi_slider = document.getElementById('noUiSlider'); $(function () { noUiSlider.create(noUi_slider, { start: [20, 80], connect: true, range: { 'min': 0, 'max': 100 } }); } componentWillUnmount(){} render() { return ( <div> <div id="noUiSlider" className="bg-success"></div> </div> ); } }; A: Your first arg to create is "noUi_slider" but your div id is "noUiSlider" Spell these exactly the same.
Q: NoUiSlider not visible I am truing to use noUiSlider in my react application. I have done the initialization in my componentDidMount method but noUiSlider is not visibble. I am not getting any error in console. The element list also shows that nouislider is present on page, but I cannot see it. import noUiSlider from 'nouislider' class AppBarComponent extends Component { componentDidMount(){ var noUi_slider = document.getElementById('noUiSlider'); $(function () { noUiSlider.create(noUi_slider, { start: [20, 80], connect: true, range: { 'min': 0, 'max': 100 } }); } componentWillUnmount(){} render() { return ( <div> <div id="noUiSlider" className="bg-success"></div> </div> ); } }; A: Your first arg to create is "noUi_slider" but your div id is "noUiSlider" Spell these exactly the same.
stackoverflow
{ "language": "en", "length": 117, "provenance": "stackexchange_0000F.jsonl.gz:845777", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482803" }
c7604595bf4138fa79b25fbd18f3215e64525882
Stackoverflow Stackexchange Q: Can you implement PayPal Adaptive Payments with the Customer Leaving Your Site? Is there any way to implement PayPal Adaptive Payments without the customer ever leaving your site? The documentation outlines using an embedded lightbox, but unless the user is already logged in to PayPal (which they almost never are), then it just opens a new window. Theres also no way to control how the lightbox / iframe is displayed - and it looks terrible! I have seen on some sites where the PayPal payments form is embedded in an iframe on a page, but I can't see any documentation supporting that. I'd be happy to pay for Payments Pro if that would enable it - but I cant find any examples / samples that show using Payments Pro with Adaptive Payments. Any help or pointers would be greatly appreciated. Matt A: You can also dynamically select your hosted pages Layout template using the form post TEMPLATE parameter. This will override your default Layout template set in PayPal Manager.
Q: Can you implement PayPal Adaptive Payments with the Customer Leaving Your Site? Is there any way to implement PayPal Adaptive Payments without the customer ever leaving your site? The documentation outlines using an embedded lightbox, but unless the user is already logged in to PayPal (which they almost never are), then it just opens a new window. Theres also no way to control how the lightbox / iframe is displayed - and it looks terrible! I have seen on some sites where the PayPal payments form is embedded in an iframe on a page, but I can't see any documentation supporting that. I'd be happy to pay for Payments Pro if that would enable it - but I cant find any examples / samples that show using Payments Pro with Adaptive Payments. Any help or pointers would be greatly appreciated. Matt A: You can also dynamically select your hosted pages Layout template using the form post TEMPLATE parameter. This will override your default Layout template set in PayPal Manager.
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:845778", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482805" }
cd3a0d94fd451c3dacc8fdbeb65ac0b689a955e0
Stackoverflow Stackexchange Q: MediaSource does not support ogg audio? MediaSource.isTypeSupported('audio/ogg; codecs="vorbis"') return false - is it mean that I can not stream ogg as a response from POST? A: That's exactly what it means. The clients which return false for this condition cannot play this media type (older browsers, unsupported OS or client settings which prevent this). For streaming OGG file formats you can definitly use Audio.play(); on most modern browsers, but unfortunately the MediaSource element does not support streaming with POST request - you would have to use the classic streaming method, or download the entire source file as a whole and then play it.
Q: MediaSource does not support ogg audio? MediaSource.isTypeSupported('audio/ogg; codecs="vorbis"') return false - is it mean that I can not stream ogg as a response from POST? A: That's exactly what it means. The clients which return false for this condition cannot play this media type (older browsers, unsupported OS or client settings which prevent this). For streaming OGG file formats you can definitly use Audio.play(); on most modern browsers, but unfortunately the MediaSource element does not support streaming with POST request - you would have to use the classic streaming method, or download the entire source file as a whole and then play it.
stackoverflow
{ "language": "en", "length": 104, "provenance": "stackexchange_0000F.jsonl.gz:845821", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44482967" }
566e6079b07448344a0f763917fbef6ed6e9342f
Stackoverflow Stackexchange Q: How to bind a click event on “v-html” in Vue I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way? https://jsfiddle.net/limingyang/bnLmx1en/1/ <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <div v-html="link"></div> </div> var app = new Vue({ el: '#app', data: { link: '<a href="javascript:void(0)">click me</a>' } }) A: You can add a ref on your div, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted hook: var app = new Vue({ el: '#app', data: { link: '<a href="#">click me</a>' }, mounted() { this.$refs['mydiv'].firstChild.addEventListener('click', function(event) { event.preventDefault(); console.log('clicked: ', event.target); }) } }) <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <div v-html="link" ref="mydiv"></div> <!-- notice 'ref' --> </div>
Q: How to bind a click event on “v-html” in Vue I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way? https://jsfiddle.net/limingyang/bnLmx1en/1/ <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <div v-html="link"></div> </div> var app = new Vue({ el: '#app', data: { link: '<a href="javascript:void(0)">click me</a>' } }) A: You can add a ref on your div, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted hook: var app = new Vue({ el: '#app', data: { link: '<a href="#">click me</a>' }, mounted() { this.$refs['mydiv'].firstChild.addEventListener('click', function(event) { event.preventDefault(); console.log('clicked: ', event.target); }) } }) <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <div v-html="link" ref="mydiv"></div> <!-- notice 'ref' --> </div> A: For people having problem with @tony19 solution: If your v-html is dynamically updated and you want to do something on the element you have to use Vue.nextTick(() => {}); Because you have to wait for the DOM to create the element before accessing its child nodes.
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:845870", "question_score": "21", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483117" }
b9ce9139faa98df52f0459b73756ed473516f0ab
Stackoverflow Stackexchange Q: how to escape quotes in gremlin queries I have this query and as you firstName contains single quote Anthony O'Neil :> g.addV('person') .property('firstName', 'Anthony O'Neil') .property('lastName', 'Andersen') .property('age', 44) Any Ideas how to escape it? A: Escape the apostrophe using \ So your Gremlin becomes: :> g.addV('person') .property('firstName', 'Anthony O\'Neil') .property('lastName', 'Andersen') .property('age', 44)
Q: how to escape quotes in gremlin queries I have this query and as you firstName contains single quote Anthony O'Neil :> g.addV('person') .property('firstName', 'Anthony O'Neil') .property('lastName', 'Andersen') .property('age', 44) Any Ideas how to escape it? A: Escape the apostrophe using \ So your Gremlin becomes: :> g.addV('person') .property('firstName', 'Anthony O\'Neil') .property('lastName', 'Andersen') .property('age', 44) A: Found out the answer for encoding use this: encodeURIComponent("Anthony O'Neil").replace(/[!'()*]/g, escape) and the output is: Anthony%20O%27Neil for decoding use this: decodeURIComponent("Anthony%20O%27Neil") and you will get back Anthony O'Neil if you just want to escape the single quote use this for encoding: "Anthony O'Neill".replace(/[!'()*]/g, escape) output: Anthony O%27Neill and the same function above for decoding
stackoverflow
{ "language": "en", "length": 110, "provenance": "stackexchange_0000F.jsonl.gz:845891", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483185" }
255a4d8675032f30271a26e1f2622f6cc00726a5
Stackoverflow Stackexchange Q: Is using batch size as 'powers of 2' faster on tensorflow? I read from somewhere that if you choose a batch size that is a power 2, training will be faster. What is this rule? Is this applicable to other applications? Can you provide a reference paper? A: The notion comes from aligning computations (C) onto the physical processors (PP) of the GPU. Since the number of PP is often a power of 2, using a number of C different from a power of 2 leads to poor performance. You can see the mapping of the C onto the PP as a pile of slices of size the number of PP. Say you've got 16 PP. You can map 16 C on them : 1 C is mapped onto 1 PP. You can map 32 C on them : 2 slices of 16 C , 1 PP will be responsible for 2 C. This is due to the SIMD paradigm used by GPUs. This is often called Data Parallelism : all the PP do the same thing at the same time but on different data.
Q: Is using batch size as 'powers of 2' faster on tensorflow? I read from somewhere that if you choose a batch size that is a power 2, training will be faster. What is this rule? Is this applicable to other applications? Can you provide a reference paper? A: The notion comes from aligning computations (C) onto the physical processors (PP) of the GPU. Since the number of PP is often a power of 2, using a number of C different from a power of 2 leads to poor performance. You can see the mapping of the C onto the PP as a pile of slices of size the number of PP. Say you've got 16 PP. You can map 16 C on them : 1 C is mapped onto 1 PP. You can map 32 C on them : 2 slices of 16 C , 1 PP will be responsible for 2 C. This is due to the SIMD paradigm used by GPUs. This is often called Data Parallelism : all the PP do the same thing at the same time but on different data. A: Algorithmically speaking, using larger mini-batches allows you to reduce the variance of your stochastic gradient updates (by taking the average of the gradients in the mini-batch), and this in turn allows you to take bigger step-sizes, which means the optimization algorithm will make progress faster. However, the amount of work done (in terms of number of gradient computations) to reach a certain accuracy in the objective will be the same: with a mini-batch size of n, the variance of the update direction will be reduced by a factor n, so the theory allows you to take step-sizes that are n times larger, so that a single step will take you roughly to the same accuracy as n steps of SGD with a mini-batch size of 1. As for tensorFlow, I found no evidence of your affirmation, and its a question that has been closed on github : https://github.com/tensorflow/tensorflow/issues/4132 Note that image resized to power of two makes sense (because pooling is generally done in 2X2 windows), but that’s a different thing altogether. A: I've heard this, too. Here's a white paper about training on CIFAR-10 where some Intel researchers make the claim: In general, the performance of processors is better if the batch size is a power of 2. (See: https://software.intel.com/en-us/articles/cifar-10-classification-using-intel-optimization-for-tensorflow.) However, it's unclear just how big the advantage may be because the authors don't provide any training duration data :/
stackoverflow
{ "language": "en", "length": 418, "provenance": "stackexchange_0000F.jsonl.gz:845906", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483233" }
8501e630e581b537ea635f2de8f768f78d5b3f8e
Stackoverflow Stackexchange Q: What is the data type of a single character in a string as an array? string s; cin>>s; suppose s = "stackoverflow" now if we access s[3], it should give out 'c' will s[3] be 'c' or "c"? as in will it be a char data type or string data type? A: It returns reference to the character as the operator [] is overloaded for std::string char& operator[] (size_t pos); const char& operator[] (size_t pos) const; will s[3] be 'c' or "c"? Character 'c', not string "c".
Q: What is the data type of a single character in a string as an array? string s; cin>>s; suppose s = "stackoverflow" now if we access s[3], it should give out 'c' will s[3] be 'c' or "c"? as in will it be a char data type or string data type? A: It returns reference to the character as the operator [] is overloaded for std::string char& operator[] (size_t pos); const char& operator[] (size_t pos) const; will s[3] be 'c' or "c"? Character 'c', not string "c". A: std::string is not a built-in type, so operator [] in s[3] is a call to a member function defining this operator in the string template. You can find the type by looking up the reference page for operator []: Returns a reference to the character at specified location pos. To look up the type reference and const_reference from the documentation see "member types" section of std::basic_string<CharT> template. If you are looking for std::string of length 1 starting at location 3, use substr instead: s.substr(3, 1); // This produces std::string containing "c" A: It is easiest to remember that std::string is not a native type like char is, but a wrapper class that contains an array of chars to form a string. std::string simply overloads the C array operator [] to return the char at a given index, hence: will s[3] be 'c' or "c"? Answer: 'c'
stackoverflow
{ "language": "en", "length": 235, "provenance": "stackexchange_0000F.jsonl.gz:845908", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483247" }
0e16ae9cfcfa6765a07edd9137e87b9fffc1e0ef
Stackoverflow Stackexchange Q: Next Button like Navigation's Back Button I want to display Next Button just like Back Button but the rightBarButton does not touch to end of the screen like the back barButton. let button = UIButton(type: .system) button.setImage(UIImage(named: "ic_next_button"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x button.setTitle("Next", for: .normal) button.sizeToFit() button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) A: As the previous answer pointed out, all you need to do is to add a negative fixed space to the left of your nextButton and it will be pushed to the right. This code creates a negative fixed width of 8 points (which seems enough in your case, but feel free to adapt as you need): let negativeWidthButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) negativeWidthButtonItem.width = -8 After creating this button, add it to the rightBarButtonItems array: self.navigationItem.rightBarButtonItems = [negativeWidthButtonItem, nextButton] Some other answers on StackOverflow also refer to the same solution: * *reduce left space and right space from navigation bar left and right bar button item *How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]
Q: Next Button like Navigation's Back Button I want to display Next Button just like Back Button but the rightBarButton does not touch to end of the screen like the back barButton. let button = UIButton(type: .system) button.setImage(UIImage(named: "ic_next_button"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x button.setTitle("Next", for: .normal) button.sizeToFit() button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) A: As the previous answer pointed out, all you need to do is to add a negative fixed space to the left of your nextButton and it will be pushed to the right. This code creates a negative fixed width of 8 points (which seems enough in your case, but feel free to adapt as you need): let negativeWidthButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) negativeWidthButtonItem.width = -8 After creating this button, add it to the rightBarButtonItems array: self.navigationItem.rightBarButtonItems = [negativeWidthButtonItem, nextButton] Some other answers on StackOverflow also refer to the same solution: * *reduce left space and right space from navigation bar left and right bar button item *How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7] A: Create another UIBarButtonItem with type of .fixedSpace and some negative value as width. Then add both buttons as right bar button item. let button = UIButton(type: .system) button.setImage(UIImage(named: "right"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x button.setTitle("Next", for: .normal) button.sizeToFit() button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) let nextBtn = UIBarButtonItem(customView: button) let spaceBtn = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) spaceBtn.width = -8// Change this value as per your need self.navigationItem.rightBarButtonItems = [spaceBtn, nextBtn]; A: Adding UIBarButtonSystemItem.fixedSpace will occupy the extra space before the BarButtonItem. let button = UIButton(type: .system) button.setImage(UIImage(named: "ic_next_button"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x button.setTitle("Next", for: .normal) button.sizeToFit() button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) let rightBarButton = UIBarButtonItem() rightBarButton.customView = button let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) negativeSpacer.width = -25; self.navigationItem.setRightBarButtonItems([negativeSpacer, rightBarButton ], animated: false)
stackoverflow
{ "language": "en", "length": 359, "provenance": "stackexchange_0000F.jsonl.gz:845910", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483249" }
87c57d71610ff7acf43f7dae60544222d38d1261
Stackoverflow Stackexchange Q: Angular4 CLI change favicon.ico to favicon.svg I started to learn Angular 4 and try to remake one site using Angilar4 CLI. Now I have a problem with new favicon that I drew in svg. I wrote this in index.html <link rel="icon" type="image/svg+xml" sizes="any" href="favicon.svg"> And I deleted favicon.ico because it has been shown every time though I changed file. Also I rewrote .angular-cli.json I changed "assets": [ "assets", "favicon.ico" ] to "assets": [ "assets", "favicon.svg" ] The favicon.svg is 16*16 px sized. A: Finally I found the problem. https://caniuse.com/#search=favicon There we can see that chrome just doesn't support svg favicons
Q: Angular4 CLI change favicon.ico to favicon.svg I started to learn Angular 4 and try to remake one site using Angilar4 CLI. Now I have a problem with new favicon that I drew in svg. I wrote this in index.html <link rel="icon" type="image/svg+xml" sizes="any" href="favicon.svg"> And I deleted favicon.ico because it has been shown every time though I changed file. Also I rewrote .angular-cli.json I changed "assets": [ "assets", "favicon.ico" ] to "assets": [ "assets", "favicon.svg" ] The favicon.svg is 16*16 px sized. A: Finally I found the problem. https://caniuse.com/#search=favicon There we can see that chrome just doesn't support svg favicons
stackoverflow
{ "language": "en", "length": 101, "provenance": "stackexchange_0000F.jsonl.gz:846008", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483580" }
b858f09d0ba53a2a9d9f0fc11fc26bb34609196f
Stackoverflow Stackexchange Q: PyCharm PEP8 on save So I have googled, I have SO'd, I have tried... How can I get PyCharm to do PEP8 auto format as an on save action? I found that I can do Ctrl+Alt+L to do auto formatting. I got used to having that as on save action on eclipse, so I'd like that in PyCharm. It was easy to do in GoGland, so why not in PyCharm? I'm lost, please help... A: So what worked for me was roundabout but I haven't found an easy built in option to do this. My solution was to record a macro of format and save and then reassign the ctrl+s keybinding to that macro. To make the macro: - Edit>Macros>Start Recording - Run ctrl+alt+L and then ctrl+s - Edit>Macros>Stop Recording>call it something like save and format To reassign ctrl+s: - Settings>Keymap>Macros: - Select your macro and 'Add Keyboard Shortcut' and enter ctrl+s - Opt to remove it from save since your macro does that anyway Documentation that goes into more detail: https://www.jetbrains.com/help/pycharm/recording-macros.html https://www.jetbrains.com/help/pycharm/binding-macros-with-keyboard-shortcuts.html
Q: PyCharm PEP8 on save So I have googled, I have SO'd, I have tried... How can I get PyCharm to do PEP8 auto format as an on save action? I found that I can do Ctrl+Alt+L to do auto formatting. I got used to having that as on save action on eclipse, so I'd like that in PyCharm. It was easy to do in GoGland, so why not in PyCharm? I'm lost, please help... A: So what worked for me was roundabout but I haven't found an easy built in option to do this. My solution was to record a macro of format and save and then reassign the ctrl+s keybinding to that macro. To make the macro: - Edit>Macros>Start Recording - Run ctrl+alt+L and then ctrl+s - Edit>Macros>Stop Recording>call it something like save and format To reassign ctrl+s: - Settings>Keymap>Macros: - Select your macro and 'Add Keyboard Shortcut' and enter ctrl+s - Opt to remove it from save since your macro does that anyway Documentation that goes into more detail: https://www.jetbrains.com/help/pycharm/recording-macros.html https://www.jetbrains.com/help/pycharm/binding-macros-with-keyboard-shortcuts.html
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:846051", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483748" }
9905b6359454820efbb4fb4ccd9117b41df9847e
Stackoverflow Stackexchange Q: NetShareGetInfo doesn't return permissions I've shared a directory with the (OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ) permissions, but when I call NetShareGetInfo on the share, the permissions are 0 (while all of the other fields are correct). Code: /* Initialize the share info structure */ tShareInfo.shi2_netname = pwstrNetName; tShareInfo.shi2_type = STYPE_DISKTREE; tShareInfo.shi2_remark = L""; tShareInfo.shi2_permissions = OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ; tShareInfo.shi2_max_uses = (DWORD)-1; tShareInfo.shi2_current_uses = 0; tShareInfo.shi2_path = pwstrPath; tShareInfo.shi2_passwd = NULL; /* Add the share */ eResult = NetShareAdd(NULL, 2, (LPBYTE)&tShareInfo, &dwError); if (NERR_Success != eResult) { printf("Failed sharing\n"); goto lbl_cleanup; } eResult = NetShareGetInfo(NULL, pwstrNetName, 2, (LPBYTE *)&ptShareInfo); if (NERR_Success == eResult) { printf("Path: %s\n", ptShareInfo->shi2_path); printf("Permissions: %d\n", ptShareInfo->shi2_permissions); } What can be the problem here?
Q: NetShareGetInfo doesn't return permissions I've shared a directory with the (OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ) permissions, but when I call NetShareGetInfo on the share, the permissions are 0 (while all of the other fields are correct). Code: /* Initialize the share info structure */ tShareInfo.shi2_netname = pwstrNetName; tShareInfo.shi2_type = STYPE_DISKTREE; tShareInfo.shi2_remark = L""; tShareInfo.shi2_permissions = OSSMBSHARE_PERMISSIONS_ATRIB | OSSMBSHARE_PERMISSIONS_EXEC | OSSMBSHARE_PERMISSIONS_READ; tShareInfo.shi2_max_uses = (DWORD)-1; tShareInfo.shi2_current_uses = 0; tShareInfo.shi2_path = pwstrPath; tShareInfo.shi2_passwd = NULL; /* Add the share */ eResult = NetShareAdd(NULL, 2, (LPBYTE)&tShareInfo, &dwError); if (NERR_Success != eResult) { printf("Failed sharing\n"); goto lbl_cleanup; } eResult = NetShareGetInfo(NULL, pwstrNetName, 2, (LPBYTE *)&ptShareInfo); if (NERR_Success == eResult) { printf("Path: %s\n", ptShareInfo->shi2_path); printf("Permissions: %d\n", ptShareInfo->shi2_permissions); } What can be the problem here?
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:846054", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483752" }
c65b9cde8c316cc6eeea43aa947a49fe213452b1
Stackoverflow Stackexchange Q: In R how to remove small community from igraph in R network graph how to remove small community of twos (two nodes connected with one edge and no connection with other nodes, like jane and ike in this example: library(igraph) g <- graph_from_literal(Andre----Beverly:Diane:Fernando Beverly--Garth:Ed, Carol----Andre:Diane:Fernando, Diane----Andre:Carol:Fernando:Beverly, Fernando-Carol:Andre:Diane:Heather, Jane-----Ike ) plot(g, vertex.label.color="blue", vertex.label.cex=1.5, vertex.label.font=2, vertex.size=25, vertex.color="white", vertex.frame.color="white", edge.color="black") A: Here's a possible solution using components to find subgraphs and then doing some counting. You could also look into functions from igraph such as groups and sizes to do these operations of getting subgraph vertex count and vertex names. library(igraph) g <- graph_from_literal(Andre----Beverly:Diane:Fernando, Beverly--Garth:Ed, Carol----Andre:Diane:Fernando, Diane----Andre:Carol:Fernando:Beverly, Fernando-Carol:Andre:Diane:Heather, Jane-----Ike ) #get all subgraphs sub_gs <- components(g)$membership #find which subgraphs have 2 nodes small_sub <- names(which(table(sub_gs) == 2)) #get names of nodes to rm (rm_nodes <- names(which(sub_gs == small_sub))) # [1] "Jane" "Ike" #remove nodes by name g2 <- delete_vertices(g, rm_nodes)
Q: In R how to remove small community from igraph in R network graph how to remove small community of twos (two nodes connected with one edge and no connection with other nodes, like jane and ike in this example: library(igraph) g <- graph_from_literal(Andre----Beverly:Diane:Fernando Beverly--Garth:Ed, Carol----Andre:Diane:Fernando, Diane----Andre:Carol:Fernando:Beverly, Fernando-Carol:Andre:Diane:Heather, Jane-----Ike ) plot(g, vertex.label.color="blue", vertex.label.cex=1.5, vertex.label.font=2, vertex.size=25, vertex.color="white", vertex.frame.color="white", edge.color="black") A: Here's a possible solution using components to find subgraphs and then doing some counting. You could also look into functions from igraph such as groups and sizes to do these operations of getting subgraph vertex count and vertex names. library(igraph) g <- graph_from_literal(Andre----Beverly:Diane:Fernando, Beverly--Garth:Ed, Carol----Andre:Diane:Fernando, Diane----Andre:Carol:Fernando:Beverly, Fernando-Carol:Andre:Diane:Heather, Jane-----Ike ) #get all subgraphs sub_gs <- components(g)$membership #find which subgraphs have 2 nodes small_sub <- names(which(table(sub_gs) == 2)) #get names of nodes to rm (rm_nodes <- names(which(sub_gs == small_sub))) # [1] "Jane" "Ike" #remove nodes by name g2 <- delete_vertices(g, rm_nodes) A: We can use induced_subgraph + membership like below to filterout the clusters of small size (e.g., size 2 or even smaller) induced_subgraph( g, V(g)[ave(1:vcount(g), membership(components(g)), FUN = length) > 2] )
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:846078", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44483836" }