qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,652,872
<p>Let's say I want to create an array of <code>Person</code> using a random data library.</p> <p>I could do something like</p> <pre><code>import {generateRandom} from 'someLib' let people = [] function getPerson() ({ name: generateRandom.string() age: generateRandom.number() }) for (let i = 0; i &lt; 10; i++) { people.push(getPerson()) } </code></pre> <p>But I could also do something like</p> <pre><code>import {generateRandom} from 'someLib' class Person { constructor() { this.name = generateRandom.string(), this.age = generateRandom.number() } } let people = [] for (let i = 0; i &lt; 10; i++) { people.push(new Person()) } </code></pre> <p>On a memory level, is there any difference in the outcome?</p> <hr /> <p>(This is just a theoretical question, I am not trying to solve any problem in particular)</p> <p>I have found this question that is related to this <a href="https://stackoverflow.com/questions/35025652/difference-between-creating-a-class-in-javascript-to-create-an-object-and-creati">Difference between creating a class in javascript to create an object and creating an class and object in Java</a></p> <p>Which states that there are no classes in JS.</p> <p>Is this just syntactic sugar? 2 ways of doing exactly the same thing?</p>
[ { "answer_id": 74653319, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 1, "selected": false, "text": "getPerson() people.push(getPerson()) undefined let people = []\n\nfunction getPerson() {\n return {\n name: generateRandom.string()\n age: generateRandom.number()\n }\n}\n\nfor (let i = 0; i < 10; i++) {\n people.push(getPerson())\n}\n .constructor class class class new Person() yourObject.constructor super(...)" }, { "answer_id": 74653962, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 3, "selected": true, "text": "class Test{};\n\nconst test = new Test();\n\nclass Class {};\ntest.Class = Class;\ntest.classObj = new Class();\n\nfunction func() {return {};};\ntest.func = func;\ntest.funcObj = func();\n Test Object classObj Class class Test{};\n\nconst test = new Test();\n\nclass Class {\n method0(){};\n method1(){};\n method2(){};\n method3(){};\n method4(){};\n method5(){};\n method6(){};\n method7(){};\n method8(){};\n method9(){};\n};\ntest.Class = Class;\nfor (let i=0; i < 10; i++){\n test[\"classObj\" + i] = new Class();\n}\n\n\nfunction func0(){};\nfunction func1(){};\nfunction func2(){};\nfunction func3(){};\nfunction func4(){};\nfunction func5(){};\nfunction func6(){};\nfunction func7(){};\nfunction func8(){};\nfunction func9(){};\nfunction constructorFunc() {\n return {\n method0: func0,\n method1: func1,\n method2: func2,\n method3: func3,\n method4: func4,\n method5: func5,\n method6: func6,\n method7: func7,\n method8: func8,\n method9: func9,\n };\n};\ntest.constructorFunc = constructorFunc;\nfor (let i=0; i < 10; i++){\n test[\"funcObj\" + i] = constructorFunc();\n}\n Class constructorFunc Class prototype constructorFunc" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734836/" ]
74,652,883
<p>How do I achieve this in Python. I know there is a vlookup function in excel but if there is a way in Python, I prefer to do it in Python. Basically my goal is to get data from CSV2 column Quantity and write the data to column Quantity of CSV1 based on Bin_Name. The script should not copy all the value at once, it must be by selecting a Bin_Name. Ex: For today, I would like to get the data from Bin_Name ABCDE of CSV2 to CSV1 then it will write the data in column Quantity of CSV1. If this is possible, I will be very grateful and will learn a lot from this. Thank you very much in advance.</p> <pre><code>CSV1 CSV2 Bin_Name Quantity Bin_Name Quantity A A 43 B B 32 C C 28 D D 33 E E 37 F F 38 G G 39 H H 41 </code></pre>
[ { "answer_id": 74653319, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 1, "selected": false, "text": "getPerson() people.push(getPerson()) undefined let people = []\n\nfunction getPerson() {\n return {\n name: generateRandom.string()\n age: generateRandom.number()\n }\n}\n\nfor (let i = 0; i < 10; i++) {\n people.push(getPerson())\n}\n .constructor class class class new Person() yourObject.constructor super(...)" }, { "answer_id": 74653962, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 3, "selected": true, "text": "class Test{};\n\nconst test = new Test();\n\nclass Class {};\ntest.Class = Class;\ntest.classObj = new Class();\n\nfunction func() {return {};};\ntest.func = func;\ntest.funcObj = func();\n Test Object classObj Class class Test{};\n\nconst test = new Test();\n\nclass Class {\n method0(){};\n method1(){};\n method2(){};\n method3(){};\n method4(){};\n method5(){};\n method6(){};\n method7(){};\n method8(){};\n method9(){};\n};\ntest.Class = Class;\nfor (let i=0; i < 10; i++){\n test[\"classObj\" + i] = new Class();\n}\n\n\nfunction func0(){};\nfunction func1(){};\nfunction func2(){};\nfunction func3(){};\nfunction func4(){};\nfunction func5(){};\nfunction func6(){};\nfunction func7(){};\nfunction func8(){};\nfunction func9(){};\nfunction constructorFunc() {\n return {\n method0: func0,\n method1: func1,\n method2: func2,\n method3: func3,\n method4: func4,\n method5: func5,\n method6: func6,\n method7: func7,\n method8: func8,\n method9: func9,\n };\n};\ntest.constructorFunc = constructorFunc;\nfor (let i=0; i < 10; i++){\n test[\"funcObj\" + i] = constructorFunc();\n}\n Class constructorFunc Class prototype constructorFunc" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610995/" ]
74,652,884
<p>From the <a href="https://stackoverflow.com/q/74652408/10969942">last post</a>, the duplicate post cannot answer my question.</p> <p>Right now, I have a function <code>f1()</code> which contains CPU intensive part and async IO intensive part. Therefore <code>f1()</code> itself is an <code>async function</code>. <strong>How can I run the whole <code>f1()</code> with given timeout?</strong> I found the method provided in the <a href="https://stackoverflow.com/q/61876399/10969942">post</a> cannot solve my situation. For the following part, it shows <code>RuntimeWarning: coroutine 'f1' was never awaited handle = None # Needed to break cycles when an exception occurs.</code></p> <pre class="lang-py prettyprint-override"><code>import asyncio import time import concurrent.futures executor = concurrent.futures.ThreadPoolExecutor(1) async def f1(): print(&quot;start sleep&quot;) time.sleep(3) # simulate CPU intensive part print(&quot;end sleep&quot;) print(&quot;start asyncio.sleep&quot;) await asyncio.sleep(3) # simulate IO intensive part print(&quot;end asyncio.sleep&quot;) async def process(): print(&quot;enter process&quot;) loop = asyncio.get_running_loop() await loop.run_in_executor(executor, f1) async def main(): print(&quot;-----f1-----&quot;) t1 = time.time() try: await asyncio.wait_for(process(), timeout=2) except: pass t2 = time.time() print(f&quot;f1 cost {(t2 - t1)} s&quot;) if __name__ == '__main__': asyncio.run(main()) </code></pre> <p>From previous post, <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor" rel="nofollow noreferrer">loop.run_in_executor</a> <strong>can only work for normal function not async function.</strong></p>
[ { "answer_id": 74653319, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 1, "selected": false, "text": "getPerson() people.push(getPerson()) undefined let people = []\n\nfunction getPerson() {\n return {\n name: generateRandom.string()\n age: generateRandom.number()\n }\n}\n\nfor (let i = 0; i < 10; i++) {\n people.push(getPerson())\n}\n .constructor class class class new Person() yourObject.constructor super(...)" }, { "answer_id": 74653962, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 3, "selected": true, "text": "class Test{};\n\nconst test = new Test();\n\nclass Class {};\ntest.Class = Class;\ntest.classObj = new Class();\n\nfunction func() {return {};};\ntest.func = func;\ntest.funcObj = func();\n Test Object classObj Class class Test{};\n\nconst test = new Test();\n\nclass Class {\n method0(){};\n method1(){};\n method2(){};\n method3(){};\n method4(){};\n method5(){};\n method6(){};\n method7(){};\n method8(){};\n method9(){};\n};\ntest.Class = Class;\nfor (let i=0; i < 10; i++){\n test[\"classObj\" + i] = new Class();\n}\n\n\nfunction func0(){};\nfunction func1(){};\nfunction func2(){};\nfunction func3(){};\nfunction func4(){};\nfunction func5(){};\nfunction func6(){};\nfunction func7(){};\nfunction func8(){};\nfunction func9(){};\nfunction constructorFunc() {\n return {\n method0: func0,\n method1: func1,\n method2: func2,\n method3: func3,\n method4: func4,\n method5: func5,\n method6: func6,\n method7: func7,\n method8: func8,\n method9: func9,\n };\n};\ntest.constructorFunc = constructorFunc;\nfor (let i=0; i < 10; i++){\n test[\"funcObj\" + i] = constructorFunc();\n}\n Class constructorFunc Class prototype constructorFunc" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10969942/" ]
74,652,891
<p>On a checkout page I make an overlay on top of the website where scroll on body is disabled, but overflow is enabled on the overlay.</p> <p>But if the viewport is smaller the content on the overlay is clipped.</p> <p>How to avoid that?</p> <p>I tried to add <code>overflow:auto</code> to the overlay but it didn't work :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { overflow: hidden; } #overlay.active { position: fixed; top: 0; left: 0; bottom: 0; right: 0; display: flex; justify-content: center; align-items: center; padding: 20px; overflow: auto; background: yellow; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="overlay" class="active"&gt; &lt;div style="height:300px; background:white; padding:20px"&gt; content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74652913, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": -1, "selected": false, "text": "body {\n overflow: hidden;\n}\n\n.overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n overflow-y: scroll;\n overflow-x: hidden;\n}\n" }, { "answer_id": 74653090, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "margin: auto div #overlay > div { margin: auto; }\n safe align-items align-items: safe center;\n body {\n overflow: hidden;\n}\n\n/* Added on the child div */\n#overlay > div {\n margin: auto;\n}\n\n#overlay.active {\n position: fixed;\n /* Can use shorthand (Optional: not supported by older browsers and IE) */\n inset: 0;\n display: flex;\n justify-content: center;\n /* Safe is only working on Firefox as of now */\n align-items: safe center;\n padding: 20px;\n background: #fff;\n overflow: auto;\n background: pink;\n} <div id=\"overlay\" class=\"active\">\n <div style=\"height:300px; background:white; padding:20px\">\n content\n </div>\n</div>" }, { "answer_id": 74653616, "author": "Jenny", "author_id": 4738016, "author_profile": "https://Stackoverflow.com/users/4738016", "pm_score": 0, "selected": false, "text": "align-items:center;" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/555222/" ]
74,652,918
<p>Say I have a list of <code>dict</code>:</p> <pre><code>ld = [{'a':1,'b':2,'c':9},{'a':1,'b':2,'c':10}] </code></pre> <p>And a list to filter the keys out:</p> <pre><code>l = ['a','c'] </code></pre> <p>Want to remove key <code>a</code> and <code>c</code> from <code>ld</code>:</p> <p>Try:</p> <pre><code>result = [d for d in ld for k in d if k in l] </code></pre> <p>Desired Result:</p> <pre><code>[{'b':2},{'b':2}] </code></pre>
[ { "answer_id": 74652966, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 3, "selected": true, "text": "ld = [{'a': 1, 'b': 2, 'c': 9}, {'a': 1, 'b': 2, 'c': 10}]\nl = ['a', 'c']\nresult = [{k: v for k, v in subdict.items() if k not in l}\n for subdict in ld]\nprint(result)\n" }, { "answer_id": 74653066, "author": "Cpt.Hook", "author_id": 20599896, "author_profile": "https://Stackoverflow.com/users/20599896", "pm_score": 0, "selected": false, "text": "data = [{'a': 1, 'b': 2, 'c': 9}, {'a': 1, 'b': 2, 'c': 10}]\nexcludes = ['a', 'c']\n list dict items() (key, value) result = []\nfor entry in data:\n # entry is now one of the dicts\n result.append({key:value for key, value in entry.items() if key not in excludes})\n" }, { "answer_id": 74653167, "author": "zhenquan zhang", "author_id": 20664498, "author_profile": "https://Stackoverflow.com/users/20664498", "pm_score": 0, "selected": false, "text": "ld = [{'a':1,'b':2,'c':9},{'a':1,'b':2,'c':10}]\n\nl = ['a','c']\nfor d in ld:\n for r in l:\n if r in d:\n del d[r]\n" }, { "answer_id": 74654245, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "ld l result = [{k:d[k]} for d in ld for k in d if k not in l]\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8176763/" ]
74,652,920
<p>For some reason when I try to do this event, it allows for only one letter in the text input. I tried searching for an answer and couldn't figure it out, can someone help me?</p> <pre><code>let button = document.getElementById(&quot;button&quot;); let input = document.getElementById(&quot;userInput&quot;); let ul = document.getElementById(&quot;list&quot;); input.addEventListener(&quot;keypress&quot;, function(e){ if(e.keyCode == 13){ let li = document.createElement(&quot;li&quot;); li.appendChild(document.createTextNode(input.value)) ul.appendChild(li)} input.value = &quot;&quot;; } ); </code></pre> <p>There is another event, but this one works perfectly when alone and there is no text limit</p> <pre><code>button.addEventListener(&quot;click&quot;, function(){ let li = document.createElement(&quot;li&quot;); if(input.value.length &gt; 0){ li.appendChild(document.createTextNode(input.value)) ul.appendChild(li)} input.value = &quot;&quot;; } ); </code></pre>
[ { "answer_id": 74652945, "author": "physiqq", "author_id": 19989201, "author_profile": "https://Stackoverflow.com/users/19989201", "pm_score": 1, "selected": false, "text": "input.value input.value = \"\"; let button = document.getElementById(\"button\");\nlet input = document.getElementById(\"userInput\");\nlet ul = document.getElementById(\"list\");\n\ninput.addEventListener(\"keypress\", function(e){\n \n if(e.keyCode == 13){\n let li = document.createElement(\"li\");\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n \n input.value = \"\";\n }\n}\n" }, { "answer_id": 74653348, "author": "Dr. Tenma", "author_id": 3357677, "author_profile": "https://Stackoverflow.com/users/3357677", "pm_score": 0, "selected": false, "text": "input.value = \"\"; keypress let button = document.getElementById(\"button\");\nlet input = document.getElementById(\"userInput\");\nlet ul = document.getElementById(\"list\");\n\ninput.addEventListener(\"keypress\", function(e) {\n if (e.keyCode == 13) {\n let li = document.createElement(\"li\");\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n input.value = \"\";\n }\n }\n\n);\n\nbutton.addEventListener(\"click\", function() {\n let li = document.createElement(\"li\");\n if (input.value.length > 0) {\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n }\n\n input.value = \"\";\n }\n\n); <button id=\"button\">button</button><input id=\"userInput\"></input><br/>\n<ul id=\"list\"></ul>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19943108/" ]
74,652,957
<p>In GCP if we want to use windows instances we have both pay as you go and Bring your own licenses. Now if we have own licenses gcp mentioned in few documents we should use solo tenant nodes. Can we migrate windows vm to gcp and use compute engine with own license without solo tenant node. Like can we bring existing license to GCP compute engine without solo tenant nodes. Thanks</p>
[ { "answer_id": 74652945, "author": "physiqq", "author_id": 19989201, "author_profile": "https://Stackoverflow.com/users/19989201", "pm_score": 1, "selected": false, "text": "input.value input.value = \"\"; let button = document.getElementById(\"button\");\nlet input = document.getElementById(\"userInput\");\nlet ul = document.getElementById(\"list\");\n\ninput.addEventListener(\"keypress\", function(e){\n \n if(e.keyCode == 13){\n let li = document.createElement(\"li\");\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n \n input.value = \"\";\n }\n}\n" }, { "answer_id": 74653348, "author": "Dr. Tenma", "author_id": 3357677, "author_profile": "https://Stackoverflow.com/users/3357677", "pm_score": 0, "selected": false, "text": "input.value = \"\"; keypress let button = document.getElementById(\"button\");\nlet input = document.getElementById(\"userInput\");\nlet ul = document.getElementById(\"list\");\n\ninput.addEventListener(\"keypress\", function(e) {\n if (e.keyCode == 13) {\n let li = document.createElement(\"li\");\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n input.value = \"\";\n }\n }\n\n);\n\nbutton.addEventListener(\"click\", function() {\n let li = document.createElement(\"li\");\n if (input.value.length > 0) {\n li.appendChild(document.createTextNode(input.value))\n ul.appendChild(li)\n }\n\n input.value = \"\";\n }\n\n); <button id=\"button\">button</button><input id=\"userInput\"></input><br/>\n<ul id=\"list\"></ul>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11105625/" ]
74,652,958
<p>I'm not entirely sure why the string &quot;6145390195186705543&quot; is outputting 6145390195186705000, at first reading through the threads it may be the base radix but even tinkering around with that still gives me the same results, can anyone help explain because I do believe this is not a bug, but I'm not entirely sure what's the explanation here.</p> <pre><code> const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3] const val1 = digits.join('') // string &quot;6145390195186705543&quot; const test1 = Number(val1) // outputs 6145390195186705000 const test2 = parseInt(val1) // outputs 6145390195186705000 </code></pre>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12353257/" ]
74,652,959
<p>I saw this query as an answer to another question on this site:</p> <pre><code>SELECT MAX(date), thread_id FROM table GROUP BY thread_id HAVING MAX(date) &lt; 1555 </code></pre> <p>With this database sample:</p> <pre><code>+-----------------------------+ | id | date | thread_id | +-----+---------+-------------+ | 1 | 1111 | 4 | | 2 | 1333 | 4 | | 3 | 1444 | 5 | | 4 | 1666 | 5 | +-----------------------------+ </code></pre> <p>Am I correct in assuming <code>MAX(date)</code> is computed twice here?</p> <p>If so, this would definitely reduce the efficiency of this query. Is it possible to refactor the query so that <code>MAX(date)</code> is only computed once, so that performance can be maximised?</p>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14146687/" ]
74,653,012
<p>i have a problem when i try to install package npm on angular, i have this kind of error but i don't understand how i should do to solve it</p> <p><code>PS C:\Users\user\Documents\Progetti\myProject\ng-app\src\app&gt; npm i angular-calendar npm WARN config global </code>--global<code>, </code>--local<code>are deprecated. Use</code>--location=global` instead. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: ng-app@0.0.0 npm ERR! Found: @angular/core@13.3.12 npm ERR! node_modules/@angular/core npm ERR! @angular/core@&quot;~13.3.0&quot; from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/core@&quot;&gt;=14.0.0&quot; from angular-calendar@0.30.1 npm ERR! node_modules/angular-calendar npm ERR! angular-calendar@&quot;*&quot; from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR!</p> <p>npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\user\AppData\Local\npm-cache_logs\2022-12-02T08_36_42_518Z-debug-0.log PS C:\Users\user\Documents\Progetti\myProject\ng-app\src\app&gt; `</p> <p>I have already done the following steps:</p> <ol> <li>deleted &quot;node_modules&quot; folder</li> <li>deleted the &quot;package-lock.json&quot;</li> <li>delete cache with &quot;npm cache clean --force&quot;</li> <li>called the &quot;npm install --save&quot; command</li> </ol> <p>if i try to install the npm packet i have always the same error where am I wrong thank you</p>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8898767/" ]
74,653,032
<p>I am switching over from Overleaf to VSCode for offline LaTeX.</p> <p>Is there an extensions that lets you click on the pdf preview and highlights the line you clicked on in the .tex file? (just like the Overleaf feature)</p>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664404/" ]
74,653,041
<pre><code>&lt;div data-component-id=&quot;nwv4kv9j5ct9&quot; class=&quot;component-inner-container status-red &quot; data-component-status=&quot;major_outage&quot; data-js-hook=&quot;&quot; id=&quot;nwv4kv9j5ct9&quot;&gt; &lt;span class=&quot;name table-item-name&quot;&gt;JHP&lt;/span&gt; &lt;span class=&quot;service-tier table-item-tier&quot;&gt;&lt;a href=&quot;&quot; target=&quot;_blank&quot; onclick=&quot;event.stopPropagation()&quot;&gt;Tier 2&lt;/a&gt;&lt;/span&gt; &lt;span class=&quot;tooltip-base tool tooltipstered&quot; style=&quot;display: none;&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;component-status table-item-status-childs&quot; title=&quot;&quot;&gt;&lt;span class=&quot;app-status bg- inactive&quot;&gt;failing&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;tool icon-indicator fa fa-times tooltipstered&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div data-component-id=&quot;rtv4kv9j5cyu&quot; class=&quot;component-inner-container status-red &quot; data-component-status=&quot;major_outage&quot; data-js-hook=&quot;&quot; id=&quot;nwv4kv9j5ct9&quot;&gt; &lt;span class=&quot;name table-item-name&quot;&gt;PHS&lt;/span&gt; &lt;span class=&quot;service-tier table-item-tier&quot;&gt;&lt;a href=&quot;&quot; target=&quot;_blank&quot; onclick=&quot;event.stopPropagation()&quot;&gt;Tier 2&lt;/a&gt;&lt;/span&gt; &lt;span class=&quot;tooltip-base tool tooltipstered&quot; style=&quot;display: none;&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;component-status table-item-status-childs&quot; title=&quot;&quot;&gt;&lt;span class=&quot;app-status bg-inactive&quot;&gt;degrading&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;tool icon-indicator fa fa-times tooltipstered&quot;&gt;&lt;/span&gt; &lt;/div&gt; ...... ...... </code></pre> <p>I need to create and append a span tag <code>&lt;span class=&quot;type table-item-type&quot;&gt;Type&lt;/span&gt;</code> inside each div with class name <code>component-inner-container</code>. It should be after</p> <pre><code>$('.component-inner-container').each(function () { var span = $('&lt;span /&gt;').attr('className', 'type') span.appendTo(&quot;.component-inner-container&quot;); }); </code></pre> <p>I'm stuck here and couldn't able to find right approach</p> <p>Edit : added span should be after for example <code>&lt;span class=&quot;name table-item-name&quot;&gt;PHS&lt;/span&gt;</code></p>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14710995/" ]
74,653,046
<p>I'm currently working on a school project: I had to code a website that sells sofas. I made the whole site but I struggle with my calculation function that adds all the prices of each sofa to get the sum of my cart. It's always false whatever I do. I'm lost.</p> <p>I had to fetch the prices of the products in my cart from the API and the products from the local storage. Then, I try to calculate the sum of all the prices within a specific function. I tried a loop but the result is always false.</p> <p>Eg: When I add 2 sofas that cost 4499€ and one sofa of 1849€, the result is 5547 € instead of 10487€.</p> <p>Getting sofas from LocalStorage : product name, photo and color only</p> <pre class="lang-js prettyprint-override"><code>function getCart() { let cart = localStorage‧getItem(&quot;cart&quot;); if (cart === null || cart === &quot;[]&quot;) { let emptyCart = document‧querySelector(&quot;#cart__items&quot;); emptyCart‧innerText = &quot;Votre panier est vide&quot;; document‧querySelector(&quot;.cart__order&quot;).style‧display = &quot;none&quot;; return []; } else { return JSON‧parse(cart); } } </code></pre> <p>Getting prices from API then adding display functions that need it</p> <pre class="lang-js prettyprint-override"><code>async function getPriceFromApi(article) { let dataFetch = await fetch( `http://localhost:3000/api/products/${article.id}` ) .then((products) =&gt; products‧json()) .then((product) =&gt; { return product; }); const apiProduct = { price: dataFetch‧price, }; const completeItem = { ...article, ...apiProduct, }; productDisplay(completeItem); displayTotalPrice(apiProduct); } </code></pre> <p>Calculation : the total price of the cart</p> <pre class="lang-js prettyprint-override"><code>function totalPriceCalculation(product) { let cart = getCart(); let total = []; cart‧forEach((sumPrice) =&gt; { let number = eval(sumPrice‧quantity); total‧push(product‧price * number); console‧log(number, total); }); let totalPrice = `${eval(total‧join(&quot;+&quot;))}`; return totalPrice; } </code></pre> <p>Displaying the whole cart (articles + prices) with every display and logic functions :</p> <pre class="lang-js prettyprint-override"><code>function completeCart() { let cart = getCart(); displayTotalQuantity(); cart‧forEach((item) =&gt; { getPriceFromApi(item); }); } completeCart(); </code></pre> <p>My display total price function :</p> <pre class="lang-js prettyprint-override"><code>function displayTotalPrice(product) { const TotalPrice = document‧querySelector(&quot;#totalPrice&quot;); TotalPrice‧innerText = totalPriceCalculation(product); return TotalPrice; } </code></pre> <p>other functions : // THE main container</p> <pre class="lang-js prettyprint-override"><code>function container(DisplayArticle) { document‧querySelector(&quot;#cart__items&quot;).appendChild(DisplayArticle); } </code></pre> <p>Here, I gather my query selectors for the images and desctiptions as well as my logic (&quot;settings&quot;= delete and modify) :</p> <pre class="lang-js prettyprint-override"><code>// The display function function productDisplay(product) { const DisplayArticle = displayArticle(product); container(DisplayArticle); // functions for the DOM : Query Selectors for HTML elements const DisplayImage = displayImage(product); const DisplayDescription = displayDescription(product); //functions &quot;delete&quot; and &quot;modify quantities&quot; const DisplaySettings = settings(product); DisplayArticle‧appendChild(DisplayImage); DisplayArticle‧appendChild(DisplayDescription); DisplayArticle‧appendChild(DisplaySettings); return DisplayArticle; } </code></pre> <p>// Displaing all the articles (it works fine)</p> <pre class="lang-js prettyprint-override"><code>function displayTotalQuantity() { const AllItems = document‧querySelector(&quot;#totalQuantity&quot;); AllItems‧innerText = totalquantityCalculation(); return AllItems; } function totalquantityCalculation() { let cart = getCart(); let number = 0; cart‧forEach((sumItem) =&gt; { number += eval(sumItem‧quantity); }); return number; } `` </code></pre>
[ { "answer_id": 74652995, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": false, "text": "9007199254740991 6145390195186705000" }, { "answer_id": 74653369, "author": "FZs", "author_id": 8376184, "author_profile": "https://Stackoverflow.com/users/8376184", "pm_score": 0, "selected": false, "text": "parseInt const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]\nconst val1 = digits.join('') \nconst test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18579477/" ]
74,653,050
<p>I created a login page. I am trying to authenticate a user by sending the message from the backend after verifying if the user exists in the database. Everything is working fine just one problem is that when I login with correct credentials I have to click twice on the submit button for it to work.</p> <pre><code>import React, { useState } from &quot;react&quot;; import axios from &quot;axios&quot;; const Login = () =&gt; { const [username, setUsername] = useState(&quot;&quot;); const [password, setPassword] = useState(&quot;&quot;); const [auth, setAuth] = useState(&quot;Wrong&quot;); const [mssg, setMssg] = useState(&quot;&quot;); const handleUser = (e) =&gt; { setUsername(e.target.value); }; const handlePassword = (e) =&gt; { setPassword(e.target.value); }; const login = (e) =&gt; { e.preventDefault(); const user = { username, password }; console.log(user); axios .post(&quot;http://localhost:5000/auth&quot;, user) .then((res) =&gt; setAuth(res.data.message)) .catch((err) =&gt; console.log(err)); if (auth === &quot;OK&quot;) { sessionStorage.setItem(&quot;user&quot;, username); window.location = &quot;/dashboard&quot;; } else { setMssg(&quot;Invalid Details. Please try again&quot;); } }; return ( &lt;div&gt; &lt;form onSubmit={login}&gt; &lt;input onChange={handleUser}&gt;&lt;/input&gt; &lt;input type=&quot;password&quot; onChange={handlePassword}&gt;&lt;/input&gt; &lt;input type=&quot;submit&quot;&gt;&lt;/input&gt; &lt;/form&gt; &lt;p id=&quot;mssg&quot;&gt;{mssg}&lt;/p&gt; &lt;/div&gt; ); }; export default Login; </code></pre> <p>When i login with correct credentials, it throws the error. But when i submit again with the same correct credentials, then it redirects me to the dashboard.</p>
[ { "answer_id": 74653128, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 0, "selected": false, "text": "login auth auth auth auth async/await login auth const login = async (e) => {\n e.preventDefault();\n const user = { username, password };\n console.log(user);\n try {\n const res = await axios.post(\"http://localhost:5000/auth\", user);\n setAuth(res.data.message);\n if (auth === \"OK\") {\n sessionStorage.setItem(\"user\", username);\n window.location = \"/dashboard\";\n } else {\n setMssg(\"Invalid Details. Please try again\");\n }\n } catch (err) {\n console.log(err);\n }\n};\n login auth" }, { "answer_id": 74653137, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 2, "selected": true, "text": "useEffect(()=>{\nif (auth === \"OK\") {\n sessionStorage.setItem(\"user\", username);\n window.location = \"/dashboard\";\n} else {\n setMssg(\"Invalid Details. Please try again\");\n}\n}, [auth])\n useEffect" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16973267/" ]
74,653,079
<p>I have button themes called green,blue and red .my solution works but it looks messy. how can I use them like in objects instead if arguments</p> <pre class="lang-js prettyprint-override"><code> const buttonBG = theme === 'green' ? COLORS.green : theme === &quot;blue&quot; ? COLORS.blue : &quot;&quot; const fontTheme = theme === 'green' ? FONTS.green : theme === &quot;blue&quot; ? FONTS.blue : &quot;&quot; const styles = StyleSheet.create({ button: { backgroundColor: buttonBG, borderRadius: 12, paddingVertical: 16, paddingHorizontal: 20, lineHeight: 24, font: fontTheme }, </code></pre>
[ { "answer_id": 74654656, "author": "Saraf", "author_id": 17709311, "author_profile": "https://Stackoverflow.com/users/17709311", "pm_score": 1, "selected": false, "text": "<ThemedBtn/> <ThemedBtn/> import React, {useState} from 'react';\nimport {View} from 'react-native';\n\nimport ThemedBtn from './components/ThemedBtn';\n\nconst _COLORS = {\n blue: 'blue',\n red: 'red',\n green: 'green',\n};\n\nconst _FONT_COLORS = {\n blue: 'blue',\n red: 'red',\n green: 'green',\n};\n\nconst App = () => {\n // edit start -> My best guess how you would like to alter the theme\n const [bgColor, setBgColor] = useState(_COLORS.blue);\n const [fontTheme, setFontTheme] = useState(_FONT_COLORS.red);\n // edit end ->\n\n return (\n <View>\n <ThemedBtn bgColor={bgColor} fontTheme={fontTheme} />\n </View>\n );\n};\n\nexport default App;\n export default function ThemedBtn({btnBg, fontTheme}) {\n const {btnStyles} = useMemo(\n () =>\n StyleSheet.create({\n btnStyles: {\n backgroundColor: btnBg,\n borderRadius: 12,\n paddingVertical: 16,\n paddingHorizontal: 20,\n lineHeight: 24,\n font: fontTheme,\n },\n }),\n [btnBg, fontTheme],\n );\n\n return (\n <TouchableOpacity style={btnStyles} title=\"Press Me\">\n <Text style={{color: btnStyles.font}}>Press Me</Text>\n </TouchableOpacity>\n );\n}\n" }, { "answer_id": 74655745, "author": "ZEESHAN ABBASI", "author_id": 13869965, "author_profile": "https://Stackoverflow.com/users/13869965", "pm_score": 0, "selected": false, "text": "\nimport { StyleSheet, Text, View } from 'react-native'\nimport React from 'react'\n\nconst App = () => {\n return (\n <Button \n style={styles.btn('red')}\n />\n )\n}\n\nexport default App\n\nconst styles = StyleSheet.create({\n btn : (color) => ({\n color : color\n })\n})\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17939803/" ]
74,653,081
<p>I'm passing a button event from the child to the parent, but when I click the button, nothing happens.</p> <p>This is the child code</p> <p>product-item.component.html</p> <pre><code> &lt;button (click)='handleShowDetail()' class=&quot;product_buttonAdd&quot;&gt; </code></pre> <p>product-item.component.ts</p> <pre><code> @Input() productItem!: Product; </code></pre> <pre><code> @Output() showDetail: EventEmitter&lt;string&gt;=new EventEmitter() handleShowDetail(){ this.showDetail.emit(this.productItem.sku) } </code></pre> <p>This is the code where the product-item is contained</p> <p>product-list.component.html</p> <pre><code>&lt;div class=&quot;header__searchResultsContainer&quot;&gt; &lt;div class=&quot;header__searchResults&quot; &gt; &lt;lpr-product-item (showDetail)=&quot;handleShowDetail($event)&quot; &gt;&lt;/lpr-product-item&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>product-list.component.ts</p> <pre><code> @Output() showDetail: EventEmitter&lt;string&gt;=new EventEmitter() handleShowDetail(sku: string){ this.showDetail.emit(sku) } </code></pre> <p>This is the parent who should activate the navigate and target the product based on its sku</p> <p>product-container.component.html</p> <pre><code>&lt;div class=&quot;product_container&quot;&gt; &lt;div&gt;&lt;lpr-products-list (showDetail)=&quot;handleShowDetail($event)&quot; &gt;&lt;/lpr-products-list&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>product-container.component.ts</p> <pre><code> handleShowDetail(sku: string){ this.router.navigate([ '/product-details' ]) } </code></pre> <p>When I click on the button, the user should be redirected to a product detail, but nothing happens</p>
[ { "answer_id": 74654656, "author": "Saraf", "author_id": 17709311, "author_profile": "https://Stackoverflow.com/users/17709311", "pm_score": 1, "selected": false, "text": "<ThemedBtn/> <ThemedBtn/> import React, {useState} from 'react';\nimport {View} from 'react-native';\n\nimport ThemedBtn from './components/ThemedBtn';\n\nconst _COLORS = {\n blue: 'blue',\n red: 'red',\n green: 'green',\n};\n\nconst _FONT_COLORS = {\n blue: 'blue',\n red: 'red',\n green: 'green',\n};\n\nconst App = () => {\n // edit start -> My best guess how you would like to alter the theme\n const [bgColor, setBgColor] = useState(_COLORS.blue);\n const [fontTheme, setFontTheme] = useState(_FONT_COLORS.red);\n // edit end ->\n\n return (\n <View>\n <ThemedBtn bgColor={bgColor} fontTheme={fontTheme} />\n </View>\n );\n};\n\nexport default App;\n export default function ThemedBtn({btnBg, fontTheme}) {\n const {btnStyles} = useMemo(\n () =>\n StyleSheet.create({\n btnStyles: {\n backgroundColor: btnBg,\n borderRadius: 12,\n paddingVertical: 16,\n paddingHorizontal: 20,\n lineHeight: 24,\n font: fontTheme,\n },\n }),\n [btnBg, fontTheme],\n );\n\n return (\n <TouchableOpacity style={btnStyles} title=\"Press Me\">\n <Text style={{color: btnStyles.font}}>Press Me</Text>\n </TouchableOpacity>\n );\n}\n" }, { "answer_id": 74655745, "author": "ZEESHAN ABBASI", "author_id": 13869965, "author_profile": "https://Stackoverflow.com/users/13869965", "pm_score": 0, "selected": false, "text": "\nimport { StyleSheet, Text, View } from 'react-native'\nimport React from 'react'\n\nconst App = () => {\n return (\n <Button \n style={styles.btn('red')}\n />\n )\n}\n\nexport default App\n\nconst styles = StyleSheet.create({\n btn : (color) => ({\n color : color\n })\n})\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538301/" ]
74,653,101
<p>I have a spreadsheet where I have used <code>SEARCH()</code> to get the possible linked ingredients from a match in a string. This sometimes leaves me with multiple possible matches. Now I would like to lookup the translated words of these possible matches using an <code>INDEX MATCH</code>. Except I cannot as cells have multiple values and therefore multiple criteria.</p> <p>My question is: how can I lookup multiple values based on multiple criteria and have them in one cell?</p> <p>An example as better explanation:</p> <p>The table I have:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>description</strong></th> <th><strong>productNameEN</strong></th> <th><strong>productNameIS</strong></th> </tr> </thead> <tbody> <tr> <td>Red onion</td> <td>Onion, Red onion</td> <td></td> </tr> <tr> <td>Egg yolk</td> <td>Egg, Egg yolk</td> <td></td> </tr> <tr> <td>Lemon</td> <td>Lemon</td> <td></td> </tr> </tbody> </table> </div> <p>And then I would like to fill the <code>productNameIS</code> column with the translations from another table, so that it looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>description</strong></th> <th><strong>productNameEN</strong></th> <th><strong>productNameIS</strong></th> </tr> </thead> <tbody> <tr> <td>Red onion</td> <td>Onion, Red onion</td> <td>Laukur, Rauðlaukur</td> </tr> <tr> <td>Egg yolk</td> <td>Egg, Egg yolk</td> <td>Egg, Eggjarauða</td> </tr> <tr> <td>Lemon</td> <td>Lemon</td> <td>Sítronu</td> </tr> </tbody> </table> </div> <p>This is a table example of the translations.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>EN</strong></th> <th><strong>IS</strong></th> </tr> </thead> <tbody> <tr> <td>Egg</td> <td>Egg</td> </tr> <tr> <td>Egg yolk</td> <td>Eggjarauða</td> </tr> <tr> <td>Lemon</td> <td>Sítronu</td> </tr> <tr> <td>Onion</td> <td>Laukur</td> </tr> <tr> <td>Red onion</td> <td>Rauðlaukur</td> </tr> </tbody> </table> </div> <p>Now the <code>INDEX MATCH</code> works for the word lemon as this is singular, but not for the other cells. I need to keep the multiple values in one cell for further use in my spreadsheet.</p>
[ { "answer_id": 74653139, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "C2 =MAP(B2:B4,LAMBDA(a,TEXTJOIN(\", \",,VLOOKUP(TEXTSPLIT(a,\", \"),F2:G6,2,0))))\n" }, { "answer_id": 74653189, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 1, "selected": false, "text": "SEARCH() FILTER() TEXTJOIN() =TEXTJOIN(\", \",TRUE,FILTER($I$2:$I$6,ISNUMBER(SEARCH($H$2:$H$6,B2))))\n =BYROW(B2:B4,LAMBDA(x,TEXTJOIN(\", \",TRUE,FILTER($I$2:$I$6,ISNUMBER(SEARCH($H$2:$H$6,x))))))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18737111/" ]
74,653,119
<p>I need help.</p> <p>I have this very simple html: <a href="https://jsfiddle.net/z8y7Lv2a/" rel="nofollow noreferrer">https://jsfiddle.net/z8y7Lv2a/</a></p> <pre><code>&lt;header&gt; &lt;ul&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Sobre&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;O que fazemos&lt;/a&gt; &lt;/li&gt; &lt;li data-submenu='Nossas sedes'&gt; &lt;a href=&quot;#&quot;&gt;Nossas sedes&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Curitiba&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Acre&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Salvador&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li data-submenu='Serviços'&gt; &lt;a href=&quot;#&quot;&gt;Serviços&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Google Analytics&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt;Google Tag Manager&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/header&gt; </code></pre> <p>I'm trying to give console when a link is clicked following this rule:</p> <p>If it is a main link, only the name of the link will appear, for example, clicking on 'About' the console will display 'About'.</p> <p>By clicking on a submenu, the console should display the parent's name + the title clicked on, for example: Nossas sedes-Curitiba</p> <p>Can you help me?</p> <p>If it is a main link, only the name of the link will appear, for example, clicking on 'About' the console will display 'About'.</p> <p>By clicking on a submenu, the console should display the parent's name + the title clicked on, for example: Nossas sedes-Curitiba</p>
[ { "answer_id": 74653206, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": -1, "selected": false, "text": "<header>\n <h1 id=\"title\">\n </h1>\n <ul>\n ...\n <a href=\"#\" onClick=\"selectTitle('Sobre')\">Sobre</a>\n selectTitle h1 function selectTitle(title) {\n document.getElementById('title').innerHTML = title;\n}\n" }, { "answer_id": 74653338, "author": "Diego D", "author_id": 1221208, "author_profile": "https://Stackoverflow.com/users/1221208", "pm_score": 2, "selected": true, "text": "About event.target data-submenu document.querySelectorAll('header a')\n .forEach(anchor => {\n anchor.addEventListener('click', event => {\n const clickedElement = event.target; \n const parentSubmenu = clickedElement.closest('li[data-submenu]'); \n if(parentSubmenu && parentSubmenu !== clickedElement.parentNode ){\n console.log(`${parentSubmenu.dataset.submenu}-${clickedElement.innerText}`);\n }else{\n console.log(clickedElement.innerText);\n } \n });\n }); <header>\n <ul>\n <li>\n <a href=\"#\">Sobre</a>\n </li>\n <li>\n <a href=\"#\">O que fazemos</a>\n </li>\n <li data-submenu='Nossas sedes'>\n <a href=\"#\">Nossas sedes</a>\n <ul>\n <li>\n <a href=\"#\">Curitiba</a>\n </li>\n <li>\n <a href=\"#\">Acre</a>\n </li>\n <li>\n <a href=\"#\">Salvador</a>\n </li>\n </ul>\n </li>\n <li data-submenu='Serviços'>\n <a href=\"#\">Serviços</a>\n <ul>\n <li>\n <a href=\"#\">Google Analytics</a>\n </li>\n <li>\n <a href=\"#\">Google Tag Manager</a>\n </li>\n </ul>\n </li>\n </ul>\n</header>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16658729/" ]
74,653,163
<p>Consider the following 2d array:</p> <pre><code>&gt;&gt;&gt; A = np.arange(2*3).reshape(2,3) array([[0, 1, 2], [3, 4, 5]]) &gt;&gt;&gt; b = np.array([1, 2]) </code></pre> <p>I would like to get the following mask from A as row wise condition from b as an upper index limit:</p> <pre><code>&gt;&gt;&gt; mask array([[True, False, False], [True, True, False]]) </code></pre> <p>Can numpy do this in a vectorized manner?</p>
[ { "answer_id": 74653188, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "mask = np.arange(A.shape[1]) < b[:,None]\n array([[ True, False, False],\n [ True, True, False]])\n" }, { "answer_id": 74653842, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "mask = np.tril(np.ones(A.shape, dtype=bool))\n array([[ True, False, False],\n [ True, True, False]])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10514935/" ]
74,653,186
<p>Table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Employee</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>USA</td> </tr> <tr> <td>Davis</td> <td>Australia</td> </tr> <tr> <td>Maria</td> <td>Australia</td> </tr> <tr> <td>Nancy</td> <td>USA</td> </tr> </tbody> </table> </div> <p>Table 2</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Country</th> <th>Employee</th> <th>Clients</th> </tr> </thead> <tbody> <tr> <td>USA</td> <td>??</td> <td>Johnson</td> </tr> <tr> <td></td> <td></td> <td>Twitter</td> </tr> <tr> <td></td> <td></td> <td>FaceBook</td> </tr> <tr> <td></td> <td></td> <td>IBM</td> </tr> <tr> <td></td> <td></td> <td>RedHat</td> </tr> <tr> <td></td> <td></td> <td>Phizer</td> </tr> </tbody> </table> </div> <p>?? should correspond to data from Table 1 with the Country filter.</p> <p>For our example, it would be <code>John, Nancy</code> in the same cell, preferably in the next line (alt+enter)</p> <p><code>John,</code></p> <p><code>Nancy</code></p> <p>I have tried to concatenate + transpose, but I am unable to make it work.</p> <p>Moreover, I am unable to find any way to do the equivalent of sumif() in transpose.</p>
[ { "answer_id": 74653278, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 3, "selected": true, "text": "google-sheet =TEXTJOIN(CHAR(10),1,FILTER(A2:A,B2:B=H2))\n CHAR(10)" }, { "answer_id": 74655089, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": false, "text": "=BYROW(D5:D10, LAMBDA(x, TEXTJOIN(CHAR(10), 1, IFERROR(FILTER(A:A, B:B=x)))))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7513280/" ]
74,653,198
<p>I wanted to practice with array and I don't get why it doesn't print the following out: The problem is that the terminal outputs: null Why is that and what did I do wrong?</p> <pre><code>package Practice; public class CreatingArrays { public static void main(String[] args) { String[] women = { &quot;persian&quot;, &quot;palestinian&quot;, &quot;german&quot;, &quot;russian&quot;, &quot;spanish&quot;, &quot;italian&quot;, &quot;greek&quot;, &quot;hungarian&quot;, &quot;brazilian&quot;, &quot;turkish&quot; }; women = new String[10]; System.out.println(women[8]); } } </code></pre>
[ { "answer_id": 74653238, "author": "Jostein S", "author_id": 20106677, "author_profile": "https://Stackoverflow.com/users/20106677", "pm_score": 1, "selected": false, "text": "women = new String[10];" }, { "answer_id": 74653626, "author": "z48o0", "author_id": 2957840, "author_profile": "https://Stackoverflow.com/users/2957840", "pm_score": 0, "selected": false, "text": "String[] women = { \"persian\", \"palestinian\", \"german\", \"russian\",\n\"spanish\", \"italian\", \"greek\", \"hungarian\",\"brazilian\", \"turkish\" };\n\nSystem.out.println(women[8]);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20546326/" ]
74,653,209
<p>In a given id of a <code>&lt;div&gt;</code> I need to get a list of all the elements which are in that div.</p> <p>My goal is to get a list of all elements in the given div and loop over them hide everyone except the first one.</p> <p>Example:</p> <pre><code>&lt;div id=&quot;RandomId&quot;&gt; &lt;img src=&quot;src_1&quot; /&gt; &lt;img src=&quot;src_2&quot; /&gt; &lt;img src=&quot;src_3&quot; /&gt; . . . &lt;img src=&quot;src_n&quot; /&gt; &lt;/div&gt; &lt;script&gt; function handleImages(divID) { const div = document.getElementById(DivID); if(div) { const Elements = // Here, I need the list; for (let i = 0; i &lt; Elements.length; i++) { if (i == 0) { continue; } else { Elements[i].style = &quot;display:block&quot;; } } } return null; } &lt;/script&gt; </code></pre>
[ { "answer_id": 74653235, "author": "Grizou", "author_id": 20068386, "author_profile": "https://Stackoverflow.com/users/20068386", "pm_score": 2, "selected": true, "text": "Element.children" }, { "answer_id": 74653242, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "<script>\nfunction handleImages(divID){\n const div = document.getElementById(DivID);\n if(div){\n\n const Elements = div.children //Here, I need the list;\n\n for (let i = 0; i < Elements.length; i++){\n if (i == 0) { continue; }\n else {Elements[i].style = \"display:block\";}\n }\n }\n return null;\n\n}\n</script>\n Element.children" }, { "answer_id": 74653259, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": 2, "selected": false, "text": "querySelectorAll const Elements = document.querySelectorAll('#RandomId > img')\n" }, { "answer_id": 74653318, "author": "DecPK", "author_id": 9153448, "author_profile": "https://Stackoverflow.com/users/9153448", "pm_score": 0, "selected": false, "text": "querySelectorAll first child function handleImages(id) {\n const allChildren = [...document.querySelectorAll(`#${id} > img`)];\n allChildren.forEach(\n (imgChild, index) =>\n (imgChild.style.display = index === 0 ? \"block\" : \"none\")\n );\n}\nhandleImages(\"RandomId\"); <div id=\"RandomId\">\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n</div>" }, { "answer_id": 74653357, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "// Get the <div> element with the id \"myDiv\"\nconst myDiv = document.getElementById(\"myDiv\");\n\n// Use the querySelectorAll() method to get a list of all elements within the <div>\nconst elementsInMyDiv = myDiv.querySelectorAll(\"img\");\n\n// Loop over the elements in the list and hide each one (except for the first one)\nfor (let i = 1; i < elementsInMyDiv.length; i++) {\n elementsInMyDiv[i].style.display = \"none\";\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20102061/" ]
74,653,239
<p>I need to save an Image in Python (created as a Numpy array) as a JPEG file, while including a &quot;comment&quot; in the file with some specific metadata. This metadata will be used by another (third-party) application and is a simple ASCII string. I have a sample image including such a &quot;comment&quot;, which I can read out using Pillow (PIL), via the <code>image.info['comment']</code> or the <code>image.app['COM']</code> property. However, when I try a simple round-trip, i.e. loading my sample image and save it again using a different file name, the comment is no longer preserved. Equally, I found no way to include a comment in a newly created image.</p> <p>I am aware that EXIF tags are the preferred way to save metadata in JPEG images, but as mentioned, the third-party application only accepts this data as a &quot;comment&quot;, not as EXIF, which I cannot change. After reading <a href="https://stackoverflow.com/questions/8283798/adding-a-comment-to-a-jpeg-file-using-python">this</a> question, I looked into the binary structure of my sample file and found the comment at the start of the file, after a few bytes of some other (meta)data. I do however not know a lot about binary file manipulation, and also I was wondering if there is a more elegant way, other than messing with the binary...</p> <p>EDIT: minimum example:</p> <pre class="lang-py prettyprint-override"><code>from PIL import Image img = Image.open(path) # where path is the path to the sample image # this prints the desired metadata if it is correctly saved in loaded image print(img.info[&quot;comment&quot;]) img.save(new_path) # save with different file name img.close() # now open to see if it has been saved correctly new_img = Image.open(new_path) print(new_img.info['comment']) # now results in KeyError </code></pre> <p>I also tried <code>img.save(new_path, info=img.info)</code>, but this does not seem to have an effect. Since <code>img.info['comment']</code> appears identical to <code>img.app['COM']</code>, I tried <code>img.save(new_path, app=img.app)</code>, again does not work.</p>
[ { "answer_id": 74653235, "author": "Grizou", "author_id": 20068386, "author_profile": "https://Stackoverflow.com/users/20068386", "pm_score": 2, "selected": true, "text": "Element.children" }, { "answer_id": 74653242, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "<script>\nfunction handleImages(divID){\n const div = document.getElementById(DivID);\n if(div){\n\n const Elements = div.children //Here, I need the list;\n\n for (let i = 0; i < Elements.length; i++){\n if (i == 0) { continue; }\n else {Elements[i].style = \"display:block\";}\n }\n }\n return null;\n\n}\n</script>\n Element.children" }, { "answer_id": 74653259, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": 2, "selected": false, "text": "querySelectorAll const Elements = document.querySelectorAll('#RandomId > img')\n" }, { "answer_id": 74653318, "author": "DecPK", "author_id": 9153448, "author_profile": "https://Stackoverflow.com/users/9153448", "pm_score": 0, "selected": false, "text": "querySelectorAll first child function handleImages(id) {\n const allChildren = [...document.querySelectorAll(`#${id} > img`)];\n allChildren.forEach(\n (imgChild, index) =>\n (imgChild.style.display = index === 0 ? \"block\" : \"none\")\n );\n}\nhandleImages(\"RandomId\"); <div id=\"RandomId\">\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n</div>" }, { "answer_id": 74653357, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "// Get the <div> element with the id \"myDiv\"\nconst myDiv = document.getElementById(\"myDiv\");\n\n// Use the querySelectorAll() method to get a list of all elements within the <div>\nconst elementsInMyDiv = myDiv.querySelectorAll(\"img\");\n\n// Loop over the elements in the list and hide each one (except for the first one)\nfor (let i = 1; i < elementsInMyDiv.length; i++) {\n elementsInMyDiv[i].style.display = \"none\";\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8467078/" ]
74,653,316
<p>How to select values in drop down select tag in react, please help to achieve as below.</p> <p>Here is my code</p> <pre><code> &lt;div&gt; &lt;SelectField label={&quot;Select Job Category&quot;} onChange={(e) =&gt; { console.log(e.target); }} value={listJobCategories} data={listJobCategories?.map((v) =&gt; ( &lt;option key={v.id} value={v} onChange={(e) =&gt; { console.log(v); console.log(e); }} &gt; {v?.attributes?.Name} &lt;/option&gt; ))} /&gt; {listCategories &amp;&amp; ( &lt;div className=&quot;flex flex-row flex-1 space-x-2 mt-4 mb-6&quot;&gt; {listCategories?.map((v) =&gt; ( &lt;Badge title={v?.id} className=&quot;text-white p-2&quot; key={v?.id} isDeleteOn={true} onClickDelete={() =&gt; { console.log(v?.id); // setListCategoriesId((prev) =&gt; // prev.filter((el) =&gt; el != v?.id) // ); // setListCategories((prev) =&gt; // prev.filter( // (el) =&gt; el?.attributes?.Name != v?.attributes?.Name // ) // ); }} /&gt; ))} &lt;/div&gt; </code></pre> <p>listJobCategories is useState from api, and the data structure looks like below:</p> <pre><code>{ &quot;id&quot;: 2, &quot;attributes&quot;: { &quot;Name&quot;: &quot;Accounting &amp; Finance&quot;, &quot;createdAt&quot;: &quot;2022-09-08T04:40:53.307Z&quot;, &quot;updatedAt&quot;: &quot;2022-11-21T14:48:49.994Z&quot;, &quot;publishedAt&quot;: &quot;2022-09-08T04:40:54.154Z&quot;, &quot;Type&quot;: null } }, { &quot;id&quot;: 3, &quot;attributes&quot;: { &quot;Name&quot;: &quot;Corporate Affairs &amp; Legal&quot;, &quot;createdAt&quot;: &quot;2022-09-08T04:41:25.968Z&quot;, &quot;updatedAt&quot;: &quot;2022-11-21T14:51:53.205Z&quot;, &quot;publishedAt&quot;: &quot;2022-09-08T04:41:26.822Z&quot;, &quot;Type&quot;: null } } } </code></pre> <p>This is how the UI looks like</p> <p><a href="https://i.stack.imgur.com/hyEIJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hyEIJ.png" alt="enter image description here" /></a></p> <p>I'm expecting to achieve like below</p> <p><a href="https://i.stack.imgur.com/7AkOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7AkOZ.png" alt="enter image description here" /></a></p> <p>I have console log e.target, result as below</p> <p><a href="https://i.stack.imgur.com/m0ZLB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m0ZLB.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74653235, "author": "Grizou", "author_id": 20068386, "author_profile": "https://Stackoverflow.com/users/20068386", "pm_score": 2, "selected": true, "text": "Element.children" }, { "answer_id": 74653242, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "<script>\nfunction handleImages(divID){\n const div = document.getElementById(DivID);\n if(div){\n\n const Elements = div.children //Here, I need the list;\n\n for (let i = 0; i < Elements.length; i++){\n if (i == 0) { continue; }\n else {Elements[i].style = \"display:block\";}\n }\n }\n return null;\n\n}\n</script>\n Element.children" }, { "answer_id": 74653259, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": 2, "selected": false, "text": "querySelectorAll const Elements = document.querySelectorAll('#RandomId > img')\n" }, { "answer_id": 74653318, "author": "DecPK", "author_id": 9153448, "author_profile": "https://Stackoverflow.com/users/9153448", "pm_score": 0, "selected": false, "text": "querySelectorAll first child function handleImages(id) {\n const allChildren = [...document.querySelectorAll(`#${id} > img`)];\n allChildren.forEach(\n (imgChild, index) =>\n (imgChild.style.display = index === 0 ? \"block\" : \"none\")\n );\n}\nhandleImages(\"RandomId\"); <div id=\"RandomId\">\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n</div>" }, { "answer_id": 74653357, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "// Get the <div> element with the id \"myDiv\"\nconst myDiv = document.getElementById(\"myDiv\");\n\n// Use the querySelectorAll() method to get a list of all elements within the <div>\nconst elementsInMyDiv = myDiv.querySelectorAll(\"img\");\n\n// Loop over the elements in the list and hide each one (except for the first one)\nfor (let i = 1; i < elementsInMyDiv.length; i++) {\n elementsInMyDiv[i].style.display = \"none\";\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8140319/" ]
74,653,327
<p>I can see the table on the screen and all the information from the db.json is imported. When I open console it shows me these errors: Text nodes cannot appear as a child of <code>&lt;table&gt;</code> [ReactJS]; Warning: Each child in a list should have a unique &quot;key&quot; prop. I tried changing div to fragment but it isn't working. How can I solve this?</p> <pre><code>return ( &lt;div className='container'&gt; &lt;table className=&quot;table&quot;&gt; &lt;thead&gt; &lt;tr className='bg-dark text-white'&gt; &lt;th scope=&quot;col&quot;&gt;#&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Product Name&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Product Number&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Color&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;List Price&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Modified Date&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {products.map((product, index) =&gt; ( &lt;tr&gt; &lt;th scope='row'&gt; {index + 1}&lt;/th&gt; &lt;td&gt;{product.name}&lt;/td&gt; &lt;td&gt;{product.number}&lt;/td&gt; &lt;td&gt;{product.color}&lt;/td&gt; &lt;td&gt;{product.price}&lt;/td&gt; &lt;td&gt;{product.date}&lt;/td&gt; &lt;td&gt; &lt;Link className='btn btn-primary m-2'&gt;&lt;i className=&quot;fa fa-eye&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/Link&gt; &lt;Link className='btn btn-otline-primary m-2'&gt;Edit&lt;/Link&gt; &lt;Link className='btn btn-danger m-2'&gt;Delete&lt;/Link&gt; &lt;/td&gt; &lt;/tr&gt; ))}; &lt;/tbody&gt; &lt;/table&gt; &lt;Link className='btn btn-outline-dark w-25' to='/product/add'&gt; Add Product &lt;/Link&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74653235, "author": "Grizou", "author_id": 20068386, "author_profile": "https://Stackoverflow.com/users/20068386", "pm_score": 2, "selected": true, "text": "Element.children" }, { "answer_id": 74653242, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "<script>\nfunction handleImages(divID){\n const div = document.getElementById(DivID);\n if(div){\n\n const Elements = div.children //Here, I need the list;\n\n for (let i = 0; i < Elements.length; i++){\n if (i == 0) { continue; }\n else {Elements[i].style = \"display:block\";}\n }\n }\n return null;\n\n}\n</script>\n Element.children" }, { "answer_id": 74653259, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": 2, "selected": false, "text": "querySelectorAll const Elements = document.querySelectorAll('#RandomId > img')\n" }, { "answer_id": 74653318, "author": "DecPK", "author_id": 9153448, "author_profile": "https://Stackoverflow.com/users/9153448", "pm_score": 0, "selected": false, "text": "querySelectorAll first child function handleImages(id) {\n const allChildren = [...document.querySelectorAll(`#${id} > img`)];\n allChildren.forEach(\n (imgChild, index) =>\n (imgChild.style.display = index === 0 ? \"block\" : \"none\")\n );\n}\nhandleImages(\"RandomId\"); <div id=\"RandomId\">\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n <img src=\"https://picsum.photos/200/300\" />\n</div>" }, { "answer_id": 74653357, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "// Get the <div> element with the id \"myDiv\"\nconst myDiv = document.getElementById(\"myDiv\");\n\n// Use the querySelectorAll() method to get a list of all elements within the <div>\nconst elementsInMyDiv = myDiv.querySelectorAll(\"img\");\n\n// Loop over the elements in the list and hide each one (except for the first one)\nfor (let i = 1; i < elementsInMyDiv.length; i++) {\n elementsInMyDiv[i].style.display = \"none\";\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14958858/" ]
74,653,330
<p>I want to mock object <code>A a</code> return from <code>B.foo()</code>.</p> <p>I've tried mock <code>A</code> with <code>@Mock</code>, it didn't work.</p> <pre><code>class SomeClass() { public void doSomeThing() { B b = new B(); A a = b.foo(); a.foo(); } } </code></pre> <pre><code>@Mock A a; @InjectMock SomeClass someClass; @Test void test() { Mockito.when( a.foo() ).thenReturn( something ); assertDoesNotThrow( () -&gt; someClass.doSomeThing() ); } </code></pre> <p>How can I mock <code>A</code>?</p>
[ { "answer_id": 74657505, "author": "Sascha Doerdelmann", "author_id": 11934850, "author_profile": "https://Stackoverflow.com/users/11934850", "pm_score": -1, "selected": false, "text": "public class SomeClassTest {\n @Mock\n A a;\n\n @InjectMocks\n SomeClass someClass;\n\n private AutoCloseable closeable;\n\n @BeforeEach\n public void openMocks() {\n closeable = MockitoAnnotations.openMocks(this);\n }\n\n @AfterEach\n public void releaseMocks() throws Exception {\n closeable.close();\n }\n\n @Test\n void test() {\n Mockito.when( a.foo() ).thenReturn(true);\n Assertions.assertDoesNotThrow( () -> someClass.doSomeThing() );\n }\n}\n @MockitoSettings(strictness = Strictness.STRICT_STUBS)\n SomeClassTest SomeClass.doSomeThing InjectMocks SomeClass.doSomeThing" }, { "answer_id": 74668145, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 3, "selected": true, "text": "class SomeClass {\n public void doSomeThing() {\n B b = new B();\n A a = b.foo();\n a.foo();\n }\n}\n B SomeClass B SomeClass B B class SomeClass {\n private final Supplier<? extends B> bFactory;\n public SomeClass(final Supplier<? extends B> bFactory) {\n this.bFactory = bFactory;\n }\n\n // Production code can use the parameterless constructor to get the old behavior\n // But this is mostly to help with migration, real code should use the parameterized constructor too\n public SomeClass() {\n this(B::new);\n }\n\n public void doSomeThing() {\n B b = this.bFactory.get();\n A a = b.foo();\n a.foo();\n }\n}\n @Test\nvoid test() {\n final A aMock = mock(A.class);\n when(aMock.foo()).thenAnswer(a -> /* ... */);\n final B bMock = mock(B.class);\n when(bMock.foo()).thenReturn(aMock);\n final SomeClass someClass = new SomeClass(() -> bMock);\n assertDoesNotThrow( () -> someClass.doSomeThing() );\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9290993/" ]
74,653,347
<p>I want the user to input hours and minutes for a Local.Time from 00 to 23 and from 00 to 59, I scanned this as an int. It works but for values from 00 to 09 the int ignores the 0 and places then as a 0,1,2...9 instead of 00,01,02,03...09; this breaks the Local.Time since, for example &quot;10:3&quot;; is not a valid format for time.</p> <p>I have read I can format this as a String, but I don't think that helps me since I need an int value to build the LocalTime and subsequent opperations with it.</p> <p>There is a way of formatting this while kepping the variable as an int?? Can I code this differently to bypass this?? Am I wrong about how these classes work??</p> <p>I am pretty new to these concepts</p> <p>Here is the code I am using</p> <pre><code>int hours; int minutes; System.out.println(&quot;Input a number for the hours (00-23): &quot;); hours = scan.nextInt(); System.out.println(&quot;Input a number for the minutes (00-59): &quot;); minutes = scan.nextInt(); LocalTime result = LocalTime.parse(hours + &quot;:&quot; + minutes); </code></pre> <p>I tried using the NumberFormat class but it returns an error when trying to declare its variables (something like it is an abstract variable and cannot be instanced)</p> <p>I also tried using the String format but I don't really know what to do with that string after that, it asks me for a int and not a string to build this method</p>
[ { "answer_id": 74653418, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 4, "selected": true, "text": "int LocalTime.parse int LocalTime.of(hours, minutes) LocalTime result = LocalTime.of(hours, minutes);\n" }, { "answer_id": 74653456, "author": "deHaar", "author_id": 1712135, "author_profile": "https://Stackoverflow.com/users/1712135", "pm_score": 3, "selected": false, "text": "LocalTime.of(hours, minutes) DateTimeFormatter public static void main(String[] args) {\n // single-digit example values\n int hours = 9;\n int minutes = 1;\n // define a formatter that parses single-digit hours and minutes\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"H:m\");\n // use it as second argument in LocalTime.parse\n LocalTime result = LocalTime.parse(hours + \":\" + minutes, dtf);\n // see the result\n System.out.println(result);\n}\n 09:01\n" }, { "answer_id": 74653463, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 1, "selected": false, "text": "DateTimeFormatter LocalTime.parse(hours + \":\" + minutes, DateTimeFormatter.ofPattern(\"H:m\"));\n LocalTime.parse(String.format(\"%02d:%02d\", hours, minutes));\n LocalTime.of(hours, minutes);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664407/" ]
74,653,362
<p>I would like to delete rows from my database that have the same name. I've checked Stackoverflow and found something like this:</p> <pre><code>DELETE FROM my_table mt1 USING my_table mt2 WHERE mt1.my_name = mt2.my_name AND mt1.unique_id&lt;mt2.unique_id; </code></pre> <p>This of course works but leaves one row. I have a request:</p> <p><strong>If there are rows with duplicate rows I have to remove ALL of them (not leave one).</strong></p>
[ { "answer_id": 74653442, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 4, "selected": true, "text": "GROUP BY HAVING DELETE\nFROM my_table \nWHERE my_name IN \n(SELECT\n my_name\nFROM\n my_table\nGROUP BY\n my_name\nHAVING \n COUNT(*) > 1);\n" }, { "answer_id": 74653561, "author": "PeterClemmensen", "author_id": 4044936, "author_profile": "https://Stackoverflow.com/users/4044936", "pm_score": 0, "selected": false, "text": "drop table if exists #have;\n\ncreate table #have\n(\n ID [int]\n, val [varchar](10)\n)\n;\n\ninsert into #have\nvalues (1, 'a')\n , (2, 'b')\n , (2, 'b')\n , (3, 'c')\n\nselect * from #have;\n\ndelete a\nfrom #have a\ninner join \n(select id from #have \n group by id\n having count(*) > 1\n) b\n on a.id = b.id\n ;\n\nselect * from #have;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3665662/" ]
74,653,366
<p>please see the image below for two examples of what is to be achived</p> <p><a href="https://i.stack.imgur.com/izvul.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/izvul.png" alt="UILabels to be aligned" /></a></p> <p>the alignment should be on the Center Y of the first lines of each UILabels and should work regardless of font size or font. currently we have implemented this with different constraints to the top of the super view for different font and font size combinations.</p> <p>the constraint to align the center of the two UILabels does not work since the text of the second UILabel is not fixed and can have several lines.</p> <p>also the text is dynamic, so it is not known where the text will wrap to create the first line, thus it cannot be shown in an one line UILabel with the rest of the text in another one below.</p> <p>currently this is implemented using UIKit, but if there is an easy solution in SwiftUI we can put these two labels in a SwiftUI component. so a SwiftUI solution would also be welcomed.</p>
[ { "answer_id": 74653487, "author": "jrturton", "author_id": 852828, "author_profile": "https://Stackoverflow.com/users/852828", "pm_score": 2, "selected": false, "text": "centerYAnchor firstBaselineAnchor UIFont capHeight * 0.5 leftLabel.centerYAnchor.constraint(equalTo: rightLabel.firstBaseLineAnchor, constant: rightFont.capHeight * 0.5)\n" }, { "answer_id": 74678573, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 1, "selected": false, "text": "\" ' \" ' \" . , . , . .hidden = true UILabel" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322622/" ]
74,653,395
<p>I want to move moodle lms from local server to live server, I moved moodeldata to httpdocs and tired to figure out httpdocs directory path on shared Linux based Plesk server. I appreciate any one helps me!</p> <p>I tried like this</p> <pre><code>$CFG-&gt;dataroot='\httpdocs\moodledata'; </code></pre> <p>but the result is</p> <blockquote> <p>Fatal error: $CFG-&gt;dataroot is not configured properly, directory does not exist or is not accessible! Exiting.</p> </blockquote>
[ { "answer_id": 74653487, "author": "jrturton", "author_id": 852828, "author_profile": "https://Stackoverflow.com/users/852828", "pm_score": 2, "selected": false, "text": "centerYAnchor firstBaselineAnchor UIFont capHeight * 0.5 leftLabel.centerYAnchor.constraint(equalTo: rightLabel.firstBaseLineAnchor, constant: rightFont.capHeight * 0.5)\n" }, { "answer_id": 74678573, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 1, "selected": false, "text": "\" ' \" ' \" . , . , . .hidden = true UILabel" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664230/" ]
74,653,398
<p>So, the question I am trying to solve is...</p> <p>&quot;Return true if two arrays are equal.</p> <p>The arrays are equal if they are the same length and contain the same value at each particular index.</p> <p>Two empty arrays are equal.&quot;</p> <p>for example:</p> <pre><code>input: a == [1, 9, 4, 6, 3] b == [1, 9, 4, 6, 3] output: true OR input: a == [5, 3, 1] b == [6, 2, 9, 4] output: false </code></pre> <p>This is how I went about it. I'm able to get the length of the arrays right, but I don't know how to ensure the values in it will be the same too. That's the part I am stuck on how to implement.</p> <pre><code>def solution(a, b): if range(len(a)) == range(len(b)): return True else: return False </code></pre>
[ { "answer_id": 74653427, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": -1, "selected": false, "text": "numpy.array_equal a = [1, 9, 4, 6, 3]\nb = [1, 9, 4, 6, 3]\nnp.array_equal(a, b)\n# True\n\na = [5, 3, 1]\nb = [6, 2, 9, 4]\nnp.array_equal(a, b)\n# False\n\nnp.array_equal([], [])\n# True\n" }, { "answer_id": 74654633, "author": "Isha Goyal", "author_id": 20665444, "author_profile": "https://Stackoverflow.com/users/20665444", "pm_score": -1, "selected": false, "text": "def solution(a, b):\n x = 0\n if (len(a) == len(b)): \n for i in range(len(a)):\n if (a[i] == b[i]):\n x = 1\n else:\n x = 0\n break\n if (x==1):\n return True\n else:\n return False\n else: \n return False\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663553/" ]
74,653,428
<p>I have a dataframe similar to the following.</p> <pre><code>import pandas as pd data = pd.DataFrame({'ind': [111,222,333,444,555,666,777,888,999,000], 'col1': [1,2,2,2,3,4,5,5,6,7], 'col2': [9,2,2,2,9,9,5,5,9,9], 'col3': [11,2,2,2,11,11,5,5,11,11], 'val': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']}) </code></pre> <p>There is an index <code>ind</code>, a number of columns <code>col</code> 1, 2 and 3, and some other column with a value <code>val</code>. Within the three columns 1, 2 and 3 there are a number of rows which are the exact same as the previous row, for instance row with index 333 and 444 are the same as 222. My actual data set is larger but what I need to do is delete all rows which have the exact same value as the <strong>immediate</strong> previous row for a number of columns (<code>col1</code>, <code>col2</code>, <code>col3</code> here).</p> <p>This would give me a dataframe like this with indeces 333/444 and 888 removed:</p> <pre><code>data_clean = pd.DataFrame({'ind': [111,222,555,666,777,999,000], 'col1': [1,2,3,4,5,6,7], 'col2': [9,2,9,9,5,9,9], 'col3': [11,2,11,11,5,11,11], 'val': ['a', 'b', 'e', 'f', 'g', 'i', 'j']}) </code></pre> <p>What is the best way to go about this for a larger dataframe?</p>
[ { "answer_id": 74653427, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": -1, "selected": false, "text": "numpy.array_equal a = [1, 9, 4, 6, 3]\nb = [1, 9, 4, 6, 3]\nnp.array_equal(a, b)\n# True\n\na = [5, 3, 1]\nb = [6, 2, 9, 4]\nnp.array_equal(a, b)\n# False\n\nnp.array_equal([], [])\n# True\n" }, { "answer_id": 74654633, "author": "Isha Goyal", "author_id": 20665444, "author_profile": "https://Stackoverflow.com/users/20665444", "pm_score": -1, "selected": false, "text": "def solution(a, b):\n x = 0\n if (len(a) == len(b)): \n for i in range(len(a)):\n if (a[i] == b[i]):\n x = 1\n else:\n x = 0\n break\n if (x==1):\n return True\n else:\n return False\n else: \n return False\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16002179/" ]
74,653,446
<p>I have the following code in React:</p> <pre class="lang-js prettyprint-override"><code>const TABS = [ { value: &quot;Names&quot;, label: &quot;Names&quot;, onclick: (obj) =&gt; { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: &quot;Logs&quot;, label: &quot;Logs&quot;, onclick: (obj) =&gt; { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: &quot;Groups&quot;, label: &quot;Groups&quot;, onclick: (obj) =&gt; { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: &quot;Subscriptions&quot;, label: &quot;Subscriptions&quot;, onclick: (obj) =&gt; { tabOnClick(obj.value); }, selected: mainTabSelected, }, ] </code></pre> <p>I have tried to make the code dynamic, as the following:</p> <pre class="lang-js prettyprint-override"><code>const values = [&quot;Names&quot;,&quot;Logs&quot;,&quot;Groups&quot;,&quot;Subscriptions&quot;]; const labels = [&quot;Names&quot;,&quot;Logs&quot;,&quot;Groups&quot;,&quot;Subscriptions&quot;]; const TABS = [ { value: {values}, label: {labels}, onclick: (obj) =&gt; { tabOnClick(obj.value); }, selected: mainTabSelected, }] </code></pre> <p>Am I right?</p>
[ { "answer_id": 74653427, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": -1, "selected": false, "text": "numpy.array_equal a = [1, 9, 4, 6, 3]\nb = [1, 9, 4, 6, 3]\nnp.array_equal(a, b)\n# True\n\na = [5, 3, 1]\nb = [6, 2, 9, 4]\nnp.array_equal(a, b)\n# False\n\nnp.array_equal([], [])\n# True\n" }, { "answer_id": 74654633, "author": "Isha Goyal", "author_id": 20665444, "author_profile": "https://Stackoverflow.com/users/20665444", "pm_score": -1, "selected": false, "text": "def solution(a, b):\n x = 0\n if (len(a) == len(b)): \n for i in range(len(a)):\n if (a[i] == b[i]):\n x = 1\n else:\n x = 0\n break\n if (x==1):\n return True\n else:\n return False\n else: \n return False\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12519901/" ]
74,653,464
<p>My OS is Windows. When creating a Docker container and interacting with it using Windows powershell:</p> <pre><code>docker create -i --name test_container debian docker container start -i test_container </code></pre> <p>And running a command such as <code>ls</code>, then it gives the following error:</p> <pre><code>bash: line 2: $'ls\r': command not found </code></pre> <p>I assume this is because newlines in windows (<code>\r\n</code>) are different than unix (<code>\n</code>).</p> <p>How can I use powershell interactively with Docker?</p> <p>I've searched online for a solution on this, but only get results on converting files, not working with powershell directly. I've also looked through the settings of Docker to see if there's an option on this, but am unable to find anything to change this behavior. Running <code>docker start --help</code> does not provide any special options for usage with powershell.</p> <p>I specifically want to use powershell as I dislike cmd and the shell provided by Docker (the up/down keys don't work as expected for example).</p>
[ { "answer_id": 74654052, "author": "user20664576", "author_id": 20664576, "author_profile": "https://Stackoverflow.com/users/20664576", "pm_score": 0, "selected": false, "text": "-t docker create -it --name test_container debian \ndocker container start -i test_container\n" }, { "answer_id": 74654068, "author": "Alez", "author_id": 5317332, "author_profile": "https://Stackoverflow.com/users/5317332", "pm_score": 1, "selected": false, "text": "docker run -it --name test_container debian /bin/bash\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664576/" ]
74,653,466
<p>I am trying to concatonate multiple columns to just one column, but only if the column name is in a list. so issue = {'a','b','c'} is my list and would need to concatonate it as issue column with ; seperator.</p> <p>I have tried: 1.</p> <pre><code>df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue})))) </code></pre> <p>Which returns invalid syntax error</p> <p>2.</p> <pre><code>df_issue = df.withColumn('issue', lit(issue)) </code></pre> <p>this just returnd a b c and not their value</p> <p>Thank you</p> <p>I have tried: 1.</p> <pre><code>df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue})))) </code></pre> <p>Which returns invalid syntax error</p> <p>2.</p> <pre><code>df_issue = df.withColumn('issue', lit(issue)) </code></pre> <p>this just returnd a b c and not their value</p> <p>Thank you</p>
[ { "answer_id": 74654052, "author": "user20664576", "author_id": 20664576, "author_profile": "https://Stackoverflow.com/users/20664576", "pm_score": 0, "selected": false, "text": "-t docker create -it --name test_container debian \ndocker container start -i test_container\n" }, { "answer_id": 74654068, "author": "Alez", "author_id": 5317332, "author_profile": "https://Stackoverflow.com/users/5317332", "pm_score": 1, "selected": false, "text": "docker run -it --name test_container debian /bin/bash\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14833314/" ]
74,653,488
<p>I created a hook which works well when I toggle between light and dark modes in Chrome's Rendering, panel. However, the values in the ConfigProvider do not change when the theme is toggled. Can someone explain how to hack the design token to achieve the desired result?</p> <pre class="lang-js prettyprint-override"><code>&quot;use client&quot;; import '@/styles/global.scss'; import { Layout } from 'antd'; import { theme, ConfigProvider } from 'antd'; import palette from &quot;@/styles/palette.module.scss&quot;; import { lato, inter, futura } from '@/assets/fonts'; import { usePrefersColorScheme } from '@/hooks/index'; import { Navbar, Footer, Ribbon } from &quot;@/components/index&quot;; const themeConfig = { token: { components: { Button: { fontFamily: futura.style.fontFamily, }, Input: { fontFamily: lato.style.fontFamily } }, // typography fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'`, } }; // palette const colours = { lucid: { colorInfo: palette['cyan'], colorError: palette['red'], colorPrimary: palette['blue'], colorWarning: palette['orange'], colorSuccess: palette['green'], colorBgLayout: palette['light'] }, muted: { colorInfo: palette['muted-cyan'], colorError: palette['muted-red'], colorPrimary: palette['muted-blue'], colorWarning: palette['muted-orange'], colorSuccess: palette['muted-green'], colorBgLayout: palette['dark'] } } const RootLayout = ({ children }) =&gt; { const { token } = theme.useToken(); const lightThemed = usePrefersColorScheme(); const preference = (colours[lightThemed ? 'lucid' : 'muted']); return &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charSet=&quot;utf-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt; &lt;/head&gt; &lt;ConfigProvider theme={{ ...themeConfig, ...preference }}&gt; &lt;body className={`${inter.className}`}&gt; &lt;Layout&gt; &lt;Layout.Header style={{ background: token.colorBgLayout, lineHeight: 'normal' }}&gt; &lt;Navbar /&gt; &lt;/Layout.Header&gt; {children} &lt;Ribbon /&gt; &lt;Footer /&gt; &lt;/Layout&gt; &lt;/body&gt; &lt;/ConfigProvider&gt; &lt;/html&gt;; }; export default RootLayout; </code></pre> <p>Is there anything I'm missing with using the new design token in Ant Design version 5?</p>
[ { "answer_id": 74654052, "author": "user20664576", "author_id": 20664576, "author_profile": "https://Stackoverflow.com/users/20664576", "pm_score": 0, "selected": false, "text": "-t docker create -it --name test_container debian \ndocker container start -i test_container\n" }, { "answer_id": 74654068, "author": "Alez", "author_id": 5317332, "author_profile": "https://Stackoverflow.com/users/5317332", "pm_score": 1, "selected": false, "text": "docker run -it --name test_container debian /bin/bash\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13482737/" ]
74,653,520
<p>So, I already finish to create a job in Dataflow. This job to process ETL from PostgreSQL to BigQuery. So, I don't know to create a schedulling using Airflow. Can share how to schedule job dataflow using Airflow?</p> <p>Thank you</p>
[ { "answer_id": 74654052, "author": "user20664576", "author_id": 20664576, "author_profile": "https://Stackoverflow.com/users/20664576", "pm_score": 0, "selected": false, "text": "-t docker create -it --name test_container debian \ndocker container start -i test_container\n" }, { "answer_id": 74654068, "author": "Alez", "author_id": 5317332, "author_profile": "https://Stackoverflow.com/users/5317332", "pm_score": 1, "selected": false, "text": "docker run -it --name test_container debian /bin/bash\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13939457/" ]
74,653,536
<p>I'm trying to end the process when I run my code using a switch case.</p> <p>Full code:</p> <pre><code>int[] Slots = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; while (true) { Console.WriteLine(&quot;Please enter the number of the slot (1-10)&quot;); int Slot = Convert.ToInt32(Console.ReadLine()); if (Slots[Slot - 1] == 0) { Slots[Slot - 1] = 1; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(&quot;Reservation Successful!&quot;); } else if (Slots[Slot - 1] == 1) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(&quot;Slot preoccupied.&quot;); } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(&quot;(R)eserve another slot, (C)heck available slots or (E)nd Process?&quot;); char choice = Convert.ToChar(Console.ReadLine()); switch (choice) { case 'E': case 'e': break; case 'C': case 'c': Console.WriteLine(&quot;The available slots are:&quot;); for (int i = 0; i &lt; Slots.Length; i++) { if (Slots[i] == 0) Console.WriteLine(&quot;{0}&quot;, i + 1); } continue; case 'R': case 'r': continue; default: Console.WriteLine(&quot;Invalid Input&quot;); break; } } </code></pre> <p>Everything works fine except for the 'E' case.</p> <p>Whenever I try to use the 'E' case it doesn't perform the break command. Instead it pinpoints to the line:</p> <pre><code>int Slot = Convert.ToInt32(Console.ReadLine()); </code></pre> <p>And it says that 'Input String was not in a correct format' and when I try to do what the system recommends, which is to change the &quot;int&quot; to &quot;var&quot;. It just tells me to change it back to &quot;int&quot; instead.</p> <p>I am very confused, I have no idea what that means. I am a student and this was never taught to us yet so I don't know what to do.</p> <p>I expected it to work since it didn't give any errors when i try to run my code, and everything works fine except for the 'E' case.</p>
[ { "answer_id": 74653697, "author": "Kisar", "author_id": 7691321, "author_profile": "https://Stackoverflow.com/users/7691321", "pm_score": 0, "selected": false, "text": "break break int var" }, { "answer_id": 74653703, "author": "cmos", "author_id": 8283536, "author_profile": "https://Stackoverflow.com/users/8283536", "pm_score": 2, "selected": false, "text": "bool isRunning = true;\nwhile(isRunning)\n{\n //your logic\n switch(choice)\n {\n case 'E':\n case 'e':\n isRunning = false;\n break;\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664671/" ]
74,653,613
<p>We have a database for 3 book shops, all with an attached inventory and books in random units in stock. The query should display each bookstore, so 3 rows, followed by the quantity (which book in X book store has the highest value calculated with <code>MAX(INV.UnitsInStock)</code>, and finally a third column that displays the title of the corresponding book.</p> <pre><code>SELECT BS.Name, B.Title, MAX(UnitsInStock) AS 'Quantity' FROM Inventories AS INV JOIN BookShops AS BS ON BS.Id = INV.ShopId JOIN Books AS B ON B.Id = INV.BookId GROUP BY BS.Name </code></pre> <p>This gives me the following error:</p> <blockquote> <p>Column 'Books.Title' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.</p> </blockquote> <p>I also tried this:</p> <pre><code>SELECT BS.Name, MAX(UnitsInStock) AS 'Quantity' FROM Inventories AS INV JOIN BookShops AS BS ON BS.Id = INV.ShopId JOIN Books AS B ON B.Id = INV.BookId GROUP BY BS.Name </code></pre> <p>This shows the correct data so far but without the title of the book.</p> <p>I've tried temp tables, <code>string_agg()</code> (which correctly displays every single book), tried hardcoding each book after finding out exactly which one etc.</p> <p>How can I fix this?</p>
[ { "answer_id": 74658483, "author": "HSS", "author_id": 553231, "author_profile": "https://Stackoverflow.com/users/553231", "pm_score": -1, "selected": false, "text": "SELECT BS.Name,B.Title, MAX(UnitsInStock) AS 'Quantity'\nFROM Inventories AS INV\nJOIN BookShops AS BS ON BS.Id = INV.ShopId\nJOIN Books AS B ON B.Id = INV.BookId\nGROUP BY BS.Name, B.Title\n" }, { "answer_id": 74659149, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "BS.Name MAX(UnitsInStock) SELECT B.Title MAX(UnitsInStock) MAX(UnitsInStock) MIN(UnitsInStock) MAX() AVG() ON APPLY SELECT BS.Name, B.Title, INV.UnitsInStock As Quantity\nFROM BookShops BS\nOUTER APPLY (\n SELECT TOP 1 BookId, UnitsInStock\n FROM Inventories i\n WHERE i.ShopId = BS.Id\n ORDER BY UnitsInStock DESC\n) INV\nINNER JOIN Books b ON b.Id = INV.BookId\n row_number() SELECT Name, Title, UnitsInStock As Quantity \nFROM (\n SELECT BS.Name, B.Title inv.UnitsInStock,\n row_number() over (PARTITION BY BS.Id ORDER BY inv.UnitsInStock DESC) rn\n FROM BookShops bs\n INNER JOIN Inventories inv ON inv.ShopId = bs.Id\n INNER JOIN Books b on b.Id = inv.BookId\n) t\nWHERE rn = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664838/" ]
74,653,630
<p>Sorry for the strange title, I don't know how to phrase it better.</p> <p>Here is a playground link to what I already have: <a href="https://www.typescriptlang.org/play?ssl=12&amp;ssc=2&amp;pln=1&amp;pc=1#code/MYGwhgzhAECyCeBhcUA8AVAfNA3gWAChpoBbeWMAB2gF5oA7AUwHc4rUBpAGmgApfKYeCAD2YACYAuaOgDaHALoBKWtgBuIgJbilshZl5KA3NAD0p6AAkRrAC4jom6AHNGt6BwD8hQsTIB5ACMAK2kcaHlHemgAa0Z4EQAzGQVPaX41MBAAV0ZpOUUVGnUtHT1oAF9aXAqTcxkAC00YZuhbBsZoCDASTqToZgawdydmEWyQcWgQTTi2h3EHEXoQeDah93bW1rBokRDGYFsfIlJyNwaRcU5oRgAPW0Z6cRg4hOSsXjBpbmhgQPSgmEYikMnkylU0A02hU4XqWxgEE0znow2yACdOq1BsNHANxpNprNOvZoEM1IwAIS+YhmCwAOkZwA6wBiMDcwHpNOI9QkU1JZAolG50zct3otnRazoCPpgqo9Ncti+xhFT0l8E89Mo2QgDV4-1VpwqhAqQA" rel="nofollow noreferrer">https://www.typescriptlang.org/play?ssl=12&amp;ssc=2&amp;pln=1&amp;pc=1#code/MYGwhgzhAECyCeBhcUA8AVAfNA3gWAChpoBbeWMAB2gF5oA7AUwHc4rUBpAGmgApfKYeCAD2YACYAuaOgDaHALoBKWtgBuIgJbilshZl5KA3NAD0p6AAkRrAC4jom6AHNGt6BwD8hQsTIB5ACMAK2kcaHlHemgAa0Z4EQAzGQVPaX41MBAAV0ZpOUUVGnUtHT1oAF9aXAqTcxkAC00YZuhbBsZoCDASTqToZgawdydmEWyQcWgQTTi2h3EHEXoQeDah93bW1rBokRDGYFsfIlJyNwaRcU5oRgAPW0Z6cRg4hOSsXjBpbmhgQPSgmEYikMnkylU0A02hU4XqWxgEE0znow2yACdOq1BsNHANxpNprNOvZoEM1IwAIS+YhmCwAOkZwA6wBiMDcwHpNOI9QkU1JZAolG50zct3otnRazoCPpgqo9Ncti+xhFT0l8E89Mo2QgDV4-1VpwqhAqQA</a></p> <p>copy of playground:</p> <pre><code>class MyClass&lt;T&gt; { myMap = new Map&lt;K, ((payload: T[K]) =&gt; void)[]&gt;(); // How do i get K? myObj: { [K in keyof T]?: ((value: T[K]) =&gt; void)[] } = {}; // This is the same of what i would like to do only that this is an object myMethod&lt;K extends keyof T&gt;(a: K, cb: (payload: T[K]) =&gt; void) { // this signature is what i would like to have! // ...checks etc. // add to myMap let entry = this.myMap.get(a); entry?.push(cb); } } </code></pre> <p>So I have a class Foo and inside this class, I have a property of type Map&lt;,&gt; and now I would like to fill in these generics based on T. I have a method on this class where this works as expected because there I can introduce a second generic 'K' but I don't know how I can do that for my Map&lt;,&gt;.</p> <p>I was able to get it somehow working with an object but not with a Map&lt;,&gt;</p> <p>All ideas are highly appreciated!</p>
[ { "answer_id": 74658483, "author": "HSS", "author_id": 553231, "author_profile": "https://Stackoverflow.com/users/553231", "pm_score": -1, "selected": false, "text": "SELECT BS.Name,B.Title, MAX(UnitsInStock) AS 'Quantity'\nFROM Inventories AS INV\nJOIN BookShops AS BS ON BS.Id = INV.ShopId\nJOIN Books AS B ON B.Id = INV.BookId\nGROUP BY BS.Name, B.Title\n" }, { "answer_id": 74659149, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "BS.Name MAX(UnitsInStock) SELECT B.Title MAX(UnitsInStock) MAX(UnitsInStock) MIN(UnitsInStock) MAX() AVG() ON APPLY SELECT BS.Name, B.Title, INV.UnitsInStock As Quantity\nFROM BookShops BS\nOUTER APPLY (\n SELECT TOP 1 BookId, UnitsInStock\n FROM Inventories i\n WHERE i.ShopId = BS.Id\n ORDER BY UnitsInStock DESC\n) INV\nINNER JOIN Books b ON b.Id = INV.BookId\n row_number() SELECT Name, Title, UnitsInStock As Quantity \nFROM (\n SELECT BS.Name, B.Title inv.UnitsInStock,\n row_number() over (PARTITION BY BS.Id ORDER BY inv.UnitsInStock DESC) rn\n FROM BookShops bs\n INNER JOIN Inventories inv ON inv.ShopId = bs.Id\n INNER JOIN Books b on b.Id = inv.BookId\n) t\nWHERE rn = 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2722783/" ]
74,653,677
<p>Here is my dictionary:</p> <p><code>inventory = {60: 20, 100: 50, 120: 30}</code></p> <p>Keys are total cost of goods [$] and values are available weight [lb].</p> <p>I need to find a way to get key based on the highest cost per pound.</p> <p>I have already tried using:</p> <p><code>most_expensive = max(inventory, key={fucntion that calculates the ratio})</code></p> <p>But cannot guess the pythonic way to do that.</p> <p>Thank you in advance.</p>
[ { "answer_id": 74653722, "author": "ViggoTW", "author_id": 10512586, "author_profile": "https://Stackoverflow.com/users/10512586", "pm_score": 0, "selected": false, "text": "max([key/value for key, value in inventory.items()])" }, { "answer_id": 74653747, "author": "Thymen", "author_id": 10961342, "author_profile": "https://Stackoverflow.com/users/10961342", "pm_score": 3, "selected": true, "text": "key inventory.items() max(inventory.items(), key=lambda x: x[0]/x[1])\n (120, 30)\n" }, { "answer_id": 74653872, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 1, "selected": false, "text": "max(inventory, key=lambda k: k / inventory[k])\n 120\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12729533/" ]
74,653,690
<p>I am trying to duplicate all values in an array in my sheet. I have {1,6,14,15} and I want to output {1,1,6,6,14,14,15,15}. I would like to do this exclusively with functions. I have seen the VSTACK function, which seems very useful, however joining the insider thing seems like a hassle and would not allow this spreadsheet to be usable across other devices easily.</p> <p>I have tried the CONCAT function, however this simply returns 161415161415 which is not helpful to me. The various alternatives to VSTACK all remove duplicates, which is exactly not what I am looking for. Besides all of those alternatives are lengthy and hard for me to wrap my head around.</p>
[ { "answer_id": 74653738, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "ROW =TRANSPOSE(ROW(1:4)^0)\n ROW ^0 TRANSPOSE A B C D\n1 {1,1,1,1} {2,2,2,2} {3,3,3,3} {4,4,4,4}\n2 1 2 3 4\n INDEX =TRANSPOSE(ROW(1:4)^0)\n\n=TRANSPOSE({1,6,14,15}*(ROW(1:4)^0))\n INDEX A B C D E F\n1 {1,1,1,1} {6,6,6,6} {14,14,14,14} {15,15,15,15}\n2 1 6 14 15\n" }, { "answer_id": 74653803, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 1, "selected": false, "text": "LET SEQUENCE =LET(ζ,{1,6,14,15},INDEX(ζ,SEQUENCE(,2*COUNTA(ζ),,0.5)))" }, { "answer_id": 74653810, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": false, "text": "EXPAND() =LET(arr,{1,6,14,15},TOROW(IFERROR(EXPAND(arr,2),arr),,1))\n 2" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12421378/" ]
74,653,707
<p>I believe common lisp is the only language I have worked with that have a variety of extremely useful data structures.</p> <p>The a-list being the most important one to me. I use it all the time.</p> <p>When and why do you (or should you) use hash tables?</p> <p>My reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. Which honestly, I find weird considering almost everything is a list.</p> <p>Maybe I am missing something in my inexperience?</p>
[ { "answer_id": 74654373, "author": "coredump", "author_id": 124319, "author_profile": "https://Stackoverflow.com/users/124319", "pm_score": 3, "selected": true, "text": "(vector 0 1 2)\n make-person person-age person-name" }, { "answer_id": 74661569, "author": "Ehvince", "author_id": 1506338, "author_profile": "https://Stackoverflow.com/users/1506338", "pm_score": 2, "selected": false, "text": "#<HASH-TABLE :TEST EQL :COUNT 1 {100F4BA883}>\n print-object (serapeum:toggle-pretty-print-hash-table) CL-USER> (serapeum:dict :a 1 :b 2 :c 3)\n;; => #<HASH-TABLE :TEST EQUAL :COUNT 3 {100F6012D3}>\n\nCL-USER> (serapeum:toggle-pretty-print-hash-table)\n\n;; print the above HT again:\nCL-USER> **\n(SERAPEUM:DICT\n :A 1\n :B 2\n :C 3\n ) \n make-hash-table" }, { "answer_id": 74675728, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 1, "selected": false, "text": "* (defun lookup (alist key) (assoc key alist))\nLOOKUP\n* (lookup '((key1 . value1) (key2 . value2)) 'key1)\n(KEY1 . VALUE1)\n* (lookup '((key1 . value1) (key2 . value2)) 'key2)\n(KEY2 . VALUE2)\n* (lookup '((key2 . value3) (key1 . value1) (key2 . value2)) 'key2)\n(KEY2 . VALUE3)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16237416/" ]
74,653,723
<p>I cannot say I am so experienced with SQL. Here is my question. A table TripEvent have millions of rows. It contains a column Bold_ID that is indexed and unique.</p> <p>So I can have this query</p> <pre><code>select bold_id from TripEvent where bold_id in (354469477, 354469536, 354469500, 987359) </code></pre> <p>Result is</p> <pre><code>354469477 354469536 354469500 </code></pre> <p>as those exists. But I want to reverse it. How can I get a list if id's that don't exists ? In this case it should return one row</p> <pre><code>987359 </code></pre> <p>I cannot use NOT in query as that would return all rows in table not match my list.</p>
[ { "answer_id": 74653812, "author": "gotqn", "author_id": 1080354, "author_profile": "https://Stackoverflow.com/users/1080354", "pm_score": 1, "selected": false, "text": "SELECT DS.*\nFROM\n(\n VALUES (354469477)\n ,(354469536)\n ,(354469500)\n ,(987359)\n) DS (bold_id)\nLEFT JOIN TripEvent TE\n ON DS.[bold_id] = TE.[bold_id]\nWHERE TE.[bold_id] IS NULL;\n DS" }, { "answer_id": 74653937, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": false, "text": "EXCEPT SELECT bold_id FROM\n(\n SELECT 354469477 AS bold_id\n UNION ALL\n SELECT 354469536\n UNION ALL\n SELECT 354469500\n UNION ALL\n SELECT 987359\n) listofValues \nEXCEPT \nSELECT bold_id\nFROM TripEvent;\n SELECT bold_id FROM\n(\n VALUES (354469477),\n (354469536),\n (354469500),\n (987359)\n) listofValues(bold_id)\nEXCEPT \nSELECT bold_id\nFROM TripEvent;\n" }, { "answer_id": 74654185, "author": "Roland Bengtsson", "author_id": 55007, "author_profile": "https://Stackoverflow.com/users/55007", "pm_score": 0, "selected": false, "text": " SELECT *\n from (values (354469477),(354469536),(354469500),(987359)) as v(id)\n WHERE NOT EXISTS (SELECT BOLD_ID FROM TripEvent WHERE TripEvent.BOLD_ID = v.id)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55007/" ]
74,653,746
<p>Consider:</p> <pre><code>let N = 12 let arr = [1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1] </code></pre> <p>Your task is to find the maximum number of times an odd number is continuously repeated in the array.</p> <p>What is the approach for this?</p> <p>This is the hint:</p> <p>1 is repeated 4 times from index 0 to index 3 → 4 times</p> <p>2 is repeated 5 times from index 4 to index 8 → 5 times</p> <p>1 is repeated 3 times from index 9 to index 11 → 3 times</p> <p>The odd numbers in array are 1s.</p> <p>1 occurs 4 times and 3 times continuously, so 4 is the maximum number of times an odd number is continuously repeated in this array.</p> <pre><code>function longestRepeatedOdd(N, array) { // Write code here let count = 0; for (let i = 0; i &lt;= array.length-1; i++){ if (array[i] % 2 !== 0){ count++ }else if (array[i] % 2 === 0){ break; } } console.log(count) } </code></pre>
[ { "answer_id": 74653812, "author": "gotqn", "author_id": 1080354, "author_profile": "https://Stackoverflow.com/users/1080354", "pm_score": 1, "selected": false, "text": "SELECT DS.*\nFROM\n(\n VALUES (354469477)\n ,(354469536)\n ,(354469500)\n ,(987359)\n) DS (bold_id)\nLEFT JOIN TripEvent TE\n ON DS.[bold_id] = TE.[bold_id]\nWHERE TE.[bold_id] IS NULL;\n DS" }, { "answer_id": 74653937, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": false, "text": "EXCEPT SELECT bold_id FROM\n(\n SELECT 354469477 AS bold_id\n UNION ALL\n SELECT 354469536\n UNION ALL\n SELECT 354469500\n UNION ALL\n SELECT 987359\n) listofValues \nEXCEPT \nSELECT bold_id\nFROM TripEvent;\n SELECT bold_id FROM\n(\n VALUES (354469477),\n (354469536),\n (354469500),\n (987359)\n) listofValues(bold_id)\nEXCEPT \nSELECT bold_id\nFROM TripEvent;\n" }, { "answer_id": 74654185, "author": "Roland Bengtsson", "author_id": 55007, "author_profile": "https://Stackoverflow.com/users/55007", "pm_score": 0, "selected": false, "text": " SELECT *\n from (values (354469477),(354469536),(354469500),(987359)) as v(id)\n WHERE NOT EXISTS (SELECT BOLD_ID FROM TripEvent WHERE TripEvent.BOLD_ID = v.id)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20655704/" ]
74,653,773
<p>I noticed that my script was ignoring my positional arguments in old terminal tabs, but working on recently created ones, so I decided to reduce it to the following:</p> <pre><code>TAG=test while getopts 't:' c do case $c in t) TAG=$OPTARG ;; esac done echo $TAG </code></pre> <p>And running the script I have:</p> <pre><code>~ source my_script test ~ source my_script -t &quot;test2&quot; test2 ~ source my_script -t &quot;test2&quot; test </code></pre> <p>I thought it could be that <code>c</code> was an special used variable elsewhere but after changing it to other names I had the exact same problem. I also tried adding a <code>.sh</code> extension to the file to see it that was a problem, but nothing worked.</p> <p>Am I doing something wrong ? And why does it work the first time, but not the subsequent attempts ?</p> <p>I am on MacOS and I use zsh.</p> <p>Thank you very much.</p>
[ { "answer_id": 74653826, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 2, "selected": false, "text": "getopts getopts -t while getopts 't:' c\ndo\n case $c in\n t)\n TAG=$OPTARG\n ;;\n esac\ndone\n source source TAG TAG source . source . source . . my_script\n bash TAG bash bash my_script\n" }, { "answer_id": 74654883, "author": "Gordon Davisson", "author_id": 89817, "author_profile": "https://Stackoverflow.com/users/89817", "pm_score": 2, "selected": true, "text": "source . getopts OPTIND -t test2 getopts OPTIND OPTIND unset OPTIND while getopts #!/bin/bash #!/usr/bin/env bash #!/bin/zsh #!/usr/bin/env zsh chmod -x my_script ./my_script . / PATH my_script bash sh zsh PATH OPTIND tag TAG echo \"$tag\" echo $tag" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13342468/" ]
74,653,795
<p>There is a function as follows:</p> <pre><code>async function validate(value) { try { const result = await schema.validate(value, { abortEarly: false }); console.log(result); return result; } catch (error) { console.log(error.errors); setError({errors:error.errors}); console.log(setError.length); } } </code></pre> <p>In line number 8, the errors are updated in the state without any problem, but when I want to find the <code>length</code> of the state <code>setError</code> array, it returns the value of 1, even though the value of the created array is greater than 1. Is there a solution to find the state length in functional components in react?</p>
[ { "answer_id": 74653826, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 2, "selected": false, "text": "getopts getopts -t while getopts 't:' c\ndo\n case $c in\n t)\n TAG=$OPTARG\n ;;\n esac\ndone\n source source TAG TAG source . source . source . . my_script\n bash TAG bash bash my_script\n" }, { "answer_id": 74654883, "author": "Gordon Davisson", "author_id": 89817, "author_profile": "https://Stackoverflow.com/users/89817", "pm_score": 2, "selected": true, "text": "source . getopts OPTIND -t test2 getopts OPTIND OPTIND unset OPTIND while getopts #!/bin/bash #!/usr/bin/env bash #!/bin/zsh #!/usr/bin/env zsh chmod -x my_script ./my_script . / PATH my_script bash sh zsh PATH OPTIND tag TAG echo \"$tag\" echo $tag" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19200481/" ]
74,653,804
<p>I have a list of integer pairs</p> <pre><code>[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1)] </code></pre> <p>I want to take each element <code>(0,0)</code> then <code>(0,1)</code>, etc. pair, to XOR the two numbers between them and the result converted to binary.</p> <p>Example: the <code>(0,2)</code> pair</p> <p>0 decimal equals to 00110000 and 2 decimal equals to 00110010. The XOR of two will be 00000010.</p> <p>I tried this, but nothing</p> <pre><code>import functools test_list = [(0,0),(0,1),(0,2)] for i in enumerate(test_list): res = functools.reduce(lambda x, y: x ^ y, test_list) print(str(res)) </code></pre>
[ { "answer_id": 74653826, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 2, "selected": false, "text": "getopts getopts -t while getopts 't:' c\ndo\n case $c in\n t)\n TAG=$OPTARG\n ;;\n esac\ndone\n source source TAG TAG source . source . source . . my_script\n bash TAG bash bash my_script\n" }, { "answer_id": 74654883, "author": "Gordon Davisson", "author_id": 89817, "author_profile": "https://Stackoverflow.com/users/89817", "pm_score": 2, "selected": true, "text": "source . getopts OPTIND -t test2 getopts OPTIND OPTIND unset OPTIND while getopts #!/bin/bash #!/usr/bin/env bash #!/bin/zsh #!/usr/bin/env zsh chmod -x my_script ./my_script . / PATH my_script bash sh zsh PATH OPTIND tag TAG echo \"$tag\" echo $tag" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20594243/" ]
74,653,806
<p>I have an array of numbers with these values</p> <pre><code>const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500]; </code></pre> <p>How can I sum each of these consecutive values, while skipping the false values (NaN).</p> <p>Expected result:</p> <pre><code>const res = [6, 22, 27, 1500] </code></pre> <p>So far i tried implementing reduce() but probably in the wrong way, also regular for loops didn't get the expected results..</p>
[ { "answer_id": 74653874, "author": "Aschen", "author_id": 5422365, "author_profile": "https://Stackoverflow.com/users/5422365", "pm_score": -1, "selected": false, "text": "let arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\nlet sum = 0;\n\nfor (let i = 0; i < arr.length; i++) {\n if(arr[i]) sum += arr[i];\n}\n\nconsole.log(sum); // 1515\n" }, { "answer_id": 74653986, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 2, "selected": false, "text": "const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\nconst countValid = (arr) => {\n let total = 0;\n let result = []\n for (let i = 0; i < arr.length; i++)\n {\n if (arr[i]) total+=arr[i]\n else if (total !== 0) {\n result.push(total);\n total = 0;\n }\n }\n if (total !== 0)\n result.push(total)\n return result;\n}\nconsole.log(countValid(arr)) // prints expected output [6, 22, 27, 1500] \n" }, { "answer_id": 74654186, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "isNaN const arr = [NaN, 1, -1, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\n// ^^^^^^ added those in the example\nconst sums = arr.reduce((acc, val, i) => {\n if (!Number.isNaN(val)) {\n if (Number.isFinite(arr[i-1])) val += acc.pop();\n acc.push(val);\n }\n return acc;\n}, []);\n\nconsole.log(sums);" }, { "answer_id": 74654272, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 0, "selected": false, "text": "const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200,NaN,1,-1,NaN, 300, 400, 500];\n\nconst result = []\nlet sum=0;\narr.forEach((num,i)=>{\n\n if(isNaN(num)) {\n if(!isNaN(arr[i-1])){\n result.push(sum)\n sum=0;\n return;\n }\n return;\n }\nsum+=num;\nif(i===arr.length-1) result.push(sum)\n})\n\nconsole.log(result)" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9020506/" ]
74,653,849
<p>I'm trying to create a new <code>SCNScene</code> from 'diceCollada.scn' file. But this file won't be loaded. <a href="https://i.stack.imgur.com/vMg7N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMg7N.png" alt="enter image description here" /></a></p> <p>This file is in &quot;ARDicee/art.assets&quot; folder.</p> <p>Not only &quot;diceCollada.scn&quot;, but also it cannot load the default &quot;ship.scn&quot;. I don't know why it doesn't load files.</p> <hr /> <p>Here is my code.</p> <pre class="lang-swift prettyprint-override"><code> import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene. ---------- The error is here --------------- guard let diceScene = SCNScene(named: &quot;art.scnassets/diceCollada.scn&quot;) else { fatalError() } // Setting node if let diceNode = diceScene.rootNode.childNode(withName: &quot;Dice&quot;, recursively: true) { diceNode.position = SCNVector3(x: 0, y: 0, z: -0.1) sceneView.scene.rootNode.addChildNode(diceNode) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if ARWorldTrackingConfiguration.isSupported { // Create a session configuration let configuration = ARWorldTrackingConfiguration() // Run the view's session sceneView.session.run(configuration) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } } </code></pre> <hr /> <p>Xcode - Version 14.1</p> <p>macOS Ventura - Version 13.0.1</p> <p>GitHub - <a href="https://github.com/AdamYoneda/ARDicee" rel="nofollow noreferrer">This project</a></p> <hr /> <p>I also tried to create <code>SCNScene</code> another way.</p> <pre class="lang-swift prettyprint-override"><code>override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // --- Another way to create SCNScene --- let filePath = URL(fileURLWithPath: &quot;/Applications/xcode/Development/ARDicee/ARDicee/art.scnassets/diceCollada.scn&quot;) do { let diceScene = try SCNScene(url: filePath) if let diceNode = diceScene.rootNode.childNode(withName: &quot;Dice&quot;, recursively: true) { diceNode.position = SCNVector3(x: 0, y: 0, z: -0.1) sceneView.scene.rootNode.addChildNode(diceNode) } } catch { print(error) } } </code></pre> <p>But it gave this error.</p> <blockquote> <p>Error Domain=NSCocoaErrorDomain Code=260 &quot;The file “diceCollada.scn” couldn’t be opened because there is no such file.&quot; UserInfo={NSFilePath=/Applications/xcode/Development/ARDicee/ARDicee/art.scnassets/diceCollada.scn, NSUnderlyingError=0x282924570 {Error Domain=NSPOSIXErrorDomain Code=2 &quot;No such file or directory&quot;}}</p> </blockquote> <hr /> <p>I'm trying to create a new <code>SCNScene</code> from 'diceCollada.scn' file.</p>
[ { "answer_id": 74653874, "author": "Aschen", "author_id": 5422365, "author_profile": "https://Stackoverflow.com/users/5422365", "pm_score": -1, "selected": false, "text": "let arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\nlet sum = 0;\n\nfor (let i = 0; i < arr.length; i++) {\n if(arr[i]) sum += arr[i];\n}\n\nconsole.log(sum); // 1515\n" }, { "answer_id": 74653986, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 2, "selected": false, "text": "const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\nconst countValid = (arr) => {\n let total = 0;\n let result = []\n for (let i = 0; i < arr.length; i++)\n {\n if (arr[i]) total+=arr[i]\n else if (total !== 0) {\n result.push(total);\n total = 0;\n }\n }\n if (total !== 0)\n result.push(total)\n return result;\n}\nconsole.log(countValid(arr)) // prints expected output [6, 22, 27, 1500] \n" }, { "answer_id": 74654186, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "isNaN const arr = [NaN, 1, -1, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];\n// ^^^^^^ added those in the example\nconst sums = arr.reduce((acc, val, i) => {\n if (!Number.isNaN(val)) {\n if (Number.isFinite(arr[i-1])) val += acc.pop();\n acc.push(val);\n }\n return acc;\n}, []);\n\nconsole.log(sums);" }, { "answer_id": 74654272, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 0, "selected": false, "text": "const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200,NaN,1,-1,NaN, 300, 400, 500];\n\nconst result = []\nlet sum=0;\narr.forEach((num,i)=>{\n\n if(isNaN(num)) {\n if(!isNaN(arr[i-1])){\n result.push(sum)\n sum=0;\n return;\n }\n return;\n }\nsum+=num;\nif(i===arr.length-1) result.push(sum)\n})\n\nconsole.log(result)" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19362896/" ]
74,653,858
<p>I am trying to install <code>WSO2 APIM 4.1.0</code> in <code>Windows 11</code> Enterprise Edition.</p> <ul> <li>Downloaded zip Achieve from <a href="https://wso2.com/api-manager/#" rel="nofollow noreferrer">wso2 site</a></li> <li><code>JAVA_HOME</code> already set as <code>C:\Program Files\Java\jdk1.8.0_291</code></li> <li>Started WSO2 API-M by navigating to the <code>C:\Development_Avecto\WSO2APImServer\ORG\org_wso2am\wso2am-4.1.0\bin</code> and executed <code>api-manager.bat --run</code></li> </ul> <p>after executing above command below ERROR shown</p> <p><code>CARBON_HOME is set incorrectly or CARBON could not be located. Please set CARBON_HOME.</code></p> <p>ERROR: <a href="https://i.stack.imgur.com/8gDcJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8gDcJ.png" alt="ERROR_Details" /></a></p> <p>Even after setting up <code>CARBON_HOME</code> in Environment Variable value as <code>C:\Development_Avecto\WSO2APImServer\ORG\org_wso2am\wso2am-4.1.0</code> getting same ERROR.</p> <p>Already checked <a href="https://stackoverflow.com/questions/41369842/wso2-api-manager-error-could-not-find-or-load-main-class-enterprise">this related question</a></p> <p>Update: As per below suggestion, i have shorten directory of apim which is mentioned below and updated the same in Environment variable too.</p> <pre><code>C:\Development_Avecto\WSO2APIm\wso2apim-4.1.0\wso2am-4.1.0 </code></pre> <p>Any help to resolve this installation issue?</p>
[ { "answer_id": 74655242, "author": "Lakshitha", "author_id": 11414612, "author_profile": "https://Stackoverflow.com/users/11414612", "pm_score": 0, "selected": false, "text": "WSO2 API Manager v4.1.0" }, { "answer_id": 74655255, "author": "Justin", "author_id": 9907182, "author_profile": "https://Stackoverflow.com/users/9907182", "pm_score": 0, "selected": false, "text": "CARBON_HOME C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0\\bin C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0 C:\\Program Files\\Java\\jdk1.8.0_291" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9907182/" ]
74,653,859
<p>I need to find the X and Y position of a div within another div, and not relative to the viewport like getboundingclient() returns. Is there a way to do this?</p> <p><a href="https://i.stack.imgur.com/BR6YC.png" rel="nofollow noreferrer">Position Relative to the Parent Div</a></p>
[ { "answer_id": 74655242, "author": "Lakshitha", "author_id": 11414612, "author_profile": "https://Stackoverflow.com/users/11414612", "pm_score": 0, "selected": false, "text": "WSO2 API Manager v4.1.0" }, { "answer_id": 74655255, "author": "Justin", "author_id": 9907182, "author_profile": "https://Stackoverflow.com/users/9907182", "pm_score": 0, "selected": false, "text": "CARBON_HOME C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0\\bin C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0 C:\\Program Files\\Java\\jdk1.8.0_291" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20184841/" ]
74,653,863
<blockquote> <p>Hello, I want to pull the links from this page. All the knowledge in that field comes in according to my own methods. But I just need the links. How can I scrape links?(Pyhton-Beautifulsoup)</p> </blockquote> <pre><code>make_list = base_soup.findAll('div', {'a class': 'link--muted no--text--decoration result-item'}) one_make = make_list.findAll('href') print(one_make) </code></pre> <blockquote> <p>The structure to extract the data is as follows:</p> </blockquote> <pre><code>&lt;div class=&quot;cBox-body cBox-body--eyeCatcher&quot; data-testid=&quot;no-top&quot;&gt; == $0 &lt;a class=&quot;link--muted no--text--decoration result-item&quot; href=&quot;https://link structure&quot; </code></pre> <blockquote> <p>Every single link I want to collect is here.(link structure)</p> </blockquote> <blockquote> <p>I tried methods like.Thank you very much in advance for your help.</p> </blockquote>
[ { "answer_id": 74655242, "author": "Lakshitha", "author_id": 11414612, "author_profile": "https://Stackoverflow.com/users/11414612", "pm_score": 0, "selected": false, "text": "WSO2 API Manager v4.1.0" }, { "answer_id": 74655255, "author": "Justin", "author_id": 9907182, "author_profile": "https://Stackoverflow.com/users/9907182", "pm_score": 0, "selected": false, "text": "CARBON_HOME C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0\\bin C:\\Development_Avecto\\WSO2APIm\\wso2am-4.1.0 C:\\Program Files\\Java\\jdk1.8.0_291" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20173428/" ]
74,653,875
<p>I have the following table <code>INPUT</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>DATE</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <td>884</td> <td>2017-03-16 06:08:40</td> <td>B</td> </tr> <tr> <td>857</td> <td>2017-03-24 07:14:29</td> <td>A</td> </tr> <tr> <td>857</td> <td>2017-06-24 12:15:29</td> <td>A</td> </tr> <tr> <td>884</td> <td>2017-10-05 00:33:08</td> <td>A</td> </tr> <tr> <td>255</td> <td>2019-08-02 02:47:22</td> <td>B</td> </tr> </tbody> </table> </div> <p>And I need to keep the first event for each ID and its TYPE in a <code>OUTPUT</code> table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>DATE</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <td>884</td> <td>2017-03-16 06:08:40</td> <td>B</td> </tr> <tr> <td>857</td> <td>2017-03-24 07:14:29</td> <td>A</td> </tr> <tr> <td>255</td> <td>2019-08-02 02:47:22</td> <td>B</td> </tr> </tbody> </table> </div> <p>I have tried to use a group by construct :</p> <pre><code>create OUTPUT as select ID, min(DATE) as DATE, TYPE from INPUT group by ID </code></pre> <p>But I got: <code>not a group by expression</code> from the <code>TYPE</code> field.</p> <p>How to keep the good value for the <code>TYPE</code>field?</p>
[ { "answer_id": 74653909, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "TYPE FIRST_VALUE TYPE field ID FIRST_VALUE CREATE OUTPUT AS\nSELECT\n ID,\n MIN(DATE) AS DATE,\n FIRST_VALUE(TYPE) OVER (PARTITION BY ID ORDER BY DATE) AS TYPE\nFROM INPUT\nGROUP BY ID\n FIRST_VALUE OVER TYPE ID PARTITION BY ORDER BY OVER FIRST_VALUE TYPE ID" }, { "answer_id": 74654029, "author": "PeterClemmensen", "author_id": 4044936, "author_profile": "https://Stackoverflow.com/users/4044936", "pm_score": 2, "selected": true, "text": "drop table if exists #have;\n\ncreate table #have\n(\n ID [int]\n, date [datetime]\n, type [varchar](10)\n)\n;\n\ninsert into #have\nvalues\n (884, '2017-03-16 06:08:40', 'B')\n, (857, '2017-03-24 07:14:29', 'A')\n, (857, '2017-06-24 12:15:29', 'A')\n, (884, '2017-10-05 00:33:08', 'A')\n, (255, '2019-08-02 02:47:22', 'B')\n;\n\nselect * from #have;\n\nSELECT a.* \nFROM #have a inner join\n(\n SELECT id, MIN(date) AS date\n FROM #have\n GROUP BY id\n) b ON a.id = b.id and a.date = b.date\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6537892/" ]
74,653,884
<p>Is it possible to provide a default value to a Guid parameter in an ASP.Net core (.net 7) web api?</p> <p>Like this:</p> <pre><code>[HttpGet()] public async Task&lt;ActionResult&lt;Foo&gt;&gt; PostSomething(Guid tenantId = &quot;21c10283-6db0-489b-94d0-f0b3969fc799&quot;) // &lt;&lt;-- invalid of course </code></pre> <p>So far I'm using an optional parameter and assigning the default value in the method, but I'd like to expose it in the signature if possible.</p> <pre><code>public async Task&lt;ActionResult&lt;Foo&gt;&gt; PostSomething(Guid? tenantId) { tenantId ??= Guid.Parse(&quot;21c10283-6db0-489b-94d0-f0b3969fc799&quot;); </code></pre> <p>Note: Other answers show how to set an empty default value, but thats not what I need here.</p> <p>// Edit: If this is not possible at all, thats also an answer. But please read the question carefully before posting anything.</p>
[ { "answer_id": 74654218, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 0, "selected": false, "text": "// define your default or take it from somewhere\nstatic Guid defaultGuid = Guid.Parse(\"21c10283-6db0-489b-94d0-f0b3969fc799\");\n\n// use this function to get your guid\npublic static Guid GetGuidOrDefault(Guid? guid) => guid ?? defaultGuid;\n\npublic async Task<ActionResult<Foo>> PostSomething(Guid? tenantId) \n{\n // but it is extremely wrong to change the values of function parameters\n tenantId = GetGuidOrDefault(tenantId);\n" }, { "answer_id": 74655098, "author": "zaw", "author_id": 9990735, "author_profile": "https://Stackoverflow.com/users/9990735", "pm_score": 0, "selected": false, "text": "tenantId ??= default(Guid); string" }, { "answer_id": 74655344, "author": "Kirk Larkin", "author_id": 2630078, "author_profile": "https://Stackoverflow.com/users/2630078", "pm_score": 2, "selected": true, "text": "DefaultValueAttribute private const string defaultTenantId = \"21c10283-6db0-489b-94d0-f0b3969fc799\";\n\n[HttpGet]\npublic async Task<ActionResult<Foo>> PostSomething(\n [DefaultValue(typeof(Guid), defaultTenantId)] Guid? tenantId) \n{\n tenantId ??= Guid.Parse(defaultTenantId);\n\n // ...\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1537195/" ]
74,653,918
<p>I need to create a report that displays information about what part of the salary in percentage terms each employee receives within the department in which they work, using analytical functions.</p> <pre><code>SELECT EMPLOYEES.FIRST_NAME, EMPLOYEES.LAST_NAME, EMPLOYEES.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME, EMPLOYEES.SALARY, (SALARY/SUM(SALARY)) * 100 over (partition by DEPARTMENT_ID) AS &quot;PercentWithinDepartment&quot; FROM HR.EMPLOYEES FULL JOIN HR.DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID </code></pre> <p>I get an &quot;ORA-00923 FROM keyword not found where expected&quot; error but I think it's not my only mistake within this task.</p> <p>I cannot provide a code snippet of database but this can be run against the HR sample schema.</p> <p><img src="https://i.stack.imgur.com/Aj3k9.png" alt="enter image description here" /></p> <p>My request is to help me figure out mistake to complete this task properly.</p>
[ { "answer_id": 74654018, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "over (SALARY/SUM(SALARY)) * 100 over (partition by DEPARTMENT_ID)\n (SALARY/SUM(SALARY) over (partition by DEPARTMENT_ID)) * 100\n DEPARTMENT_ID (SALARY/SUM(EMPLOYEES.SALARY) over (partition by DEPARTMENTS.DEPARTMENT_ID)) * 100\n SALARY/SUM(EMPLOYEES.SALARY)*100\n over SALARY/SUM(EMPLOYEES.SALARY) over () * 100\n select employees.first_name,\n employees.last_name,\n employees.department_id, \n departments.department_name,\n employees.salary,\n salary / sum(employees.salary) over (partition by departments.department_id) * 100 as \"PercentWithinDepartment\",\n salary / sum(employees.salary) over () * 100 as \"PercentWithinOrganization\"\nfrom hr.employees\nleft join hr.departments on employees.department_id = departments.department_id;\n\nFIRST_NAME LAST_NAME DEPARTMENT_ID DEPARTMENT_NAME SALARY PercentWithinDepartment PercentWithinOrganization\n-------------------- ------------------------- ------------- ------------------------------ ---------- ----------------------- -------------------------\nJennifer Whalen 10 Administration 4400 100 .636389933\nMichael Hartstein 20 Marketing 13000 68.4210526 1.88024299\nPat Fay 20 Marketing 6000 31.5789474 .867804455\n...\nKimberely Grant 7000 100 1.01243853\n order by" }, { "answer_id": 74654035, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "SQL> set numformat 999g990d00\nSQL> break on deptno on dname\nSQL> compute sum of pct_sal on deptno\nSQL>\nSQL> select e.deptno, d.dname, e.ename, e.sal,\n 2 sum(e.sal) over (partition by e.deptno) dept_sal,\n 3 --\n 4 round((e.sal / sum(e.sal) over (partition by e.deptno)) * 100, 2) pct_sal\n 5 from emp e join dept d on d.deptno = e.deptno\n 6 order by e.deptno, e.ename;\n \n DEPTNO DNAME ENAME SAL DEPT_SAL PCT_SAL\n----------- -------------- ---------- ----------- ----------- -----------\n 10,00 ACCOUNTING CLARK 2.450,00 8.750,00 28,00\n KING 5.000,00 8.750,00 57,14\n MILLER 1.300,00 8.750,00 14,86\n*********** ************** -----------\nsum 100,00\n 20,00 RESEARCH ADAMS 1.100,00 10.915,00 10,08\n FORD 3.000,00 10.915,00 27,49\n JONES 2.975,00 10.915,00 27,26\n SCOTT 3.000,00 10.915,00 27,49\n SMITH 840,00 10.915,00 7,70\n*********** ************** -----------\nsum 100,02\n 30,00 SALES ALLEN 1.600,00 9.400,00 17,02\n BLAKE 2.850,00 9.400,00 30,32\n JAMES 950,00 9.400,00 10,11\n MARTIN 1.250,00 9.400,00 13,30\n TURNER 1.500,00 9.400,00 15,96\n WARD 1.250,00 9.400,00 13,30\n*********** ************** -----------\nsum 100,01\n\n14 rows selected.\n\nSQL>\n" }, { "answer_id": 74654606, "author": "ekochergin", "author_id": 6033601, "author_profile": "https://Stackoverflow.com/users/6033601", "pm_score": 1, "selected": false, "text": "SELECT E.FIRST_NAME, E.LAST_NAME, E.DEPARTMENT_ID, \n D.DEPARTMENT_NAME, E.SALARY,\n 100 * ratio_to_report(e.salary) over (partition by d.department_id)\n FROM HR.EMPLOYEES e\n JOIN hr.departments d \n on e.department_id = d.department_id\n order by d.department_id;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20617869/" ]
74,653,946
<p>I have a table for emails with &quot;primary&quot; radiobuttons column which means only one of them could have class .checked. How can I check this with Cypress?</p> <p>I tried this but it's not working for classes since it checks if all the elements in the column to have this class.</p> <p>P.S I'm using TypeScript and React. Each row is rendered separately</p> <pre><code> it(&quot;check if rest of the emails' primary setting are set to false&quot;, () =&gt; { cy.get('td:nth-child(2)') .should('not.have.class', 'checked') .should('have.length', 1); </code></pre>
[ { "answer_id": 74654003, "author": "Schiff", "author_id": 20664332, "author_profile": "https://Stackoverflow.com/users/20664332", "pm_score": 2, "selected": false, "text": "cy.get('td:nth-child(2):checked')\n .should('have.length', 1)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20665031/" ]
74,653,947
<p>Using Jest in bitbucket pipelines, it doesn't find the tests and hence failed with the following error :</p> <pre class="lang-bash prettyprint-override"><code>+ npx jest No tests found, exiting with code 1 Run with `--passWithNoTests` to exit with code 0 In /opt/atlassian/pipelines/agent/build 12 files checked. testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 2 matches testPathIgnorePatterns: /node_modules/, /build/ - 0 matches testRegex: - 0 matches Pattern: - 0 matches </code></pre> <p><strong>Locally my tests run fine.</strong></p> <p><strong>Project structure :</strong></p> <pre><code>. ├── build │ ├── coverage │ └── js └── src ├── account │ ├── account.ts │ └── account.test.ts ├── index.ts └── index.test.ts </code></pre> <p><strong>jest.config.js</strong></p> <pre class="lang-js prettyprint-override"><code>module.exports = { preset: 'ts-jest', testEnvironment: 'node', transform: { &quot;^.+\\.(t|j)sx?$&quot;: &quot;ts-jest&quot;, }, moduleFileExtensions: [&quot;ts&quot;, &quot;tsx&quot;, &quot;js&quot;, &quot;jsx&quot;, &quot;json&quot;, &quot;node&quot;], coverageDirectory: &quot;build/coverage&quot;, testPathIgnorePatterns: [&quot;/node_modules/&quot;, &quot;/build/&quot;], }; </code></pre> <p>Tests are launched using following npm script</p> <pre><code>&quot;test&quot;: &quot;jest --coverage&quot;, </code></pre> <p>Is it normal for Jest not to run the test it finds with <code>testMatch</code> ?</p> <ul> <li>Tried to switch from <code>testMatch</code> to <code>testRegex</code> without success</li> <li>Tried to add the path to src in the launch script (<code>npx jest ./src</code>)</li> </ul>
[ { "answer_id": 74654141, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 0, "selected": false, "text": "testPathIgnorePatterns jest.config.js testPathIgnorePatterns src testPathIgnorePatterns testPathIgnorePatterns src module.exports = {\n // ...\n testPathIgnorePatterns: [\"/node_modules/\", \"/build/\", \"/lib/\"],\n};\n src testMatch module.exports = {\n // ...\n testMatch: [\"**/__tests__/**/*.[jt]s?(x)\", \"**/?(*.)+(spec|test).[tj]s?(x)\"],\n};\n src" }, { "answer_id": 74655293, "author": "Wogle220", "author_id": 6181096, "author_profile": "https://Stackoverflow.com/users/6181096", "pm_score": 1, "selected": false, "text": "/opt/atlassian/pipelines/agent/build /opt/atlassian/pipelines/agent/build\n ├── build\n │ ├── coverage\n │ └── js\n └── src\n ├── account\n │ ├── account.ts\n │ └── account.test.ts\n ├── index.ts\n └── index.test.ts\n build testPathIgnorePatterns build testPathIgnorePatterns testRegex: \".*/src/.*\\\\.test\\\\.(t|j)sx?$\"" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6181096/" ]
74,653,972
<p>I have a function that splits a slice into three parts, a leading and trailing slice, and a reference to the middle element.</p> <pre><code>/// The leading and trailing parts of a slice. struct LeadingTrailing&lt;'a, T&gt;(&amp;'a mut [T], &amp;'a mut [T]); /// Divides one mutable slice into three parts, a leading and trailing slice, /// and a reference to the middle element. pub fn split_at_rest_mut&lt;T&gt;(x: &amp;mut [T], index: usize) -&gt; (&amp;mut T, LeadingTrailing&lt;T&gt;) { debug_assert!(index &lt; x.len()); let (leading, trailing) = x.split_at_mut(index); let (val, trailing) = trailing.split_first_mut().unwrap(); (val, LeadingTrailing(leading, trailing)) } </code></pre> <p>I would like to implement Iterator for <code>LeadingTrailing&lt;'a, T&gt;</code> so that it first iterates over the first slice, and then over the second. i.e., it will behave like:</p> <pre><code>let mut foo = [0,1,2,3,4,5]; let (item, lt) = split_at_rest_mut(&amp;foo, 2); for num in lt.0 { ... } for num in lt.1 { ... } </code></pre> <p>I have tried converting to a <code>Chain</code>:</p> <pre><code>struct LeadingTrailing&lt;'a, T&gt;(&amp;'a mut [T], &amp;'a mut [T]); impl &lt;'a, T&gt; LeadingTrailing&lt;'a, T&gt; { fn to_chain(&amp;mut self) -&gt; std::iter::Chain&lt;&amp;'a mut [T], &amp;'a mut [T]&gt; { self.0.iter_mut().chain(self.1.iter_mut()) } } </code></pre> <p>But I get the error:</p> <pre><code>89 | self.0.iter_mut().chain(self.1.iter_mut()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&amp;mut [T]`, found struct `std::slice::IterMut` </code></pre> <p>I have also tried creating a custom <code>Iterator</code></p> <pre><code>/// The leading and trailing parts of a slice. struct LeadingTrailing&lt;'a, T&gt;(&amp;'a mut [T], &amp;'a mut [T]); struct LTOthersIterator&lt;'a, T&gt; { data: LeadingTrailing&lt;'a, T&gt;, index: usize, } /// Iterates over the first slice, then the second slice. impl&lt;'a, T&gt; Iterator for LTOthersIterator&lt;'a, T&gt; { type Item = &amp;'a T; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let leading_len = self.data.0.len(); let trailing_len = self.data.1.len(); let total_len = leading_len + trailing_len; match self.index { 0..=leading_len =&gt; { self.index += 1; self.data.0.get(self.index - 1) } leading_len..=total_len =&gt; { self.index += 1; self.data.1.get(self.index - leading_len - 1) } } } } </code></pre> <p>But I get the error:</p> <pre><code>error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements --&gt; src\main.rs:104:29 | 104 | self.data.0.get(self.index - 1) ^^^ </code></pre> <p>What is the correct way to do this?</p>
[ { "answer_id": 74654118, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 2, "selected": false, "text": "to_chain() impl Iterator /// The leading and trailing parts of a slice.\n#[derive(Debug)]\npub struct LeadingTrailing<'a, T>(&'a mut [T], &'a mut [T]);\n\n/// Divides one mutable slice into three parts, a leading and trailing slice,\n/// and a reference to the middle element.\npub fn split_at_rest_mut<T>(x: &mut [T], index: usize) -> (&mut T, LeadingTrailing<T>) {\n debug_assert!(index < x.len());\n let (leading, trailing) = x.split_at_mut(index);\n let (val, trailing) = trailing.split_first_mut().unwrap();\n (val, LeadingTrailing(leading, trailing))\n}\n\nimpl<T> LeadingTrailing<'_, T> {\n fn to_chain(&mut self) -> impl Iterator<Item = &mut T> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n\nfn main() {\n let mut arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];\n let (x, mut leadtrail) = split_at_rest_mut(&mut arr, 5);\n\n println!(\"x: {}\", x);\n println!(\"leadtrail: {:?}\", leadtrail);\n\n for el in leadtrail.to_chain() {\n *el *= 2;\n }\n\n println!(\"leadtrail: {:?}\", leadtrail);\n}\n x: 5\nleadtrail: LeadingTrailing([0, 1, 2, 3, 4], [6, 7, 8])\nleadtrail: LeadingTrailing([0, 2, 4, 6, 8], [12, 14, 16])\n impl<T> LeadingTrailing<'_, T> {\n fn to_chain(&mut self) -> std::iter::Chain<std::slice::IterMut<T>, std::slice::IterMut<T>> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n" }, { "answer_id": 74654130, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": false, "text": "impl <'a, T> LeadingTrailing<'a, T> {\n fn to_chain(&mut self) -> impl Iterator<Item = &mut T> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n Chain impl <'a, T> LeadingTrailing<'a, T> {\n fn to_chain(&'a mut self) -> std::iter::Chain<std::slice::IterMut<'a, T>, std::slice::IterMut<'a, T>> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3052832/" ]
74,653,976
<p>I search that resize event detect when i resizing the windows, and i know the widht o window can i get it using <code>window.innerWidth</code> or <code>innerWidht</code></p> <pre><code>const swiperRooms = document.querySelector('#swiperRooms'); //this contain class mySwiper-rooms addEventListener(&quot;resize&quot;, (event) =&gt; { if(innerWidth &lt; 834) swiperRooms?.classList.toggle('mySwiper'); }); </code></pre> <p>I want to change the class of my swiper(slider) to other class that i have but i dont know why my code doesnt work. Its my first time doing resize</p>
[ { "answer_id": 74654118, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 2, "selected": false, "text": "to_chain() impl Iterator /// The leading and trailing parts of a slice.\n#[derive(Debug)]\npub struct LeadingTrailing<'a, T>(&'a mut [T], &'a mut [T]);\n\n/// Divides one mutable slice into three parts, a leading and trailing slice,\n/// and a reference to the middle element.\npub fn split_at_rest_mut<T>(x: &mut [T], index: usize) -> (&mut T, LeadingTrailing<T>) {\n debug_assert!(index < x.len());\n let (leading, trailing) = x.split_at_mut(index);\n let (val, trailing) = trailing.split_first_mut().unwrap();\n (val, LeadingTrailing(leading, trailing))\n}\n\nimpl<T> LeadingTrailing<'_, T> {\n fn to_chain(&mut self) -> impl Iterator<Item = &mut T> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n\nfn main() {\n let mut arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];\n let (x, mut leadtrail) = split_at_rest_mut(&mut arr, 5);\n\n println!(\"x: {}\", x);\n println!(\"leadtrail: {:?}\", leadtrail);\n\n for el in leadtrail.to_chain() {\n *el *= 2;\n }\n\n println!(\"leadtrail: {:?}\", leadtrail);\n}\n x: 5\nleadtrail: LeadingTrailing([0, 1, 2, 3, 4], [6, 7, 8])\nleadtrail: LeadingTrailing([0, 2, 4, 6, 8], [12, 14, 16])\n impl<T> LeadingTrailing<'_, T> {\n fn to_chain(&mut self) -> std::iter::Chain<std::slice::IterMut<T>, std::slice::IterMut<T>> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n" }, { "answer_id": 74654130, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": false, "text": "impl <'a, T> LeadingTrailing<'a, T> {\n fn to_chain(&mut self) -> impl Iterator<Item = &mut T> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n Chain impl <'a, T> LeadingTrailing<'a, T> {\n fn to_chain(&'a mut self) -> std::iter::Chain<std::slice::IterMut<'a, T>, std::slice::IterMut<'a, T>> {\n self.0.iter_mut().chain(self.1.iter_mut())\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15407192/" ]
74,653,996
<p>I need to transform dict { name : department } to { department : [ name ] } and print all names after transformation, but it prints me only one, what is wrong here?</p> <p><strong>I need to use dictionary comprehension method.</strong></p> <p>Tried this, but it doesn't work as expected:</p> <pre><code>orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': \ 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'} new_dict = {value: [key] for key, value in orig_dict.items()} it_names = new_dict['IT'] print(it_names) </code></pre>
[ { "answer_id": 74654177, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 1, "selected": false, "text": "orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\nnew_dict = {}\nfor k, v in orig_dict.items():\n new_dict.setdefault(v, []).append(k)\nprint(new_dict)\n {'HR': ['Tom', 'Margo'], 'IT': ['Ted', 'Jesica'], 'Marketing': ['Ken', 'Jason']}\n" }, { "answer_id": 74654226, "author": "louis joseph", "author_id": 20652486, "author_profile": "https://Stackoverflow.com/users/20652486", "pm_score": -1, "selected": false, "text": "old_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing',\n 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\n# Printing original dictionary\nprint(\"Original dictionary is : \")\nprint(old_dict)\n\nprint()\nnew_dict = {}\nfor key, value in old_dict.items():\n if value in new_dict:\n new_dict[value].append(key)\n else:\n new_dict[value] = [key]\n\n# Printing new dictionary after swapping\n# keys and values\nprint(\"Dictionary after swapping is : \")\nprint(\"keys: values\")\nfor i in new_dict:\n print(i, \" :\", new_dict[i])\n\nit_names = new_dict['IT'] \nprint(it_names)\n Original dictionary is : \n{'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'HR'} \n\nDictionary after swapping is :\nkeys: values\nHR : ['Tom', 'Margo']\nIT : ['Ted', 'Jesica']\nMarketing : ['Ken', 'Jason']\n['Ted', 'Jesica']\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20527602/" ]
74,653,998
<p>I have simple note app based on Django+Rest+React. It contains list of notes page (<code>NotesListPage.js</code>) and note pages (<code>NotePage.js</code>). List of notes page contains short previews, titles and links to note pages. The NotePage, in addition to the entire content, contains delete and update functionality. It works, but sometimes (~50%) to see updates on NotesListPage it needs hard refresh or step back to NotePage and come back to list of notes again.</p> <p>When I look at the sequence of execution of functions in the console, everything goes in the correct order. First, updating the note, then reloading the data.</p> <p>How can this be fixed?</p> <p><strong>NotesListPage.js</strong></p> <pre><code>import ListItem from '../components/ListItem' import AddButton from '../components/AddButton' const NotesListPage = () =&gt; { let [notes, setNotes] = useState([]) let getNotes = async () =&gt; { let response = await fetch('/api/notes/') let data = await response.json() console.log(data) setNotes(data) } useEffect(() =&gt; { getNotes().then(() =&gt; {console.log('NotesList useEffect getNote')}) }, []) return ( &lt;div className=&quot;notes&quot;&gt; &lt;div className=&quot;notes-list&quot;&gt; {notes.map((note, index) =&gt; ( &lt;ListItem key={index} note={note} /&gt; ))} &lt;/div&gt; &lt;AddButton /&gt; &lt;/div&gt; ) } export default NotesListPage </code></pre> <p><strong>NotePage.js</strong></p> <pre><code>import { ReactComponent as ArrowLeft } from '../assets/arrow-left.svg' const NotePage = ({ match, history }) =&gt; { let noteId = match.params.id let [note, setNote] = useState(null) let getNote = async () =&gt; { if (noteId === 'new') return let response = await fetch(`/api/notes/${noteId}/`) let data = await response.json() setNote(data) } useEffect(() =&gt; { getNote().then(() =&gt; {console.log('NotePage useEffect getNote')}) }, [noteId]) let createNote = async () =&gt; { await fetch(`/api/notes/`, { method: &quot;POST&quot;, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(note) }) } let updateNote = async () =&gt; { await fetch(`/api/notes/${noteId}/`, { method: &quot;PUT&quot;, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(note) }) } let deleteNote = async () =&gt; { await fetch(`/api/notes/${noteId}/`, { method: 'DELETE', 'headers': { 'Content-Type': 'application/json' } }) history.push('/') } let handleSubmit = () =&gt; { console.log('NOTE:', note) if (noteId !== 'new' &amp;&amp; note.body === '') { deleteNote().then(() =&gt; {console.log('deleteNote')}) } else if (noteId !== 'new') { updateNote().then(() =&gt; {console.log('updateNote')}) } else if (noteId === 'new' &amp;&amp; note.body !== null) { createNote().then(() =&gt; {console.log('createNote')}) } history.push('/') } let handleChange = (value) =&gt; { setNote(note =&gt; ({ ...note, 'body': value })) console.log('Handle Change:', note) } return ( &lt;div className=&quot;note&quot; &gt; &lt;div className=&quot;note-header&quot;&gt; &lt;h3&gt; &lt;ArrowLeft onClick={handleSubmit} /&gt; &lt;/h3&gt; {noteId !== 'new' ? ( &lt;button onClick={deleteNote}&gt;Delete&lt;/button&gt; ) : ( &lt;button onClick={handleSubmit}&gt;Done&lt;/button&gt; )} &lt;/div&gt; &lt;textarea onChange={(e) =&gt; { handleChange(e.target.value) }} value={note?.body}&gt;&lt;/textarea&gt; &lt;/div&gt; ) } export default NotePage </code></pre> <p><strong>ListItem.js</strong></p> <pre><code>import React from 'react' import { Link } from 'react-router-dom' let getTime = (note) =&gt; { return new Date(note.updated).toLocaleDateString() } let getTitle = (note) =&gt; { let title = note.body.split('\n')[0] if (title.length &gt; 45) { return title.slice(0, 45) } return title } let getContent = (note) =&gt; { let title = getTitle(note) let content = note.body.replaceAll('\n', ' ') content = content.replaceAll(title, '') if (content.length &gt; 45) { return content.slice(0, 45) + '...' } else { return content } } const ListItem = ({ note }) =&gt; { return ( &lt;Link to={`/note/${note.id}`}&gt; &lt;div className=&quot;notes-list-item&quot; &gt; &lt;h3&gt;{getTitle(note)}&lt;/h3&gt; &lt;p&gt;&lt;span&gt;{getTime(note)}&lt;/span&gt;{getContent(note)}&lt;/p&gt; &lt;/div&gt; &lt;/Link&gt; ) } export default ListItem </code></pre> <p><strong>App.js</strong></p> <pre><code>import { BrowserRouter as Router, Route } from &quot;react-router-dom&quot;; import './App.css'; import Header from './components/Header' import NotesListPage from './pages/NotesListPage' import NotePage from './pages/NotePage' function App() { return ( &lt;Router&gt; &lt;div className=&quot;container dark&quot;&gt; &lt;div className=&quot;app&quot;&gt; &lt;Header title=&quot;Note List&quot; /&gt; &lt;Route path=&quot;/&quot; exact component={NotesListPage} /&gt; &lt;Route path=&quot;/note/:id&quot; component={NotePage} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Router&gt; ); } export default App; </code></pre>
[ { "answer_id": 74654177, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 1, "selected": false, "text": "orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\nnew_dict = {}\nfor k, v in orig_dict.items():\n new_dict.setdefault(v, []).append(k)\nprint(new_dict)\n {'HR': ['Tom', 'Margo'], 'IT': ['Ted', 'Jesica'], 'Marketing': ['Ken', 'Jason']}\n" }, { "answer_id": 74654226, "author": "louis joseph", "author_id": 20652486, "author_profile": "https://Stackoverflow.com/users/20652486", "pm_score": -1, "selected": false, "text": "old_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing',\n 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}\n# Printing original dictionary\nprint(\"Original dictionary is : \")\nprint(old_dict)\n\nprint()\nnew_dict = {}\nfor key, value in old_dict.items():\n if value in new_dict:\n new_dict[value].append(key)\n else:\n new_dict[value] = [key]\n\n# Printing new dictionary after swapping\n# keys and values\nprint(\"Dictionary after swapping is : \")\nprint(\"keys: values\")\nfor i in new_dict:\n print(i, \" :\", new_dict[i])\n\nit_names = new_dict['IT'] \nprint(it_names)\n Original dictionary is : \n{'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'HR'} \n\nDictionary after swapping is :\nkeys: values\nHR : ['Tom', 'Margo']\nIT : ['Ted', 'Jesica']\nMarketing : ['Ken', 'Jason']\n['Ted', 'Jesica']\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74653998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975285/" ]
74,654,015
<p>I have an array of products that looks like this <a href="https://i.stack.imgur.com/Q0H9F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q0H9F.png" alt="enter image description here" /></a> I am trying to filter out products with a specific category,</p> <pre><code> const filteredTrendingProducts = products.filter( (item) =&gt; item.data.category === &quot;Kids&quot; ); setTrendingProducts(filteredTrendingProducts); </code></pre> <p>this returns and empty object yet I can clearly see in the array there is a data key and in data there is category.Why is the object returning empty?</p>
[ { "answer_id": 74654048, "author": "Greg", "author_id": 1661367, "author_profile": "https://Stackoverflow.com/users/1661367", "pm_score": -1, "selected": false, "text": "const filteredTrendingProducts = products.filter(\n (item) => return item.data.category === \"Kids\"\n);\nsetTrendingProducts(filteredTrendingProducts);\n" }, { "answer_id": 74654116, "author": "Srushti Shah", "author_id": 17786978, "author_profile": "https://Stackoverflow.com/users/17786978", "pm_score": 0, "selected": false, "text": "const filteredTrendingProducts = products.filter(\n (item) => {\n console.log(\"item.data\", item.data);\n console.log(\"item.data.category\", item.data.category);\n console.log(item.data.category === \"Kids\", item.data.category == \"Kids\");\n return item.data.category === \"Kids\"\n }\n );\n" }, { "answer_id": 74654161, "author": "Ajay Thakur", "author_id": 11013282, "author_profile": "https://Stackoverflow.com/users/11013282", "pm_score": 0, "selected": false, "text": " const filteredTrendingProducts = products.length === 0\n ? []\n : products.filter((item) => item.data.category === \"Kids\");\n\nsetTrendingProducts(filteredTrendingProducts);\n const filteredTrendingProduct = products.find((item) => item.data.category === \"Kids\");\n\nif (filteredTrendingProduct) {\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13541483/" ]
74,654,034
<p>I used the enrich mediator to add a payload containing the name and totalnote of students my problem that i want to replace the values ​​with the property</p> <p>here is my code</p> <pre><code> &lt;property expression=&quot;get-property('uri.var.nom')&quot; name=&quot;uri.var.nom&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;property expression=&quot;get-property('totalnote')&quot; name=&quot;totalnote&quot; scope=&quot;default&quot; type=&quot;STRING&quot;/&gt; &lt;enrich&gt; &lt;source clone=&quot;true&quot; type=&quot;inline&quot;&gt; {&quot;nom&quot;:&quot;&quot; , &quot;note&quot;:&quot;&quot;} &lt;/source&gt; &lt;target action=&quot;child&quot; xpath=&quot;json-eval($)&quot;/&gt; &lt;/enrich&gt; &lt;enrich&gt; &lt;source clone=&quot;true&quot; property=&quot;uri.var.nom&quot; type=&quot;property&quot;/&gt; &lt;target action=&quot;replace&quot; xpath=&quot;json-eval($.etudiants.nom)&quot;/&gt; &lt;/enrich&gt; &lt;enrich&gt; &lt;source clone=&quot;true&quot; property=&quot;totalnote&quot; type=&quot;property&quot;/&gt; &lt;target action=&quot;replace&quot; xpath=&quot;json-eval($.etudiants.note)&quot;/&gt; &lt;/enrich&gt; &lt;respond/&gt; </code></pre> <p>it doesn't work I always receive empty</p> <p><code>{ &quot;etudiants&quot;: { &quot;nom&quot;: &quot;&quot;, &quot;note&quot;: &quot;&quot; }</code></p>
[ { "answer_id": 74655887, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 0, "selected": false, "text": "{ \"etudiants\": { \"nom\": \"\", \"note\": \"\" }} <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<api context=\"/HelloWorld\" name=\"HelloWorld\" xmlns=\"http://ws.apache.org/ns/synapse\">\n <resource methods=\"POST\">\n <inSequence>\n <property name=\"uri.var.nom\" scope=\"default\" type=\"STRING\" value=\"nomVal\"/>\n <property name=\"totalnote\" scope=\"default\" type=\"STRING\" value=\"20\"/>\n <enrich>\n <source clone=\"true\" property=\"uri.var.nom\" type=\"property\"/>\n <target xpath=\"json-eval($.etudiants.nom)\"/>\n </enrich>\n <enrich>\n <source clone=\"true\" property=\"totalnote\" type=\"property\"/>\n <target xpath=\"json-eval($.etudiants.note)\"/>\n </enrich>\n <respond/>\n </inSequence>\n <outSequence/>\n <faultSequence/>\n </resource>\n</api>\n curl --location --request POST 'http://localhost:8290/HelloWorld' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n \"etudiants\": {\n \"nom\": \"\",\n \"note\": \"\"\n }\n}'\n {\n \"etudiants\": {\n \"nom\": \"nomVal\",\n \"note\": 20\n }\n}\n" }, { "answer_id": 74656576, "author": "ophychius", "author_id": 677983, "author_profile": "https://Stackoverflow.com/users/677983", "pm_score": 3, "selected": true, "text": "<enrich>\n <source clone=\"true\" type=\"inline\">\n {\"etudiants\": {\n \"nom\":\"\" ,\n \"note\":\"\"\n }\n </source>\n <target action=\"replace\" type=\"body\"/>\n </enrich>\n <enrich>\n <source clone=\"true\" type=\"inline\">\n {\"nom\":\"\" ,\n \"note\":\"\"}\n </source>\n <target action=\"child\" xpath=\"json-eval($.etudiants)\"/>\n </enrich>\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442057/" ]
74,654,037
<p>I´m still learning to code, and I'm making a new project with MDI forms (C# and Visual Studio 2019). In mdichild, I launched a task, but if the form is unloaded, the task still remains. I would like to know how cancel the task, even on a cancel button click.</p> <p>The code:</p> <pre><code>private async void BuscaActualizaciones() { await Task.Run(() =&gt; DoLongThing()); } private void DoLongThing() { //some hard stuff } private void BtnBuscar_Click(object sender, EventArgs e) { //In here i launch the task with hard stuff BuscaActualizaciones(); } </code></pre> <p>This code works perfectly, but I need to cancel in some events, and I don't know how.</p> <p>I tried some home-made tricks, and read on Google about task cancellation, but all of them used <code>Task</code> in other way that I don't understand. I'm still learning, and it is my first time with tasks.</p>
[ { "answer_id": 74654112, "author": "ˈvɔlə", "author_id": 1865613, "author_profile": "https://Stackoverflow.com/users/1865613", "pm_score": 2, "selected": false, "text": "CancellationTokenSource cts = new();\n\nprivate async Task BuscaActualizaciones()\n{\n await Task.Run(DoLongThing, cts.Token); \n}\n\nprivate Task DoLongThing() // <-- needs to return a Task\n{\n //some hard stuff\n cts.Token.ThrowIfCancellationRequested();\n //some hard stuff\n}\n\nprivate void CancelButton_Click(object sender, EventArgs e)\n{\n cts.Cancel(); // <-- here is the cancallation\n}\n" }, { "answer_id": 74654544, "author": "Dav3", "author_id": 2429551, "author_profile": "https://Stackoverflow.com/users/2429551", "pm_score": -1, "selected": false, "text": "CancellationTokenSource cts = new CancellationTokenSource ();\n\nprivate async void BuscaActualizaciones()\n{\n await Task.Run(() => DoLongThing(), cts.Token); \n}\n\nprivate Void DoLongThing() \n{\n //some hard stuff\n\n if (cts.IsCancellationRequested)\n {\n throw new TaskCanceledException();\n }\n}\n\nprivate void CancelButton_Click(object sender, EventArgs e)\n{\n cts.Cancel(); // <-- here is the cancellation\n}\n" }, { "answer_id": 74655959, "author": "Stephen Cleary", "author_id": 263693, "author_profile": "https://Stackoverflow.com/users/263693", "pm_score": 3, "selected": true, "text": "CancellationToken Task.Run DoLongThing CancellationTokenSource cts = new ();\n\nprivate async void BuscaActualizaciones()\n{\n await Task.Run(() => DoLongThing(cts.Token)); \n}\n\nprivate void DoLongThing(CancellationToken token)\n{\n ...\n token.ThrowIfCancellationRequested();\n}\n\nprivate void CancelButton_Click(object sender, EventArgs e)\n{\n cts.Cancel();\n}\n ThrowIfCancellationRequested" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429551/" ]
74,654,080
<p>I'm having problem translating my JavaScript snippet to Python.</p> <p>The JavaScript code looks like this:</p> <pre class="lang-js prettyprint-override"><code>const reviver = (_key, value) =&gt; { try { return JSON.parse(value, reviver); } catch { if(typeof value === 'string') { const semiValues = value.split(';'); if(semiValues.length &gt; 1) { return stringToObject(JSON.stringify(semiValues)); } const commaValues = value.split(','); if(commaValues.length &gt; 1) { return stringToObject(JSON.stringify(commaValues)); } } const int = Number(value); if(value.length &amp;&amp; !isNaN(int)) { return int; } return value; } }; const stringToObject = (str) =&gt; { const formatted = str.replace(/&quot;{/g, '{').replace(/}&quot;/g, '}').replace(/&quot;\[/g, '[').replace(/\]&quot;/g, ']').replace(/\\&quot;/g, '&quot;'); return JSON.parse(formatted, reviver); }; </code></pre> <p>The goal of the function is that:</p> <ul> <li>String values that are numbers are parsed</li> <li>String values that are json are parsed using these rules</li> <li>String values like <code>&quot;499,504;554,634&quot;</code> should be parsed to <code>[(499, 504), (554, 634)]</code></li> </ul> <p>I have tried using the <a href="https://docs.python.org/3/library/json.html#encoders-and-decoders" rel="nofollow noreferrer">JSONDecoder</a>.</p> <pre class="lang-py prettyprint-override"><code>import json def object_hook(value): try: return json.loads(value) except: if(isinstance(value, str)): semiValues = value.split(';') if(len(semiValues) &gt; 1): return parse_response(json.dumps(semiValues)) commaValues = value.split(',') if(commaValues.length &gt; 1): return parse_response(json.dumps(commaValues)) try: return float(value) except ValueError: return value def parse_response(data: str): formatted = data.replace(&quot;\&quot;{&quot;, &quot;{&quot;).replace(&quot;}\&quot;&quot;, '}').replace(&quot;\&quot;[&quot;, '[').replace(&quot;]\&quot;&quot;, ']').replace(&quot;\\\&quot;&quot;, &quot;\&quot;&quot;) return json.load(formatted, object_hook=object_hook) </code></pre>
[ { "answer_id": 74654164, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "def reviver(_key, value):\n try:\n return json.loads(value, object_hook=reviver)\n except:\n if type(value) == str:\n semi_values = value.split(';')\n if len(semi_values) > 1:\n return string_to_object(json.dumps(semi_values))\n comma_values = value.split(',')\n if len(comma_values) > 1:\n return string_to_object(json.dumps(comma_values))\n int_val = int(value)\n if len(value) and not isinstance(int_val, int):\n return int_val\n return value\n\ndef string_to_object(str):\n formatted = str.replace('\"{', '{').replace('}\"', '}').replace('\"[', '[').replace(']\"', ']').replace('\\\\\"', '\"')\n return json.loads(formatted, object_hook=reviver)\n" }, { "answer_id": 74665572, "author": "Albin Médoc", "author_id": 10664990, "author_profile": "https://Stackoverflow.com/users/10664990", "pm_score": 0, "selected": false, "text": "import json\n\ndef parse_value(value):\n if(isinstance(value, str)):\n try:\n return parse_value(json.loads(value))\n except:\n pass\n semi_values = value.split(';')\n if(len(semi_values) > 1):\n return list(map(parse_value, semi_values))\n comma_values = value.split(',')\n if(len(comma_values) > 1):\n return list(map(parse_value, comma_values))\n if(value.replace('.','',1).isdigit()):\n return int(value)\n if(isinstance(value, dict)):\n return {k: parse_value(v) for k, v in value.items()}\n if(isinstance(value, list)):\n return list(map(parse_value, value))\n return value\n" }, { "answer_id": 74665601, "author": "sametcodes", "author_id": 8574166, "author_profile": "https://Stackoverflow.com/users/8574166", "pm_score": 0, "selected": false, "text": "commaValues len(commaValues) commaValues 1 json.load() json.loads() import json\n\ndef reviver(key, value):\n try:\n return json.loads(value, reviver=reviver)\n except:\n if isinstance(value, str):\n semiValues = value.split(';')\n if len(semiValues) > 1:\n return stringToObject(json.dumps(semiValues))\n commaValues = value.split(',')\n if len(commaValues) > 1:\n return stringToObject(json.dumps(commaValues))\n\n try:\n return int(value)\n except ValueError:\n return value\n\ndef stringToObject(str):\n formatted = str.replace('\"{', '{').replace('}\"', '}').replace('\"[', '[').replace(']\"', ']').replace('\\\\\"', '\"')\n return json.loads(formatted, reviver=reviver)\n int() float() string_to_object stringToObject" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10664990/" ]
74,654,082
<p>I want to extract the IP address from the input string</p> <pre><code>[IP-Address]: [ipv4]: [10.124.25.210] </code></pre> <p>using <code>Pattern</code> matching in Java. There are 2 whitespaces after <code>:</code>.</p> <p>What would be the regex for the same?</p> <p>The pattern that I tried with was:</p> <pre><code>Pattern p2 = Pattern.compile(&quot;\\[.*\\]\\: \\[.*\\]\\: \\[(.*?)\\]&quot;); </code></pre> <p>But obviously it didn't work, as I am new to regex.</p>
[ { "answer_id": 74654143, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "String input = \"[IP-Address]: [ipv4]: [10.124.25.210]\";\nString ip = input.replaceAll(\".*\\\\[|\\\\]\", \"\");\nSystem.out.println(ip); // 10.124.25.210\n String input = \"[IP-Address]: [ipv4]: [10.124.25.210]\";\nString ip = input.replaceAll(\".*\\\\[(\\\\d+(?:\\\\.\\\\d+){3})\\\\].*\", \"$1\");\nSystem.out.println(ip); // 10.124.25.210\n" }, { "answer_id": 74654156, "author": "dobby", "author_id": 948979, "author_profile": "https://Stackoverflow.com/users/948979", "pm_score": 0, "selected": false, "text": "\\[IP-Address\\]\\: \\s\\[ipv4\\]\\: \\s\\[(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\]\n // Compile the regex pattern\nPattern p2 = Pattern.compile(\"\\\\[IP-Address\\\\]: \\\\s\\\\[ipv4\\\\]: \\\\s\\\\[(\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3})\\\\]\");\n\n// Create a Matcher object for the input string\nMatcher m2 = p2.matcher(\"[IP-Address]: [ipv4]: [10.124.25.210]\");\n\n// Check if the input string matches the regex pattern\nif (m2.matches()) {\n // Print the captured IP address\n System.out.println(\"IP address: \" + m2.group(1));\n}\n IP address: 10.124.25.210\n" }, { "answer_id": 74654398, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 0, "selected": false, "text": "(?:\\d{1,3}\\.){3}\\d{1,3} (?: \\d{1,3}\\. ) {3} \\d{1,3} public class Main {\n public static void main(String[] args) {\n String text = \"[IP-Address]: [ipv4]: [10.124.25.210]\";\n Matcher matcher = Pattern.compile(\"(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}\").matcher(text);\n if (matcher.find())\n System.out.println(matcher.group());\n }\n}\n 10.124.25.210\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13823913/" ]
74,654,097
<p>I am trying to access members of an existing Mailman 3 mailing list directly from <a href="https://docs.mailman3.org/en/latest/django-primer.html#management-commands" rel="nofollow noreferrer">Django Management console</a> on a Debian Bullseye where Mailman is installed from deb packages (<code>mailman3-full</code>). I can connect to the Django admin console like this (all 3 variants seem to work fine):</p> <pre class="lang-bash prettyprint-override"><code>$ /usr/share/mailman3-web/manage.py shell $ mailman-web shell $ mailman-web shell --settings /etc/mailman3/mailman-web.py Python 3.9.2 (default, Feb 28 2021, 17:03:44) &gt;&gt;&gt; </code></pre> <p>But inside the Django admin console, some mailman components seem to be missing.</p> <p>I try to access the list manager as described here: <a href="https://docs.mailman3.org/projects/mailman/en/latest/src/mailman/model/docs/listmanager.html" rel="nofollow noreferrer">Docs &gt; Models &gt; The mailing list manager</a>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from mailman.interfaces.listmanager import IListManager &gt;&gt;&gt; from zope.component import getUtility &gt;&gt;&gt; list_manager = getUtility(IListManager) Traceback (most recent call last): File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt; File &quot;/usr/lib/python3/dist-packages/zope/component/_api.py&quot;, line 169, in getUtility raise ComponentLookupError(interface, name) zope.interface.interfaces.ComponentLookupError: (&lt;InterfaceClass mailman.interfaces.listmanager.IListManager&gt;, '') </code></pre> <p>Can't figure out why this <code>ComponentLookupError</code> happens.</p> <p>Also tried to acccess a list with the <code>ListManager</code> implementation:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from mailman.config import config &gt;&gt;&gt; from mailman.model.listmanager import ListManager &gt;&gt;&gt; list_manager = ListManager() &gt;&gt;&gt; list_manager.get('mynews@example.com') Traceback (most recent call last): File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt; File &quot;/usr/lib/python3/dist-packages/mailman/database/transaction.py&quot;, line 85, in wrapper return function(args[0], config.db.store, *args[1:], **kws) AttributeError: 'NoneType' object has no attribute 'store' &gt;&gt;&gt; list_manager.get_by_list_id('mynews.example.com') Traceback (most recent call last): File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt; File &quot;/usr/lib/python3/dist-packages/mailman/database/transaction.py&quot;, line 85, in wrapper return function(args[0], config.db.store, *args[1:], **kws) AttributeError: 'NoneType' object has no attribute 'store' </code></pre> <p>What am I doing wrong here? None of the examples in the Mailman 3 models documentation is working if I don't even get that far.</p> <p>any help greatly appreciated!</p>
[ { "answer_id": 74655150, "author": "Mailman3.com", "author_id": 1934852, "author_profile": "https://Stackoverflow.com/users/1934852", "pm_score": 1, "selected": false, "text": "mailman shell" }, { "answer_id": 74661749, "author": "Philip Iezzi", "author_id": 5982842, "author_profile": "https://Stackoverflow.com/users/5982842", "pm_score": 0, "selected": false, "text": "mailman shell from mailman.interfaces.listmanager import IListManager\nfrom zope.component import getUtility\nfrom mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef dump_members(roster):\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n\nlist_manager = getUtility(IListManager)\nmlist = list_manager.get('ant@example.com')\ndump_members(mlist.members.members)\n mailman withlist -r listmembers -l ant@example.com from mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef listmembers(mlist):\n roster = mlist.members.members\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n listmembers.py /usr/lib/python3/dist-packages/mailman/runners $ mailman withlist -r listmembers -l ant@example.com\nModuleNotFoundError: No module named 'listmembers'\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5982842/" ]
74,654,127
<p>This is my mysql-deployment.yaml I am trying to get this to run on kubernetes but I am getting error I have mentioned the errors below my deployment.yml</p> <pre><code>apiVersion: v1 kind: Service metadata: name: mysql labels: app: mysql tier: database spec: ports: - port: 3306 targetPort: 3306 selector: app: mysql tier: database clusterIP: None --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim labels: app: mysql tier: database spec: accessMode: - ReadWriteOnce resources: requests: storage: 1Gi --- apiVersion: apps/v1 kind: Deployment metadata: name: mysql labels: app: mysql tier: database spec: selector: matchLabels: app: mysql tier: database strategy: type: Recreate template: metadata: labels: apps: mysql tier: database spec: containers: - image: mysql:5.7 name: mysql env: - name: MYSQL_ROOT_PASSWORD valueFrom: secretKeyRef: name: db-root-credentials key: password - name: MYSQL_USER valueFrom: secretKeyRef:: name: db-credentials key: username - name: MYSQL_PASSWORD valueFrom: secretkeyRef: name: db-credentials key: password - name: MYSQL_DATABASE valueFrom: configMapKeyRef: name: dbbuddyto_mstr_local key: name ports: - containerPort: 3306 name: mysql volumeMounts: - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage PersistentVolumeClaim: claimName: mysql-pv-claim </code></pre> <p>I am getting two errors: <code>error parsing mysql-deployment.yml: error converting YAML to JSON: yaml: line 24: mapping values are not allowed in this context</code></p> <p>and the second error is</p> <p><code>Error from server (BadRequest): error when creating &quot;mysql-deployment.yml&quot;: PersistentVolumeClaim in version &quot;v1&quot; cannot be handled as a PersistentVolumeClaim: strict decoding error: unknown field &quot;spec.accessMode&quot;</code></p> <p>I am trying to build a Kubernetes deployment for angular, spring and mysql. and the mentioned errors are the ones I am currently facing.</p>
[ { "answer_id": 74655150, "author": "Mailman3.com", "author_id": 1934852, "author_profile": "https://Stackoverflow.com/users/1934852", "pm_score": 1, "selected": false, "text": "mailman shell" }, { "answer_id": 74661749, "author": "Philip Iezzi", "author_id": 5982842, "author_profile": "https://Stackoverflow.com/users/5982842", "pm_score": 0, "selected": false, "text": "mailman shell from mailman.interfaces.listmanager import IListManager\nfrom zope.component import getUtility\nfrom mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef dump_members(roster):\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n\nlist_manager = getUtility(IListManager)\nmlist = list_manager.get('ant@example.com')\ndump_members(mlist.members.members)\n mailman withlist -r listmembers -l ant@example.com from mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef listmembers(mlist):\n roster = mlist.members.members\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n listmembers.py /usr/lib/python3/dist-packages/mailman/runners $ mailman withlist -r listmembers -l ant@example.com\nModuleNotFoundError: No module named 'listmembers'\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641267/" ]
74,654,145
<p>I am trying to find a way to compute values that are of type <code>uint1024_t</code> (unsigned 1024-bit integer), by defining the 5 basic operations: plus, minus, times, divide, modulus.</p> <p>The way that I can do that is by creating a structure that will have the following prototype:</p> <pre><code>typedef struct { uint64_t chunk[16]; } uint1024_t; </code></pre> <p>Now since it is complicated to wrap my head around such operations with <code>uint64_t</code> as block size, I have first written some code for manipulating <code>uint8_t</code>. Here is what I came up with:</p> <pre><code>#define UINT8_HI(x) (x &gt;&gt; 4) #define UINT8_LO(x) (((1 &lt;&lt; 4) - 1) &amp; x) void uint8_add(uint8_t a, uint8_t b, uint8_t *res, int i) { uint8_t s0, s1, s2; uint8_t x = UINT8_LO(a) + UINT8_LO(b); s0 = UINT8_LO(x); x = UINT8_HI(a) + UINT8_HI(b) + UINT8_HI(x); s1 = UINT8_LO(x); s2 = UINT8_HI(x); uint8_t result = s0 + (s1 &lt;&lt; 4); uint8_t carry = s2; res[1 + i] = result; res[0 + i] = carry; } void uint8_multiply(uint8_t a, uint8_t b, uint8_t *res, int i) { uint8_t s0, s1, s2, s3; uint8_t x = UINT8_LO(a) * UINT8_LO(b); s0 = UINT8_LO(x); x = UINT8_HI(a) * UINT8_LO(b) + UINT8_HI(x); s1 = UINT8_LO(x); s2 = UINT8_HI(x); x = s1 + UINT8_LO(a) * UINT8_HI(b); s1 = UINT8_LO(x); x = s2 + UINT8_HI(a) * UINT8_HI(b) + UINT8_HI(x); s2 = UINT8_LO(x); s3 = UINT8_HI(x); uint8_t result = s1 &lt;&lt; 4 | s0; uint8_t carry = s3 &lt;&lt; 4 | s2; res[1 + i] = result; res[0 + i] = carry; } </code></pre> <p>And it seems to work just fine, however I am unable to define the same operations for division, subtraction and modulus...</p> <p>Furthermore I just can't seem to see how to implement the same principal to my custom <code>uint1024_t</code> structure even though it is pretty much identical with a few lines of code more to manage overflows.</p> <p>I would really appreciate some help in implementing the 5 basic operations for my structure.</p> <p>EDIT:</p> <p>After looking at the proposed answers I have written quite some code. At this point I have minus, plus and times operations working correctly but can't get the modulus to work... For the algorithm to implement modulo I have been using the pseudo code from Rosetta code that does polynomial division. Please see the updated code:</p> <pre class="lang-c prettyprint-override"><code> #include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #define BASE 16 typedef struct { uint64_t values[BASE]; } uint1024_t; #define UINT64_HI(x) (x &gt;&gt; 32) #define UINT64_LO(x) (((1ULL &lt;&lt; 32) - 1) &amp; x) uint64_t uint64_add(uint64_t a, uint64_t b, uint64_t *carry) { uint64_t s0, s1, s2; uint64_t x = UINT64_LO(a) + UINT64_LO(b); s0 = UINT64_LO(x); x = UINT64_HI(a) + UINT64_HI(b) + UINT64_HI(x); s1 = UINT64_LO(x); s2 = UINT64_HI(x); *carry = s2; return (s0 | (s1 &lt;&lt; 32)); } void uint64_sub(uint64_t a, uint1024_t *src, int i) { // Check if the subtraction can be performed if (src-&gt;values[i] &gt;= a) src-&gt;values[i] -= a; else { // If we need to take higher positions: int rem = i; while (i &lt; BASE) { i++; if (src-&gt;values[i] != 0) { src-&gt;values[i] -= 1; // Distribute while (rem &lt; i - 1) { i--; src-&gt;values[i] = UINT64_MAX; } // Subtract uint64_t intermediate = a - src-&gt;values[rem]; src-&gt;values[rem] = UINT64_MAX - intermediate; return; } } } } void uint1024_t_shift(uint1024_t src, uint1024_t *dest, int shift) { int i = 0; while (i &lt; BASE &amp;&amp; i &lt; shift) { dest-&gt;values[i] = 0; i++; } while (i &lt; BASE) { dest-&gt;values[i] = src.values[i - shift]; i++; } } int uint1024_t_degree(uint1024_t dest) { int i = BASE - 1; while (i &gt;= 0) { if (dest.values[i]) return i; i--; } } void propagate(uint64_t a, uint1024_t *dest, int i) { uint64_t carry; uint64_t res = uint64_add(dest-&gt;values[i], a, &amp;carry); dest-&gt;values[i] = res; if (carry) propagate(carry, dest, i + 1); } uint64_t uint64_multiply(uint64_t a, uint64_t b, uint64_t *carry) { // actually uint32_t would do, but the casting is annoying uint64_t s0, s1, s2, s3; uint64_t x = UINT64_LO(a) * UINT64_LO(b); s0 = UINT64_LO(x); x = UINT64_HI(a) * UINT64_LO(b) + UINT64_HI(x); s1 = UINT64_LO(x); s2 = UINT64_HI(x); x = s1 + UINT64_LO(a) * UINT64_HI(b); s1 = UINT64_LO(x); x = s2 + UINT64_HI(a) * UINT64_HI(b) + UINT64_HI(x); s2 = UINT64_LO(x); s3 = UINT64_HI(x); uint64_t result = s1 &lt;&lt; 32 | s0; uint64_t cr = s3 &lt;&lt; 32 | s2; *carry = cr; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // iterative in and out void printf_value(uint1024_t x) { for (int i = 0; i &lt; BASE; i++) { printf(&quot;%016llx &quot;, x.values[15 - i]); } printf(&quot;\n&quot;); } // generator uint1024 from uint64 // Put the actual uint64_t at the lest significant bit // Fill up the rest with zeros void uint1024_t_init(uint64_t x, uint1024_t *num) { for (int i = 1; i &lt; BASE; i++) { num-&gt;values[i] = 0; } num-&gt;values[0] = x; } void uint1024_t_add(uint1024_t *x, uint1024_t y) { uint64_t remaining = 0; for (int i = 0; i &lt; BASE; i++) { uint64_t carry = 0; uint64_t result = uint64_add(x-&gt;values[i], y.values[i], &amp;carry); x-&gt;values[i] = result + remaining; remaining = carry; } } void uint1024_t_sub(uint1024_t *x, uint1024_t y) { for (int i = 0; i &lt; BASE; i++) { uint64_sub(y.values[i], x, i); } } int uint1024_t_compare(uint1024_t *x, uint1024_t y) { int i = BASE - 1; while (i) { // If the difference is not zero if (x-&gt;values[i] - y.values[i]) { return x-&gt;values[i] &gt; y.values[i] ? 1 : -1; } i--; } return 0; } void uint1024_t_muly(uint1024_t *dest, const uint1024_t *a, const uint1024_t *b) { for (size_t i = 0; i &lt; BASE; i++) { uint64_t result = 0; uint64_t carry = 0; for (size_t j = 0, k = i; k &lt; BASE; j++, k++) { uint64_t mult_res = uint64_multiply(a-&gt;values[i], b-&gt;values[j], &amp;carry); // Dont forget to check for overflow here if (mult_res) { propagate(mult_res, dest, k); propagate(carry, dest, k + 1); } } } } /* void uint1024_t_mod(uint1024_t *numerator, uint1024_t denominator) { uint1024_t q; uint1024_t_init(0,&amp;q); while (uint1024_t_degree(*numerator) &gt;= uint1024_t_degree(denominator)) { int shift = uint1024_t_degree(*numerator) - uint1024_t_degree(denominator); uint1024_t d; uint1024_t_shift(denominator,&amp;d,shift); q.values[shift] = numerator-&gt;values[uint1024_t_degree(*numerator)] / d.values[uint1024_t_degree(d)]; uint1024_t tmp; uint1024_t_init(q.values[shift],&amp;tmp); uint1024_t tmp1; uint1024_t_muly(&amp;tmp1,&amp;d,&amp;tmp); uint1024_t_sub(numerator,tmp1); } } */ void uint1024_t_copy(uint1024_t *dst, uint1024_t *src) { for (int i = 0; i &lt; BASE; i++) { dst-&gt;values[i] = src-&gt;values[i]; } } void uint1024_t_mod(uint1024_t *numerator, uint1024_t denominator, uint1024_t *rest, uint1024_t *q) { uint1024_t_init(0, q); uint1024_t_init(0, rest); int num_pow = uint1024_t_degree(*numerator); int dem_pow = uint1024_t_degree(denominator); uint1024_t_copy(rest, numerator); uint64_t ratio = 0; for (int i = num_pow; i &gt;= dem_pow; i--) { uint64_t div = rest-&gt;values[i] / denominator.values[dem_pow]; uint64_t mod = rest-&gt;values[i] % denominator.values[dem_pow]; q-&gt;values[i - dem_pow] = div; ratio = div; rest-&gt;values[i] = mod; for (int j = 0; j &lt; dem_pow; j++) rest-&gt;values[i - dem_pow + j] -= denominator.values[j] * ratio; } } </code></pre> <p>As you can tell I have two version of the modulo that both don't work, but for different reasons, since the algorithms used differ quite a lot.</p> <p>What am I missing in my modulo implementation?</p> <p>Thanks in advance!</p>
[ { "answer_id": 74655150, "author": "Mailman3.com", "author_id": 1934852, "author_profile": "https://Stackoverflow.com/users/1934852", "pm_score": 1, "selected": false, "text": "mailman shell" }, { "answer_id": 74661749, "author": "Philip Iezzi", "author_id": 5982842, "author_profile": "https://Stackoverflow.com/users/5982842", "pm_score": 0, "selected": false, "text": "mailman shell from mailman.interfaces.listmanager import IListManager\nfrom zope.component import getUtility\nfrom mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef dump_members(roster):\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n\nlist_manager = getUtility(IListManager)\nmlist = list_manager.get('ant@example.com')\ndump_members(mlist.members.members)\n mailman withlist -r listmembers -l ant@example.com from mailman.testing.documentation import dump_list\nfrom operator import attrgetter\n\ndef listmembers(mlist):\n roster = mlist.members.members\n all_addresses = list(member.address for member in roster)\n sorted_addresses = sorted(all_addresses, key=attrgetter('email'))\n dump_list(sorted_addresses)\n listmembers.py /usr/lib/python3/dist-packages/mailman/runners $ mailman withlist -r listmembers -l ant@example.com\nModuleNotFoundError: No module named 'listmembers'\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18644076/" ]
74,654,146
<p>Hey im looking for a random date generator that uses the date of the system how can i do it? i give an example, if the month is february i want 5 numbers between 1-28 and if the month is january i want 5 numbers between 1-31</p> <p>ive tried to do it with</p> <pre><code>private Random gen = new Random(); DateTime RandomDay() { DateTime start = new DateTime(1995, 1, 1); int range = (DateTime.Today - start).Days; return start.AddDays(gen.Next(range)); } </code></pre> <p>but i didnt figured it out</p>
[ { "answer_id": 74654937, "author": "Hans Kesting", "author_id": 121309, "author_profile": "https://Stackoverflow.com/users/121309", "pm_score": 0, "selected": false, "text": "Random gen = new Random();\n\n// returns a *list* of dates\npublic List<DateTime> GetRandomDatesInOneMonth(int count)\n{\n // prepare the return value\n var result = new List<DateTime>();\n\n // count the total available days\n DateTime start = new DateTime(1995, 1, 1);\n int range = (int)(DateTime.Today - start).TotalDays;\n\n // get a random date in that range, to get the target month\n var target = start.AddDays(gen.Next(range));\n \n // get the number of days in this month, handling leap years\n var daysinmonth = DateTime.DaysInMonth(target.Year, target.Month);\n\n // repeat for the required amount of days\n for (int i=0; i<count; i++)\n {\n // get a day-number between 1 and daysinmonth, inclusive\n var day = gen.Next(daysinmonth) + 1;\n\n // calculate the new date, and add to result\n result.Add(new DateTime(target.Year, target.Month, day)); \n }\n\n // finally, return the list\n return result;\n}\n List<DateTime> fivedates = GetRandomDatesInOneMonth(5);\n" }, { "answer_id": 74655397, "author": "Palle Due", "author_id": 5516339, "author_profile": "https://Stackoverflow.com/users/5516339", "pm_score": 1, "selected": false, "text": "List<DateTime> GetRandomDatesForYearAndMonth(int year, int month, int numberOfDates, Random randomizer)\n{\n var result = new List<DateTime>();\n // Get number of days in month\n int days = DateTime.DaysInMonth(year, month);\n // Determine the candidate days\n var candidates = Enumerable.Range(1, days);\n for (int i=0;i<numberOfDates;i++)\n {\n // Pick a random element\n var dayIndex = randomizer.Next(candidates.Count());\n var day = candidates.ElementAt(dayIndex);\n // Add the date\n result.Add(new DateTime(year, month, day));\n // Remove it from the candidates\n candidates = candidates.Where(x => x != day);\n }\n return result;\n}\n\n Random randomizer = new Random();\nvar result = GetRandomDatesForYearAndMonth(1995, 2, 5, randomizer);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20665214/" ]
74,654,163
<p>Given the following test data:</p> <pre><code>declare @mg nvarchar(max); set @mg = '{&quot;fiskepind&quot;:[&quot;ko&quot;,&quot;hest&quot;,&quot;gris&quot;]}'; select @mg, JSON_VALUE(@mg,'$.fiskepind') </code></pre> <p>How do i get returned a column with:</p> <pre><code> ko,hest,gris </code></pre> <p>Example returns: <code>NULL</code>, and i dont want to [index] to only get one returned.</p>
[ { "answer_id": 74656984, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 0, "selected": false, "text": "OPENJSON FOR XML PATH STRING_AGG declare @mg nvarchar(max);\nset @mg = '{\"fiskepind\":[\"ko\",\"hest\",\"gris\"]}';\n\nselect @mg, JSON_VALUE(@mg,'$.fiskepind')\n , STUFF((\n SELECT\n ',' + value\n FROM OPENJSON(@mg, '$.fiskepind')\n FOR XML PATH('')\n ),1,1,'') as combined_list\n" }, { "answer_id": 74657218, "author": "Zhorov", "author_id": 6578080, "author_profile": "https://Stackoverflow.com/users/6578080", "pm_score": 2, "selected": true, "text": "OPENJSON() STRING_AGG() SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])) AS Result\nFROM OPENJSON(@mg, '$.fiskepind')\n JSON_VALUE() NULL '$.fiskepind'" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8554170/" ]
74,654,166
<p>I create a Task variable and try to await it just for learning purposes with the next code:</p> <pre><code> static async Task Main(string[] args) { Console.WriteLine(&quot;Start&quot;); Task myTask = new Task(() =&gt; { Console.WriteLine(&quot;Done&quot;); }); await myTask; Console.WriteLine(&quot;Finish&quot;); } </code></pre> <p>Application writes Start in the console and then it freezes. I am not sure how to understand whats happened here and why does it freeze. What can be the reason?</p> <p>I know that usually we apply await to the methods which return Task, but not variable. But vs compiles such code successfully. The expectation was to get all 3 messages in the console.</p>
[ { "answer_id": 74654278, "author": "Franz Gleichmann", "author_id": 5309228, "author_profile": "https://Stackoverflow.com/users/5309228", "pm_score": 3, "selected": false, "text": "new Task() static async Task Main(string[] args)\n{\n Console.WriteLine(\"Start\");\n Task myTask = new Task(() => { Console.WriteLine(\"Done\"); });\n\n myTask.Start();\n\n await myTask;\n Console.WriteLine(\"Finish\");\n}\n" }, { "answer_id": 74655882, "author": "Stephen Cleary", "author_id": 263693, "author_profile": "https://Stackoverflow.com/users/263693", "pm_score": 1, "selected": false, "text": "Task Task.Run static async Task Main(string[] args)\n{\n Console.WriteLine(\"Start\");\n Task myTask = Task.Run(() => { Console.WriteLine(\"Done\"); });\n await myTask;\n Console.WriteLine(\"Finish\");\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046672/" ]
74,654,180
<p>i have created global method that call showDialog, whenever i call it, it wont come out if i put Navigator.pop(context) , if i remove the navigator it will come out. I cannot close the errordialog if i dont have the navigator. Did i do something wrong? below is my code</p> <pre><code>class GlobalMethod { static void showErrorDialog( {required String error, required BuildContext ctx}) { showDialog( context: ctx, builder: (context) { return AlertDialog( title: Row(children: [ Padding( padding: EdgeInsets.all(8.0), child: Icon( Icons.logout, color: Colors.grey, size: 35, ), ), Padding( padding: EdgeInsets.all(8.0), child: Text('Error Occured'), ), ]), content: Text(error, style: TextStyle( color: Colors.black, fontSize: 20, fontStyle: FontStyle.italic)), actions: [ TextButton( onPressed: () { Navigator.canPop(context) ? Navigator.canPop(context) : null; }, child: Text( 'Okay', style: TextStyle( color: Colors.red, ), ), ) ], ); }); } </code></pre> <p>This is example when i call the method. If i remove the Navigator.pop the error dialog will pop out, if i put the navigator.pop nothing will come out</p> <pre><code>else if (balance &lt; price! ){ GlobalMethod.showErrorDialog(error: &quot;you dont have enough balance , please top up first&quot;, ctx: context); Navigator.pop(context); } </code></pre>
[ { "answer_id": 74654333, "author": "Jasmin Sojitra", "author_id": 11557906, "author_profile": "https://Stackoverflow.com/users/11557906", "pm_score": 0, "selected": false, "text": "class GlobalMethod {\n static void showErrorDialog(\n {required String error, required BuildContext ctx}) {\n showDialog(\n context: ctx,\n builder: (context) {\n return AlertDialog(\n title: Row(children: [\n Padding(\n padding: EdgeInsets.all(8.0),\n child: Icon(\n Icons.logout,\n color: Colors.grey,\n size: 35,\n ),\n ),\n Padding(\n padding: EdgeInsets.all(8.0),\n child: Text('Error Occured'),\n ),\n ]),\n content: Text(error,\n style: TextStyle(\n color: Colors.black,\n fontSize: 20,\n fontStyle: FontStyle.italic)),\n actions: [\n TextButton(\n onPressed: () {\n Navigator.canPop(ctx) ? Navigator.pop(context) : null;\n },\n child: Text(\n 'Okay',\n style: TextStyle(\n color: Colors.red,\n ),\n ),\n )\n ],\n );\n });\n }\n }\n else if (balance < price! ){\n GlobalMethod.showErrorDialog(error: \"you dont have enough balance , please top up first\", ctx: context);\n \n }\n" }, { "answer_id": 74654337, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "else if (balance < price! ){\n GlobalMethod.showErrorDialog(error: \"you dont have enough balance , please top up first\", ctx: context);\n \n}\n showErrorDialog onPressed: () {\n Navigator.canPop(context) ? Navigator.pop(context): null;\n},\n canPop pop canPop" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10625379/" ]
74,654,212
<p>Pretty new to these orchestration tools. Is it possible to integrate Control-M and mwaa airflow to trigger/ track jobs?</p> <p>Couldn't find much information regarding the same.</p>
[ { "answer_id": 74654333, "author": "Jasmin Sojitra", "author_id": 11557906, "author_profile": "https://Stackoverflow.com/users/11557906", "pm_score": 0, "selected": false, "text": "class GlobalMethod {\n static void showErrorDialog(\n {required String error, required BuildContext ctx}) {\n showDialog(\n context: ctx,\n builder: (context) {\n return AlertDialog(\n title: Row(children: [\n Padding(\n padding: EdgeInsets.all(8.0),\n child: Icon(\n Icons.logout,\n color: Colors.grey,\n size: 35,\n ),\n ),\n Padding(\n padding: EdgeInsets.all(8.0),\n child: Text('Error Occured'),\n ),\n ]),\n content: Text(error,\n style: TextStyle(\n color: Colors.black,\n fontSize: 20,\n fontStyle: FontStyle.italic)),\n actions: [\n TextButton(\n onPressed: () {\n Navigator.canPop(ctx) ? Navigator.pop(context) : null;\n },\n child: Text(\n 'Okay',\n style: TextStyle(\n color: Colors.red,\n ),\n ),\n )\n ],\n );\n });\n }\n }\n else if (balance < price! ){\n GlobalMethod.showErrorDialog(error: \"you dont have enough balance , please top up first\", ctx: context);\n \n }\n" }, { "answer_id": 74654337, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "else if (balance < price! ){\n GlobalMethod.showErrorDialog(error: \"you dont have enough balance , please top up first\", ctx: context);\n \n}\n showErrorDialog onPressed: () {\n Navigator.canPop(context) ? Navigator.pop(context): null;\n},\n canPop pop canPop" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20665276/" ]
74,654,231
<p>I have following piece of code that pulls environment variables via dotenv, can substitute it, if it does not exist and <code>defaultValue</code> is passed or throws error if neither of them contain value. This creates a scenario where execution either crashes or it returns valid value.</p> <pre><code>const getEnvironmentVariable = ( variable: string, defaultValue?: string|number, ): string | number =&gt; { if((process.env[variable] === undefined) &amp;&amp; defaultValue === undefined){ // eslint-disable-next-line max-len throw new Error(`Mandatory environment variable ${variable} was not set.`) } if( process.env[variable] === undefined &amp;&amp; defaultValue !== undefined ) { // eslint-disable-next-line no-console, max-len console.info(`Environment variable ${variable} was not set. Using default: ${defaultValue}`) } return process.env[variable] ?? defaultValue } </code></pre> <p>But I am getting following error on return, even tho it will never happen, that undefined will be returned.</p> <blockquote> <p>Type 'string | undefined' is not assignable to type 'string | number'. Type 'undefined' is not assignable to type 'string | number'.</p> </blockquote>
[ { "answer_id": 74654364, "author": "Nullndr", "author_id": 10503039, "author_profile": "https://Stackoverflow.com/users/10503039", "pm_score": 0, "selected": false, "text": "if defaultValue string | number | undefined and process.env[variable] === undefined if defaultValue === undefined if const getEnvironmentVariable = (\n variable: string,\n defaultValue?: string|number,\n): string | number => {\n if(process.env[variable] === undefined) {\n\n if(defaultValue === undefined) {\n // eslint-disable-next-line max-len\n throw new Error(`Mandatory environment variable ${variable} was not set.`) \n }\n\n if(defaultValue) {\n console.info(`Environment variable ${variable} was not set. Using default: ${defaultValue}`)\n return defaultValue;\n }\n }\n \n return process.env[variable];\n}\n" }, { "answer_id": 74654527, "author": "chribjel", "author_id": 13246837, "author_profile": "https://Stackoverflow.com/users/13246837", "pm_score": 2, "selected": true, "text": "process.env[variable] string | undefined const const getEnvironmentVariable = (\n variable: string,\n defaultValue?: string | number,\n): string | number => {\n const environmentVariable = process.env[variable]\n \n if (environmentVariable === undefined) {\n if (defaultValue === undefined) {\n throw new Error(\n `Mandatory environment variable ${variable} was not set.`,\n );\n }\n console.info(\n `Environment variable ${variable} was not set. Using default: ${defaultValue}`\n );\n return defaultValue;\n }\n return environmentVariable;\n};\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20241005/" ]
74,654,240
<p>Hi i am trying to learn Lua, I was playing around with the language and I come accrosed this code block</p> <pre><code>for i = 1, 4, 1 do if(i == 2) then break undefinedFunction(&quot;print 1&quot;) end print(&quot;print 2&quot;) end </code></pre> <p>which is fine for the interpreter and did nothing for the undefined function. On the other hand if we make this code block like that</p> <pre><code>for i = 1, 4, 1 do if(i == 2) then break 1 end print(&quot;Hello World asdasdsad asdasdas&quot;) end </code></pre> <p>which the lua interpreter throws error unexpected sign '1'.</p> <p>So i thought that Lua interpreter fines with undefined functions and just ignore them but if i code like that</p> <pre><code>for i = 1, 4, 1 do if(i == 2) then break end undefinedFunction(&quot;argument 1&quot;) print(&quot;print 1&quot;) end </code></pre> <p>now Lua interpreter gives error. Why there is an inconsistency?</p>
[ { "answer_id": 74654578, "author": "Lucas S.", "author_id": 3124208, "author_profile": "https://Stackoverflow.com/users/3124208", "pm_score": 4, "selected": true, "text": "1 \"foo\" 1 undefinedFunction == nil break break if if true then\n 1\nend\n if true then\n undefined()\nend\n if false then\n undefined() -- This line is never reached, and will not cause an error\nend\n" }, { "answer_id": 74654585, "author": "LMD", "author_id": 7185318, "author_profile": "https://Stackoverflow.com/users/7185318", "pm_score": 2, "selected": false, "text": "for i = 1, 4 do\n if i == 2 then\n break\n undefinedFunction(\"print 1\")\n end\n print(\"print 2\")\nend\n break break goto break goto undefinedFunction(\"print 1\") for i = 1, 4 do\n if i == 2 then\n break\n 1\n end\n print(\"print 2\")\nend\n 1 break end for i = 1, 4 do\n if i == 2 then\n break\n end\n undefinedFunction(\"argument 1\")\n print(\"print 2\")\nend\n undefinedFunction _G[\"undefinedFunction\"] nil nil" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17448163/" ]
74,654,248
<p>im trying to reverse div with Jquery which when i click a button the divs will reverse and switch place</p> <pre><code>&lt;div class=&quot;player1&quot;&gt; &lt;div class=&quot;player1-a&quot;&gt; &lt;div class=&quot;pemain p1a&quot;&gt; &lt;h4&gt;Samsudin&lt;/h4&gt; &lt;/div&gt; &lt;div class=&quot;cock 1a&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;player1-b&quot;&gt; &lt;div class=&quot;pemain p1b&quot;&gt; &lt;h4&gt;Joko&lt;/h4&gt; &lt;/div&gt; &lt;div class=&quot;cock 1b&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>&lt;button class=&quot;btn btn-light score_plus&quot; id=&quot;score_kiri&quot;&gt;&lt;h1&gt;SCORE&lt;/h1&gt;&lt;/button&gt; </code></pre> <p>whenever this button clicked the div p1b will move to div player1-a and so do div p1a will move to div player1-b.</p> <p>Here's my jquery code that the divs only move once and dont move again when i click again.</p> <pre><code>$('#score_kiri').click(function() { $('#player_kiri').val(i++); $('.p1a').appendTo('.player1-b'); $('.1a').appendTo('.player1-b'); $('.p1b').appendTo('.player1-a'); $('.1b').appendTo('.player1-a'); $('.p1a').append('.player1-b'); $('.1a').append('.player1-b'); $('.p1b').append('.player1-a'); $('.1b').append('.player1-a'); }); </code></pre>
[ { "answer_id": 74654578, "author": "Lucas S.", "author_id": 3124208, "author_profile": "https://Stackoverflow.com/users/3124208", "pm_score": 4, "selected": true, "text": "1 \"foo\" 1 undefinedFunction == nil break break if if true then\n 1\nend\n if true then\n undefined()\nend\n if false then\n undefined() -- This line is never reached, and will not cause an error\nend\n" }, { "answer_id": 74654585, "author": "LMD", "author_id": 7185318, "author_profile": "https://Stackoverflow.com/users/7185318", "pm_score": 2, "selected": false, "text": "for i = 1, 4 do\n if i == 2 then\n break\n undefinedFunction(\"print 1\")\n end\n print(\"print 2\")\nend\n break break goto break goto undefinedFunction(\"print 1\") for i = 1, 4 do\n if i == 2 then\n break\n 1\n end\n print(\"print 2\")\nend\n 1 break end for i = 1, 4 do\n if i == 2 then\n break\n end\n undefinedFunction(\"argument 1\")\n print(\"print 2\")\nend\n undefinedFunction _G[\"undefinedFunction\"] nil nil" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20665160/" ]
74,654,296
<p>I would like to be able to send requests to the graph API from nodejs. For that I followed the tutorial <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-console" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-console</a> I manage to get a token that allows me to execute a request on the endpoint <a href="https://graph.microsoft.com/v1.0/users" rel="nofollow noreferrer">https://graph.microsoft.com/v1.0/users</a> with insomnia. I have the list of users of the tenant in JSON. But in JS the response.data is unreadable (▼♦ ��KK♥...), I tried to change the encoding but without success.</p> <p>The tutorial uses the axios library and the get method to get the result, is it necessary to add something to get a json?</p>
[ { "answer_id": 74654578, "author": "Lucas S.", "author_id": 3124208, "author_profile": "https://Stackoverflow.com/users/3124208", "pm_score": 4, "selected": true, "text": "1 \"foo\" 1 undefinedFunction == nil break break if if true then\n 1\nend\n if true then\n undefined()\nend\n if false then\n undefined() -- This line is never reached, and will not cause an error\nend\n" }, { "answer_id": 74654585, "author": "LMD", "author_id": 7185318, "author_profile": "https://Stackoverflow.com/users/7185318", "pm_score": 2, "selected": false, "text": "for i = 1, 4 do\n if i == 2 then\n break\n undefinedFunction(\"print 1\")\n end\n print(\"print 2\")\nend\n break break goto break goto undefinedFunction(\"print 1\") for i = 1, 4 do\n if i == 2 then\n break\n 1\n end\n print(\"print 2\")\nend\n 1 break end for i = 1, 4 do\n if i == 2 then\n break\n end\n undefinedFunction(\"argument 1\")\n print(\"print 2\")\nend\n undefinedFunction _G[\"undefinedFunction\"] nil nil" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408511/" ]
74,654,313
<p>I want to add months to a date by conditition. That means if my ISO column is ET I want to add 92 month.</p> <p>When I only run this code, i recieve the dates I want.</p> <pre><code>ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, &quot;01&quot;, sep = &quot;-&quot;)) %m+% months(92) </code></pre> <p>first lines of my output:</p> <pre><code> [1] &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; [9] &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; [17] &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; [25] &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; &quot;2011-04-01&quot; </code></pre> <p>But if I use it in an <code>ifelse</code> statement, it will returns numbers</p> <pre><code>comb_extract_all$date &lt;- ifelse(comb_extract_all$ISO == &quot;ET&quot;, ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, &quot;01&quot;, sep=&quot;-&quot;)) %m+% months(92), ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, &quot;01&quot;, sep=&quot;-&quot;))) </code></pre> <p>My <code>dput</code> output with the most important columns is as follows (where you can see the &quot;wrong&quot; date column):</p> <pre><code>dput(comb_extract_all[1:5,c(1,5,6,23,24)]) structure(list(hhid = c(&quot; 1 27&quot;, &quot; 1 27&quot;, &quot; 1 27&quot;, &quot; 1 27&quot;, &quot; 1 67&quot;), hv006 = c(8, 8, 8, 8, 8), hv007 = c(2003, 2003, 2003, 2003, 2003), ISO = c(&quot;ET&quot;, &quot;ET&quot;, &quot;ET&quot;, &quot;ET&quot;, &quot;ET&quot; ), date = c(15065, 15065, 15065, 15065, 15065)), row.names = c(&quot;ETPR61SV.1&quot;, &quot;ETPR61SV.2&quot;, &quot;ETPR61SV.3&quot;, &quot;ETPR61SV.4&quot;, &quot;ETPR61SV.5&quot;), class = &quot;data.frame&quot;) </code></pre>
[ { "answer_id": 74654448, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "numeric dplyr::if_else library(lubridate)\nlibrary(dplyr)\n\ncomb_extract_all$date <- ymd(paste(comb_extract_all$hv007, comb_extract_all$hv006, \"01\", sep = \"-\"))\n\ncomb_extract_all$date <- dplyr::if_else(comb_extract_all$ISO == \"ET\",\n comb_extract_all$date %m+% months(92),\n comb_extract_all$date\n)\n\ncomb_extract_all\n#> hhid hv006 hv007 ISO date\n#> ETPR61SV.1 1 27 8 2003 ET 2011-04-01\n#> ETPR61SV.2 1 27 8 2003 ET 2011-04-01\n#> ETPR61SV.3 1 27 8 2003 ET 2011-04-01\n#> ETPR61SV.4 1 27 8 2003 ET 2011-04-01\n#> ETPR61SV.5 1 67 8 2003 ET 2011-04-01\n" }, { "answer_id": 74654569, "author": "chris jude", "author_id": 14579051, "author_profile": "https://Stackoverflow.com/users/14579051", "pm_score": 0, "selected": false, "text": "library(tidyverse)\ncomb_extract_all$date <- \n if_else(comb_extract_all$ISO == \"ET\", \n (ymd(paste(comb_extract_all$hv007,\n comb_extract_all$hv006,\"01\", \n sep = \"-\")) %m+% months(92)), \n (ymd(paste(comb_extract_all$hv007,\n comb_extract_all$hv006,\"01\", \n sep = \"-\"))))\n\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169859/" ]
74,654,355
<p>A dumb question. How to manipulate columns in Polars?</p> <p>Explicitly, I have a table with 3 columns : N , Survivors, Deaths</p> <p>I want to replace Deaths by Deaths * N and Survivors by Survivors * N</p> <p>the following code is not working</p> <pre><code>table[&quot;SURVIVORS&quot;] = table[&quot;SURVIVORS&quot;]*table[&quot;N&quot;] </code></pre> <p>I have this error:</p> <pre><code>TypeError: 'DataFrame' object does not support 'Series' assignment by index. Use 'DataFrame.with_columns' </code></pre> <p>thank you</p>
[ { "answer_id": 74654528, "author": "user120027", "author_id": 1535961, "author_profile": "https://Stackoverflow.com/users/1535961", "pm_score": -1, "selected": false, "text": "# Import the pandas library\nimport pandas as pd\n\n# Load the table data into a DataFrame object\ntable = pd.read_csv(\"table.csv\")\n\n#Create a new DataFrame object with the modified columns .with_columns()\ntable = table.with_columns(\"SURVIVORS\": table[\"SURVIVORS\"]*table[\"N\"], \"DEATHS\": table[\"DEATHS\"]*table[\"N\"])\n" }, { "answer_id": 74654570, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "polars.DataFrame.with_column import polars as pl\n\ntable = pl.DataFrame({\"N\": [5, 2, 6],\n \"SURVIVORS\": [1, 10, 3],\n \"Deaths\": [0, 3, 2]})\n\ntable= table.with_column(pl.Series(name=\"SURVIVORS\",\n values=table[\"SURVIVORS\"]*table[\"N\"])) \n print(table)\n\nshape: (3, 3)\n┌─────┬───────────┬────────┐\n│ N ┆ SURVIVORS ┆ Deaths │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ i64 │\n╞═════╪═══════════╪════════╡\n│ 5 ┆ 5 ┆ 0 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 20 ┆ 3 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤\n│ 6 ┆ 18 ┆ 2 │\n└─────┴───────────┴────────┘\n" }, { "answer_id": 74655083, "author": "Dean MacGregor", "author_id": 1818713, "author_profile": "https://Stackoverflow.com/users/1818713", "pm_score": 1, "selected": false, "text": "table[\"SURVIVORS\"]= with_column with_columns select select table=table.with_columns([\n pl.col('SURVIVORS')*pl.col('N'),\n pl.col('DEATHS')*pl.col('N')\n ])\n table=table.with_columns([\n (pl.col('SURVIVORS')*pl.col('N')).alias('SURIVORS_N'),\n (pl.col('DEATHS')*pl.col('N')).alias('DEATHS_N')\n ])\n with_columns select select table=table.select([ 'N',\n (pl.col('SURVIVORS')*pl.col('N')).alias('SURIVORS_N'),\n (pl.col('DEATHS')*pl.col('N')).alias('DEATHS_N')\n ])\n pl.col('column_name')" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11535369/" ]
74,654,356
<p>How to split an array into smaller arrays separated by &quot;&quot;?</p> <p>I have an array which looks like this:</p> <pre><code> `[ '1000', '2000', '3000', '', '4000', '', '5000', '6000', '', '7000', '8000', '9000', '', '10000' ] ` </code></pre> <p>I need arrays which would look like this:</p> <pre><code> ` ['1000', '2000', '3000',] [ '4000'] ['5000', '6000' ] ['7000', '8000', '9000'] [ '10000'] ` </code></pre> <p>Any help is useful</p>
[ { "answer_id": 74654537, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "Array.slice() let arr = [\n '1000', '2000', '3000',\n '', '4000', '',\n '5000', '6000', '',\n '7000', '8000', '9000',\n '', '10000'\n]\n\nconst convertArray = data => {\n let pos = []\n data.forEach((v,i) =>{\n if(!v){\n pos.push(i)\n }\n })\n\n let result = []\n let prev = 0\n for(p of pos){\n result.push(data.slice(prev,p))\n prev = p + 1\n }\n result.push(data.slice(prev))\n return result\n}\n\n\nconsole.log(convertArray(arr))" }, { "answer_id": 74655287, "author": "Sagar Didel", "author_id": 19626832, "author_profile": "https://Stackoverflow.com/users/19626832", "pm_score": 0, "selected": false, "text": " const arr = [\n '1000', '2000', '3000',\n '', '4000', '',\n '5000', '6000', '',\n '7000', '8000', '9000',\n '', '10000'\n]\n\nconst newArr = []\nlet index = 0\n\nfor (let i = 0; i < arr.length; i++) {\n if (arr[i] == '') {\n const newArrSet = []\n for(let j = i ; j > index ; j-- ){\n console.log('revese' , arr[j] , i)\n newArrSet.push(arr[j])\n }\n newArr.push(newArrSet)\n index = i\n }\n\n}\n const mappedArray = newArr.map((item)=>{\n return item.filter(item=> item !== '')\n })\n\n console.log(mappedArray)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570295/" ]
74,654,370
<p>I can produce a query that looks at this separately but when I try and combine it I'm having an issue.</p> <p>Original example query</p> <pre><code>Select account_name, count(distinct user_id) from table where event like 'birthday' group by account name </code></pre> <p>Any help greatly appreciated</p> <p>When I try and combine this in a larger query that looks at multiple event types I'm having trouble getting it to count distinct users</p> <p>What I'm trying</p> <pre><code>Select account_name, case when event_text = 'birthday' then count(distinct user_id) end case when event_text = 'wedding' then count(distinct user_id) end case when event_text = 'wedding' then count(distinct user_id) end from table group by account_name </code></pre>
[ { "answer_id": 74654537, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "Array.slice() let arr = [\n '1000', '2000', '3000',\n '', '4000', '',\n '5000', '6000', '',\n '7000', '8000', '9000',\n '', '10000'\n]\n\nconst convertArray = data => {\n let pos = []\n data.forEach((v,i) =>{\n if(!v){\n pos.push(i)\n }\n })\n\n let result = []\n let prev = 0\n for(p of pos){\n result.push(data.slice(prev,p))\n prev = p + 1\n }\n result.push(data.slice(prev))\n return result\n}\n\n\nconsole.log(convertArray(arr))" }, { "answer_id": 74655287, "author": "Sagar Didel", "author_id": 19626832, "author_profile": "https://Stackoverflow.com/users/19626832", "pm_score": 0, "selected": false, "text": " const arr = [\n '1000', '2000', '3000',\n '', '4000', '',\n '5000', '6000', '',\n '7000', '8000', '9000',\n '', '10000'\n]\n\nconst newArr = []\nlet index = 0\n\nfor (let i = 0; i < arr.length; i++) {\n if (arr[i] == '') {\n const newArrSet = []\n for(let j = i ; j > index ; j-- ){\n console.log('revese' , arr[j] , i)\n newArrSet.push(arr[j])\n }\n newArr.push(newArrSet)\n index = i\n }\n\n}\n const mappedArray = newArr.map((item)=>{\n return item.filter(item=> item !== '')\n })\n\n console.log(mappedArray)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6813879/" ]
74,654,413
<p>In the code snippet below, I add a random number to an array every 3 seconds using <a href="https://developer.mozilla.org/en-US/docs/Web/API/setInterval" rel="nofollow noreferrer">setInterval</a>. This goes well, until I try to <strong>also</strong> call the function on the <strong>first render</strong> (see the commented line). This gives me this error: <code>Maximum update depth exceeded.</code></p> <pre class="lang-js prettyprint-override"><code>const [listItems, setListItems] = useState([]); useEffect(() =&gt; { function extendTheList() { const randNr = Math.floor(Math.random() * 10); setListItems([...listItems, randNr]); } // extendTheList(); const int = setInterval(() =&gt; { extendTheList(); }, 3000); return () =&gt; clearInterval(int); }, [listItems]); </code></pre> <p>Sandbox: <a href="https://codesandbox.io/s/vigilant-shamir-ltkh6m?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/vigilant-shamir-ltkh6m?file=/src/App.js</a></p>
[ { "answer_id": 74654458, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "const [listItems, setListItems] = useState([]);\n\nuseEffect(() => {\n function extendTheList() {\n const randNr = Math.floor(Math.random() * 10);\n setListItems(listItems => [...listItems, randNr]);\n }\n\n extendTheList();\n\n const int = setInterval(() => {\n extendTheList();\n }, 3000);\n return () => clearInterval(int);\n }, []);\n" }, { "answer_id": 74654470, "author": "Disco", "author_id": 11196441, "author_profile": "https://Stackoverflow.com/users/11196441", "pm_score": 1, "selected": false, "text": "listItems const [listItems, setListItems] = useState([]);\n\nuseEffect(() => {\n function extendTheList() {\n const randNr = Math.floor(Math.random() * 10);\n setListItems((currentItems) => [...currentItems, randNr]);\n }\n\n // extendTheList();\n\n const int = setInterval(() => {\n extendTheList();\n }, 3000);\n return () => clearInterval(int);\n}, [setListItems]);\n" }, { "answer_id": 74654509, "author": "rap-2-h", "author_id": 978690, "author_profile": "https://Stackoverflow.com/users/978690", "pm_score": 0, "selected": false, "text": "extendTheList() useEffect extendTheList() const [listItems, setListItems] = useState([]);\n\nfunction extendTheList() {\n const randNr = Math.floor(Math.random() * 10);\n setListItems([...listItems, randNr]);\n}\n\nuseEffect(() => {\n extendTheList();\n\n const int = setInterval(() => {\n extendTheList();\n }, 3000);\n return () => clearInterval(int);\n }, []);\n extendTheList() useEffect" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134029/" ]
74,654,439
<p>I can't find any proper tutorial of how to do this.</p> <p>I tried:</p> <pre><code>var hashMap = [Int:[String:String]]() hashMap[7][&quot;height&quot;] = &quot;bla&quot; hashMap[7][&quot;align&quot;] = &quot;blatoo&quot; print(hashMap[7][&quot;height&quot;]) </code></pre> <p>It prints nil</p> <p>How to do this?</p>
[ { "answer_id": 74654519, "author": "Thang Phi", "author_id": 10650407, "author_profile": "https://Stackoverflow.com/users/10650407", "pm_score": 2, "selected": true, "text": "[Int:[String:String]] key Int [String:String] [String:String] String String [String:String] 7 hashMap 7 var hashMap = [Int:[String:String]]()\n\nvar dict = [String:String]()\n\ndict[\"height\"] = \"bla\"\ndict[\"align\"] = \"blatoo\"\n\nhashMap[7] = dict\n\nprint(\"hashmap: \", hashMap[7]?[\"height\"]) // Optional(\"bla\")\n" }, { "answer_id": 74654526, "author": "DarkDust", "author_id": 400056, "author_profile": "https://Stackoverflow.com/users/400056", "pm_score": 2, "selected": false, "text": "[7] nil var hashMap = [Int:[String:String]]()\n\nhashMap[7, default: [:]][\"height\"] = \"bla\"\nhashMap[7, default: [:]][\"align\"] = \"blatoo\"\n\nprint(hashMap[7]?[\"height\"])\n func set(int: Int, key: String, value: String) {\n hashMap[int, default: [:]][key] = value\n}\n\nset(int: 7, key: \"height\", value: \"bla\")\nset(int: 7, key: \"align\", value: \"blatoo\")\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19559647/" ]
74,654,449
<p><a href="https://i.stack.imgur.com/bvGog.png" rel="nofollow noreferrer">enter image description here</a></p> <p>what i need is when i selected item in combobox to show in listbox and his price in the cost textbox and sum price if i choose another items</p> <p>this is my code public void fill_listbox() { SqlDataAdapter da = new SqlDataAdapter(&quot;select TestCost,TestName from TestTbl&quot;, con); DataSet dt = new DataSet(); da.Fill(dt, &quot;TestName&quot;); TestidCb.DataSource = dt.Tables[&quot;TestName&quot;]; TestidCb.DisplayMember = &quot;TestName&quot;; TestidCb.ValueMember = &quot;TestCost&quot;; TestidCb.Text = &quot;Select NorTest&quot;;</p> <pre><code> } string TR = &quot;&quot;; int GrdCost = 0; private void OkBtn_Click(object sender, EventArgs e) { if (LabidCb.SelectedIndex == -1 ) { MessageBox.Show(&quot;select the Test And Lab&quot;); } else { TR = TR + &quot;|&quot; + TestidCb.Text; TestTb.Text = TR; GrdCost = GrdCost +Cost; CostTb.Text = &quot;&quot; + GrdCost; //TestidCb.SelectedIndex = -1; //LabidCb.SelectedIndex = -1; //StNameTb.Text = &quot;&quot;; Reset1(); } </code></pre> <p>}</p>
[ { "answer_id": 74656108, "author": "Crowcoder", "author_id": 276469, "author_profile": "https://Stackoverflow.com/users/276469", "pm_score": 1, "selected": false, "text": "ExecuteNonQuery SELECT public void fill_list()\n{\n try\n {\n con.Open();\n using(SqlCommand cmd = con.CreateCommand())\n {\n cmd.CommandType = CommandType.Text;\n cmd.CommandText = \"select TestName, TestPrice from TestTbl\";\n \n DataTable dt = new DataTable();\n SqlDataAdapter da = new SqlDataAdapter(cmd);\n da.Fill(dt);\n \n TestidCb.DataSource = dt;\n TestidCb.DisplayMember = \"TestName\";\n TestidCb.ValueMember = \"TestPrice\";\n } \n }\n finally\n {\n con.Close();\n }\n}\n private void TestidCb_SelectedIndexChanged(object sender, EventArgs e)\n{\n string name = ((ComboBox)sender).Text;\n string price = ((ComboBox)sender).SelectedValue.ToString();\n\n MessageBox.Show($\"Name: {name}, Price: {price}\");\n}\n" }, { "answer_id": 74656238, "author": "ufosnowcat", "author_id": 1728208, "author_profile": "https://Stackoverflow.com/users/1728208", "pm_score": 0, "selected": false, "text": " public class myListItem\n {\n public string Name { get; set; }\n public decimal Price { get; set; }\n\n public override string ToString()\n {\n return Name;\n }\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n comboBox1.Items.Add(new myListItem(){Name = \"myname\",Price = 10});\n }\n\n private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n {\n var selected = comboBox1.SelectedItem as myListItem;\n if (selected != null)\n {\n textBox1.Text = selected.Price.ToString();\n\n }\n }\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20552904/" ]
74,654,474
<p>I'm trying to save some string content into a file from JavaScript. Below is my code and I'm getting issues because of new lines in the String content.</p> <p>How to save a file with preserving new lines?</p> <pre><code>var text = &quot;Hello \n World!&quot; var file = new Blob([text], {{type:'text/plain'}}); var anchor = document.createElement(&quot;a&quot;); anchor.href = URL.createObjectURL(file); anchor.download = &quot;file.log&quot;; anchor.click(); </code></pre> <p>Note: I'm using python code as below to execute above JS code.</p> <pre><code>log_lines : str = &quot;Hello \n World&quot; q.page['meta'].script = ui.inline_script( f''' var file = new Blob([&quot;{log_lines}&quot;], {{type:'text/plain'}}); var anchor = document.createElement(&quot;a&quot;); anchor.href = URL.createObjectURL(file); anchor.download = &quot;test.log&quot;; anchor.click(); ''' ) </code></pre> <p>Python SDK: <a href="https://wave.h2o.ai/docs/javascript" rel="nofollow noreferrer">https://wave.h2o.ai/docs/javascript</a></p> <p>I'm getting below error in my browser, <a href="https://i.stack.imgur.com/A9Y9C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9Y9C.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/Jsaun.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jsaun.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74654508, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "var text = \"Hello \\n World!\"\nvar encodedText = encodeURIComponent(text);\nvar file = new Blob([encodedText], {{type:'text/plain'}});\nvar anchor = document.createElement(\"a\");\nanchor.href = URL.createObjectURL(file);\nanchor.download = \"file.log\";\nanchor.click();\n" }, { "answer_id": 74655085, "author": "Senal Weerasinghe", "author_id": 4249637, "author_profile": "https://Stackoverflow.com/users/4249637", "pm_score": 0, "selected": false, "text": "\\n \\\\n log_lines : str = \"Hello \\n World\".replace(\"\\n\", \"\\\\n\")\n\nq.page['meta'].script = ui.inline_script(\n f'''\n var file = new Blob([\"{log_lines}\"], {{type:'text/plain'}});\n var anchor = document.createElement(\"a\");\n anchor.href = URL.createObjectURL(file);\n anchor.download = \"test.log\";\n anchor.click();\n '''\n )\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249637/" ]
74,654,503
<p>I have a dataset with 21 columns there are 2 columns that has 25% missing values, I'm reluctant to drop them or not? Is it make sence to drop columns that has more than 20% of its data as missing, or how can I determine the percentage of missing values that decide to drop the column</p> <p>I dropped the columns that have 20% or more missing values, I am expecting to know the best way to determine this percentage amount for example: should I use 20% or 40% or higher?</p>
[ { "answer_id": 74654508, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "var text = \"Hello \\n World!\"\nvar encodedText = encodeURIComponent(text);\nvar file = new Blob([encodedText], {{type:'text/plain'}});\nvar anchor = document.createElement(\"a\");\nanchor.href = URL.createObjectURL(file);\nanchor.download = \"file.log\";\nanchor.click();\n" }, { "answer_id": 74655085, "author": "Senal Weerasinghe", "author_id": 4249637, "author_profile": "https://Stackoverflow.com/users/4249637", "pm_score": 0, "selected": false, "text": "\\n \\\\n log_lines : str = \"Hello \\n World\".replace(\"\\n\", \"\\\\n\")\n\nq.page['meta'].script = ui.inline_script(\n f'''\n var file = new Blob([\"{log_lines}\"], {{type:'text/plain'}});\n var anchor = document.createElement(\"a\");\n anchor.href = URL.createObjectURL(file);\n anchor.download = \"test.log\";\n anchor.click();\n '''\n )\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17574071/" ]
74,654,504
<p>Im really new to Nuxt 3 and Vue 3. I just want simple value change when i click on my div tag.</p> <pre><code>&lt;a id=&quot;change&quot; @click=&quot;changeValue()&quot;&gt;{{value}}&lt;/a&gt; </code></pre> <pre><code>&lt;script lang=&quot;ts&quot; setup&gt; let value = &quot;Old&quot;; function changeValue(){ value=&quot;new&quot; } &lt;/script&gt; </code></pre> <p>This is the only thing i tried</p>
[ { "answer_id": 74654508, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "var text = \"Hello \\n World!\"\nvar encodedText = encodeURIComponent(text);\nvar file = new Blob([encodedText], {{type:'text/plain'}});\nvar anchor = document.createElement(\"a\");\nanchor.href = URL.createObjectURL(file);\nanchor.download = \"file.log\";\nanchor.click();\n" }, { "answer_id": 74655085, "author": "Senal Weerasinghe", "author_id": 4249637, "author_profile": "https://Stackoverflow.com/users/4249637", "pm_score": 0, "selected": false, "text": "\\n \\\\n log_lines : str = \"Hello \\n World\".replace(\"\\n\", \"\\\\n\")\n\nq.page['meta'].script = ui.inline_script(\n f'''\n var file = new Blob([\"{log_lines}\"], {{type:'text/plain'}});\n var anchor = document.createElement(\"a\");\n anchor.href = URL.createObjectURL(file);\n anchor.download = \"test.log\";\n anchor.click();\n '''\n )\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20622025/" ]
74,654,524
<p>Suppose I have this random vector:</p> <pre><code>julia&gt; rnd = rand(1:100, 1000); </code></pre> <p>And I have Boolean indices related to <code>rnd</code> like this:</p> <pre><code>julia&gt; idx = rand(0:1, 1000); </code></pre> <p>If I say <code>rnd[idx]</code>, it will return the <code>rnd</code>'s elements where the <code>idx==1</code> in that indices. But, I want to get the elements where the <code>idx==0</code> efficiently!</p> <p>So I tried these:</p> <pre><code>julia&gt; rnd[~idx] ERROR: MethodError: no method matching ~(::Vector{Int64}) julia&gt; rnd[replace(idx, 0=&gt;1, 1=&gt;0)] ERROR: BoundsError: attempt to access 1000-element Vector{Int64} at index [[1, 0, 0, 1, 0, 1, 0, 0, 1, 0 … 1, 1, 1, 1, 0, 1, 1, 0, 0, 0]] julia&gt; rnd[findall(==(0), idx)] 511-element Vector{Int64}: 70 31 43 ⋮ </code></pre> <p>Apparently, the last one works. Is there any better way to do this?</p>
[ { "answer_id": 74654508, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "var text = \"Hello \\n World!\"\nvar encodedText = encodeURIComponent(text);\nvar file = new Blob([encodedText], {{type:'text/plain'}});\nvar anchor = document.createElement(\"a\");\nanchor.href = URL.createObjectURL(file);\nanchor.download = \"file.log\";\nanchor.click();\n" }, { "answer_id": 74655085, "author": "Senal Weerasinghe", "author_id": 4249637, "author_profile": "https://Stackoverflow.com/users/4249637", "pm_score": 0, "selected": false, "text": "\\n \\\\n log_lines : str = \"Hello \\n World\".replace(\"\\n\", \"\\\\n\")\n\nq.page['meta'].script = ui.inline_script(\n f'''\n var file = new Blob([\"{log_lines}\"], {{type:'text/plain'}});\n var anchor = document.createElement(\"a\");\n anchor.href = URL.createObjectURL(file);\n anchor.download = \"test.log\";\n anchor.click();\n '''\n )\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664373/" ]
74,654,564
<p>Hello I'm sorry if my question is a bit silly. I'm learning html css as I go along and I'm currently having trouble placing a sign to the right (blue area) of a container (green area). I tried to position this panel using 'absolute' positioning with top: 0 and right: 0 but part of the panel is hidden.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&amp;display=swap'); *{ font-family: 'Poppins', sans-serif; margin: 0; padding: 0; box-sizing: border-box } :root{ /* ===== Colors ===== */ --body-color: #E4E9F7; --sidebar-color: #FFF; --primary-color: #1c1a1a; --primary-color-light: #F6F5FF; --toggle-color: #DDD; --text-color: #707070; /* ===== Transition ===== */ --tran-02: all 0.2s ease; --tran-03: all 0.3s ease; --tran-04: all 0.4s ease; --tran-05: all 0.5s ease; } body{ height: 100vh; background: var(--body-color); } /*--------------------- SIDEBAR ---------------------*/ /*Paramètres de la sidebar*/ .sidebar{ position: fixed; top: 0; left: 0; height:100%; width: 78px; background: var(--primary-color); padding: 6px 14px; transition: all 0.5s ease; } /*Activer l'élargissement de la sidebar*/ .sidebar.active{ width: 240px } /*Paramètre du logo*/ .sidebar .logo_content .logo{ color: #FFF; display: flex; height: 50px; width:100%; align-items: center; opacity: 0; pointer-events: none; } /*Activation de l'affichage du logo*/ .sidebar.active .logo_content .logo{ opacity: 1; pointer-events: none; } /*?*/ .logo_content .logo i{ font-size: 28px; margin-right: 5px; } /*Paramètre texte logo*/ .logo_content .logo .logo_name{ font-size: 20px; font-weight: 400; } /*Paramètre du bouton d'activation de la sidebar*/ .sidebar #btn{ position: absolute; color: #FFF; top: 6px; left: 50%; font-size: 20px; height: 50px; width: 50px; text-align: center; line-height: 50px; cursor: pointer; transform: translateX(-50%); } /*Activer le déplacement du bouton en mode toggle*/ .sidebar.active #btn{ left:90%; } /**/ .sidebar .divider{ margin-top:0px; font-size: 12px; text-transform: uppercase; font-weight: 700; color: #707070; text-align: center; } .sidebar.active .divider{ margin-top:0px; font-size: 12px; text-transform: uppercase; font-weight: 700; color: #707070; text-align: left; } /*Paramètre de la liste*/ .sidebar ul{ margin-top: 20px; } /*Paramètres pour chaque éléments de la liste*/ .sidebar li{ position: relative; height: 50px; width: 100%; margin: 0 0px; list-style: none; line-height:50px ; } /*Paramètres des textes de chaque élément*/ .sidebar li a{ color: #FFF; display: flex; align-items: center; text-decoration: none; transition: all 0.4s ease; border-radius: 12px; white-space: nowrap; } /*Activer un fond par dessus lors du passage de la souris*/ .sidebar li a:hover{ color: #11101d; background: #FFF; } /*Paramètres des logos*/ .sidebar li a i{ height: 50px; min-width: 50px; border-radius: 12px; line-height: 50px; text-align: center; } /*Désactiver l'affichage des noms*/ .sidebar .links_name{ opacity: 0; pointer-events: none; } /*Activer l'affichage des noms*/ .sidebar.active .links_name{ opacity: 1; pointer-events: auto; } /*Séparation des 2 sous menus*/ .sidebar .menu-bar{ height: calc(100% - 50px); display: flex; flex-direction: column; justify-content: space-between; } /*Paramétre logo notification*/ .sidebar .badge{ position: relative; font-size: 10px; top: -10px; left: -116px; display: flex; } /*Paramètres de la page des templates*/ .home{ position: relative; height: 100vh; left: 78px; width: calc(100% - 78px); background: var(--body-color); transition: var(--tran-05); } /*Paramètre texte de la page*/ .home .text{ font-size: 30px; font-weight: 500; color: var(--text-color); padding: 8px 40px; } /*Activer le mouvement de la page*/ .sidebar.active ~ .home{ left: 240px; width: calc(100% - 78px); } /*--------------------- TEMPLATE 1 ---------------------*/ .template-1{ display: block; position: fixed; top: 0; width: 100%; height: 100%; background: green; } /* PANEL N°1*/ /*Paramètres de la fenêtre modal*/ .panel-1{ position: absolute; width: 10%; height: 100%; padding: 5px; background: red; } /*Paramétre titre du panneau*/ .panel-1 .panel-header h1{ font-size: 1.5vh; margin-left: 5px; font-family: Montserrat, sans-serif; font-weight: 500; } /*Paramétre panel header*/ .panel-1 .panel-header{ display: flex; height: 3%; border-radius: 5px 5px 0px 0px; align-items: center; justify-content: space-between; padding: 0.1% 0.1%; background-color: rgb(91, 91, 91); color: rgb(255, 255, 255); box-shadow: 0 0 7px rgba(18,18,18,0.5); } /*Paramètres panel body*/ .panel-1 .panel-body{ height: 97%; background-color: #ffffff; box-shadow: 0 0 7px rgba(18,18,18,0.5); } /*----- Sections -----*/ .panel-body .sec-5{ position: relative; width: 100%; height: 20%; cursor: pointer; border: 1px solid #000000; } .panel-body .sec-5:hover{ background-color: #707070; color: #E4E9F7; } .panel-body h1{ position: absolute; top: 58%; left: 50%; transform: translate(-50%,-50%); font-size: 4vh; } .panel-body h2{ position: absolute; left: 50%; transform: translateX(-50%); font-size: 3vh; } .panel-body h3{ position: absolute; margin-left: 2%; font-size: 1.5vh; } .panel-body .sec-4{ position: relative; width: 100%; height: 20%; cursor: pointer; border: 1px solid #000000; } .panel-body .sec-4:hover{ background-color: #707070; color: #E4E9F7; } .panel-body .sec-3{ position: relative; width: 100%; height: 20%; cursor: pointer; border: 1px solid #000000; } .panel-body .sec-3:hover{ background-color: #707070; color: #E4E9F7; } .panel-body .sec-2{ position: relative; width: 100%; height: 20%; cursor: pointer; border: 1px solid #000000; } .panel-body .sec-2:hover{ background-color: #707070; color: #E4E9F7; } .panel-body .sec-1{ position: relative; width: 100%; height: 20%; cursor: pointer; border: 1px solid #000000; } .panel-body .sec-1:hover{ background-color: #707070; color: #E4E9F7; } /* PANEL N°2 */ /*Paramètres de la fenêtre modal*/ .panel-2{ position: absolute; width: 10%; height: 100%; padding: 5px; top: 0; right: 0; background: blue; } /*Paramétre titre du panneau*/ .panel-2 .panel-header h1{ font-size: 1.5vh; margin-left: 5px; font-family: Montserrat, sans-serif; font-weight: 500; } /*Paramétre panel header*/ .panel-2 .panel-header{ display: flex; height: 3%; border-radius: 5px 5px 0px 0px; align-items: center; justify-content: space-between; padding: 0.1% 0.1%; background-color: rgb(91, 91, 91); color: rgb(255, 255, 255); box-shadow: 0 0 7px rgba(18,18,18,0.5); } /*Paramètres panel body*/ .panel-2 .panel-body{ height: 97%; background-color: #ffffff; box-shadow: 0 0 7px rgba(18,18,18,0.5); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- &lt;meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"&gt; --&gt; &lt;!----===== CSS ===== --&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;!----===== Boxicons CSS ===== --&gt; &lt;link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'&gt; &lt;title&gt;Sail Vision&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="sidebar"&gt; &lt;div class="logo_content"&gt; &lt;div class="logo"&gt; &lt;i class='bx bx1-c-plus-plus'&gt;&lt;/i&gt; &lt;div class="logo_name"&gt;SailVision&lt;/div&gt; &lt;/div&gt; &lt;i class='bx bx-menu' id="btn"&gt;&lt;/i&gt; &lt;/div&gt; &lt;div class="menu-bar"&gt; &lt;ul class="dash_list"&gt; &lt;li class="divider" data-text="dashboard"&gt;.&lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bx-windows'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;Défaut&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bx-windows'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;GV&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bx-windows'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;Voile d'avant&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="divider" data-text="modification"&gt;.&lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bx-customize modal-trigger'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;Template&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class="bottom_content"&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bxs-bell'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;Notifications&lt;/span&gt; &lt;span class="badge"&gt;1&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;i class='bx bx-cog modal-trigger-param'&gt;&lt;/i&gt; &lt;span class="links_name"&gt;Paramétres&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="home"&gt; &lt;div class="template-1" id="temp1"&gt; &lt;div class="panel-1"&gt; &lt;div class="panel-header"&gt; &lt;h1&gt;Headsail&lt;/h1&gt; &lt;i class='bx bx-cog modal-trigger-panel'&gt;&lt;/i&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="sec-5 modal-trigger-data" id="hs-sec-5"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s5&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-4 modal-trigger-data" id="hs-sec-4"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s4&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-3 modal-trigger-data" id="hs-sec-3"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s3&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-2 modal-trigger-data" id="hs-sec-2"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s2&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-1 modal-trigger-data" id="hs-sec-1"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s1&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-2"&gt; &lt;div class="panel-header"&gt; &lt;h1&gt;Mainsail&lt;/h1&gt; &lt;i class='bx bx-cog modal-trigger-panel'&gt;&lt;/i&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="sec-5 modal-trigger-data" id="ms-sec-5"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s5&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-4 modal-trigger-data" id="ms-sec-4"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s4&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-3 modal-trigger-data" id="ms-sec-3"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s3&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-2 modal-trigger-data" id="ms-sec-2"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s2&lt;/h3&gt; &lt;/div&gt; &lt;div class="sec-1 modal-trigger-data" id="ms-sec-1"&gt; &lt;h1&gt;--&lt;/h1&gt; &lt;h2&gt;TWIST&lt;/h2&gt; &lt;h3&gt;s1&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Regards,</p>
[ { "answer_id": 74654508, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": -1, "selected": false, "text": "var text = \"Hello \\n World!\"\nvar encodedText = encodeURIComponent(text);\nvar file = new Blob([encodedText], {{type:'text/plain'}});\nvar anchor = document.createElement(\"a\");\nanchor.href = URL.createObjectURL(file);\nanchor.download = \"file.log\";\nanchor.click();\n" }, { "answer_id": 74655085, "author": "Senal Weerasinghe", "author_id": 4249637, "author_profile": "https://Stackoverflow.com/users/4249637", "pm_score": 0, "selected": false, "text": "\\n \\\\n log_lines : str = \"Hello \\n World\".replace(\"\\n\", \"\\\\n\")\n\nq.page['meta'].script = ui.inline_script(\n f'''\n var file = new Blob([\"{log_lines}\"], {{type:'text/plain'}});\n var anchor = document.createElement(\"a\");\n anchor.href = URL.createObjectURL(file);\n anchor.download = \"test.log\";\n anchor.click();\n '''\n )\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19930293/" ]
74,654,574
<p>I'm trying to adapt flutter source code to create a side panel. My code is this :</p> <pre><code> class _MyHomePageState extends State&lt;MyHomePage&gt; { final GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = GlobalKey&lt;ScaffoldState&gt;(); void _openEndDrawer(){ _scaffoldKey.currentState!.openEndDrawer(); } void _closeEndDrawer(){ Navigator.of(context).pop(); } @override Widget build(BuildContext context) { return Scaffold( appBar: HEADER(appBar:new AppBar()), drawer:LeftPanel(drawer: new Drawer()), endDrawer: Drawer( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ const Text('This is the Drawer'), ElevatedButton( onPressed: _closeEndDrawer, child: const Text('Close Drawer'), ... body: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SectionTitle(title: &quot;Historial&quot;), Padding( padding: EdgeInsets.fromLTRB(10, 30, 0, 0), child: IconButton ( icon: Icon(Icons.filter_alt), onPressed: _openEndDrawer, ...... </code></pre> <p>when i click on the button flutter throws this error :</p> <pre><code>======== Exception caught by gesture =============================================================== The following _CastError was thrown while handling a gesture: Null check operator used on a null value </code></pre> <p>At this point I don't know what to do ..., Im new codding with flutter</p>
[ { "answer_id": 74654660, "author": "Vignesh KM", "author_id": 4646166, "author_profile": "https://Stackoverflow.com/users/4646166", "pm_score": 2, "selected": false, "text": "key: _scaffoldKey @override\n Widget build(BuildContext context) {\n return Scaffold(\n key: _scaffoldKey,\n appBar: AppBar(title: const Text('Drawer Demo')),\n body: (..)\n );\n }\n" }, { "answer_id": 74654667, "author": "Jasmin Sojitra", "author_id": 11557906, "author_profile": "https://Stackoverflow.com/users/11557906", "pm_score": 2, "selected": true, "text": "Scaffold( key: _scaffoldKey,...\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14889083/" ]
74,654,575
<p>I have a data class that I pull from internet and I want to save room database but there is a problem like that.</p> <p><a href="https://i.stack.imgur.com/oZ5WS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oZ5WS.png" alt="enter image description here" /></a></p> <p>It always gives an error like this, how can I overcome this problem?</p> <p><strong>my room entity class</strong></p> <pre><code>@Entity(tableName = &quot;ExchangeValues&quot;) data class ExchangeEntity( @ColumnInfo(name = &quot;base_code&quot;) val base_code: String, @ColumnInfo(name = &quot;conversion_rates&quot;) val conversion_rates: ConversionRates, @ColumnInfo(name = &quot;result&quot;) val result: String, @PrimaryKey(autoGenerate = true) val uid:Int?=null ) </code></pre> <p><strong>my dao</strong></p> <pre><code>@Dao interface ExchangeDao { @Query(&quot;SELECT * FROM ExchangeValues&quot;) suspend fun getAll() : List&lt;ExchangeEntity&gt; @Query(&quot;UPDATE ExchangeValues SET base_code=:base_code,conversion_rates=:conversion_rates , result=:result&quot;) suspend fun update(base_code:String,conversion_rates:ConversionRates,result:String) } </code></pre> <p><strong>my exchange data class</strong></p> <pre><code>@Serializable data class Exchange( val base_code: String, val conversion_rates: ConversionRates, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) { fun toEntity() = ExchangeEntity( base_code = base_code, conversion_rates = conversion_rates, result = result ) } @Serializable data class ConversionRates( val conversionRates : Map&lt;String,Double&gt; ) </code></pre> <p>I cant use toEntity function in getAll()</p> <p><strong>exchangeRepositoryImpl</strong></p> <pre><code>class ExchangeRepositoryImpl @Inject constructor( private val dao:ExchangeDao ) : ExchangeRepository{ override suspend fun getAll() : Flow&lt;List&lt;Exchange&gt;&gt; { return flow { emit(dao.getAll()) } } override suspend fun update(exchange: Exchange) { dao.update(exchange.base_code,exchange.result,exchange.conversion_rates) } } </code></pre> <p><strong>my exchange converter</strong></p> <pre><code>class ExchangeConverter { @TypeConverter fun fromSource(conversionRates: ConversionRates) : String{ val gson = Gson() return gson.toJson(conversionRates) } @TypeConverter fun toSource(json: String): ConversionRates { val gson = Gson() val typeToken = object : TypeToken&lt;List&lt;ConversionRates&gt;&gt;() {}.type return Gson().fromJson(json, typeToken) } } </code></pre> <p>I wrote a converter like this, but it might not be correct, I'm not so sure. How can I solve this problem?</p>
[ { "answer_id": 74654660, "author": "Vignesh KM", "author_id": 4646166, "author_profile": "https://Stackoverflow.com/users/4646166", "pm_score": 2, "selected": false, "text": "key: _scaffoldKey @override\n Widget build(BuildContext context) {\n return Scaffold(\n key: _scaffoldKey,\n appBar: AppBar(title: const Text('Drawer Demo')),\n body: (..)\n );\n }\n" }, { "answer_id": 74654667, "author": "Jasmin Sojitra", "author_id": 11557906, "author_profile": "https://Stackoverflow.com/users/11557906", "pm_score": 2, "selected": true, "text": "Scaffold( key: _scaffoldKey,...\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18002913/" ]
74,654,620
<p>I do this post because I've a problem...</p> <p>I do a website for a shop and I want see &quot;Open&quot; when the store is open and &quot;Close&quot; when the store is close. Normally. BUT! Because they have a BUT! The store close at 12:30AM and 6:30PM. So, when I do the condition like you can see below(The hour is in French format. 18 = 6PM), my console.log print &quot;Open&quot; IF (hour &lt;= 12) AND IF (minute &lt;= 30). So when it's 10:30AM, console.log = Open, when it's 10:31AM, console.log = Close. Like if it's 11:30AM, console.log = Open, when it's 11:31AM, console.log = Close.</p> <pre><code>function etatMagasin() { let today = new Date() let day = today.getDay() let hour = today.getHours() let minute = today.getMinutes() let second = today.getSeconds() // Lundi à Vendredi if (day &lt; 6) { if (hour &gt;= 9 &amp;&amp; (hour &lt;= 12 &amp;&amp; minute &lt;= 30)) { console.log(&quot;Open&quot;) } else if (hour &gt;= 14 &amp;&amp; (hour &lt;= 18 &amp;&amp; minute &lt;= 30)) { console.log(&quot;Open&quot;) } else {console.log(&quot;Close&quot;)} } else if (day == 6) { if (hour &gt;= 10 &amp;&amp; hour &lt;= 16) { console.log(&quot;Open&quot;) } else {console.log(&quot;Close&quot;)} } else {console.log(&quot;Close&quot;)} console.log(day + &quot;:&quot; + hour + &quot;:&quot; + minute + &quot;:&quot; + second) t = setTimeout(function() {etatMagasin()}, 1000) } etatMagasin() </code></pre> <p>So nobody have an idea how to solve that? I really don't find how to do that... :/</p> <p>Thank you!</p>
[ { "answer_id": 74654653, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": 0, "selected": false, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Check if the store is closing at 12:30AM or 6:30PM\n if ((hour == 12 || hour == 18) && minute > 30) {\n hour += 12; // Add 12 hours to the current hour\n minute = 0; // Set the minutes to 0\n }\n\n // Lundi à Vendredi\n if (day < 6) {\n if (hour >= 9 && hour <= 12) {\n console.log(\"Open\")\n } else if (hour >= 14 && hour <= 18) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else if (day == 6) {\n if (hour >= 10 && hour <= 16) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else {console.log(\"Close\")}\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n} etatMagasin()\n" }, { "answer_id": 74654685, "author": "Nicolás Guglielmi Manent", "author_id": 5577208, "author_profile": "https://Stackoverflow.com/users/5577208", "pm_score": 2, "selected": true, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Convert the hour and minute into a total number of minutes since midnight\n let totalMinutes = hour * 60 + minute\n\n // Lundi à Vendredi\n if (day < 6) {\n if (totalMinutes >= 540 && totalMinutes <= 750) {\n console.log(\"Open\")\n } else if (totalMinutes >= 840 && totalMinutes <= 1110) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else if (day == 6) {\n if (totalMinutes >= 600 && totalMinutes <= 960) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else {\n console.log(\"Close\")\n }\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20292170/" ]
74,654,639
<p>I have an image file <code>day.jpg</code> in <code>Resources</code> folder and I want to access it in the code as <code>string path</code> not as <code>byte[] img</code></p> <p>Here's what I have tried.</p> <pre><code>string dayWallpaper = Assembly.GetExecutingAssembly().Location + @&quot;..\..\Resources\day.jpg&quot;; // Didn't found it </code></pre> <pre><code>string dayWallpaper = Resource.day; // Outputs byte[] and gives me an error </code></pre> <p>Then I tried to convert the <code>byte[]</code> to <code>String</code> didn't work as well</p> <pre><code>static byte[] SliceMe(byte[]? source, int pos) { byte[]? destfoo = new byte[source.Length - pos]; Array.Copy(source, pos, destfoo, 0, destfoo.Length); return destfoo; } static string ByteToPath(path) { String file = Encoding.Unicode.GetString(SliceMe(path, 24)).TrimEnd(&quot;\0&quot;.ToCharArray()); return file } </code></pre> <p>Outputs black screen</p> <p>Later I search for the file</p> <pre><code>if (File.Exists(dayWallpaper)) { do stuff } else { Console.WriteLine(&quot;File does not exists&quot;); } </code></pre> <p>And gives me the else statement.</p>
[ { "answer_id": 74654653, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": 0, "selected": false, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Check if the store is closing at 12:30AM or 6:30PM\n if ((hour == 12 || hour == 18) && minute > 30) {\n hour += 12; // Add 12 hours to the current hour\n minute = 0; // Set the minutes to 0\n }\n\n // Lundi à Vendredi\n if (day < 6) {\n if (hour >= 9 && hour <= 12) {\n console.log(\"Open\")\n } else if (hour >= 14 && hour <= 18) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else if (day == 6) {\n if (hour >= 10 && hour <= 16) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else {console.log(\"Close\")}\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n} etatMagasin()\n" }, { "answer_id": 74654685, "author": "Nicolás Guglielmi Manent", "author_id": 5577208, "author_profile": "https://Stackoverflow.com/users/5577208", "pm_score": 2, "selected": true, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Convert the hour and minute into a total number of minutes since midnight\n let totalMinutes = hour * 60 + minute\n\n // Lundi à Vendredi\n if (day < 6) {\n if (totalMinutes >= 540 && totalMinutes <= 750) {\n console.log(\"Open\")\n } else if (totalMinutes >= 840 && totalMinutes <= 1110) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else if (day == 6) {\n if (totalMinutes >= 600 && totalMinutes <= 960) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else {\n console.log(\"Close\")\n }\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18523789/" ]
74,654,658
<p>How do I create a discriminated union where I can check either for a statusCode of '0000' or not '0000', so that the correct object type is used?</p> <pre><code>type Foo = { statusCode: '0000', something: string } | { statusCode: // any string that is not '0000' somethingElse: string } </code></pre>
[ { "answer_id": 74654653, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": 0, "selected": false, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Check if the store is closing at 12:30AM or 6:30PM\n if ((hour == 12 || hour == 18) && minute > 30) {\n hour += 12; // Add 12 hours to the current hour\n minute = 0; // Set the minutes to 0\n }\n\n // Lundi à Vendredi\n if (day < 6) {\n if (hour >= 9 && hour <= 12) {\n console.log(\"Open\")\n } else if (hour >= 14 && hour <= 18) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else if (day == 6) {\n if (hour >= 10 && hour <= 16) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else {console.log(\"Close\")}\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n} etatMagasin()\n" }, { "answer_id": 74654685, "author": "Nicolás Guglielmi Manent", "author_id": 5577208, "author_profile": "https://Stackoverflow.com/users/5577208", "pm_score": 2, "selected": true, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Convert the hour and minute into a total number of minutes since midnight\n let totalMinutes = hour * 60 + minute\n\n // Lundi à Vendredi\n if (day < 6) {\n if (totalMinutes >= 540 && totalMinutes <= 750) {\n console.log(\"Open\")\n } else if (totalMinutes >= 840 && totalMinutes <= 1110) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else if (day == 6) {\n if (totalMinutes >= 600 && totalMinutes <= 960) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else {\n console.log(\"Close\")\n }\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1487636/" ]
74,654,666
<p>script which loads consecutive numeric values until 0 is encountered, then find the highest value among the given numbers my script below:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!---Napisz skrypt który pozwoli na wczytanie kolejnych wartości liczbowych aż do napotkania 0 następnie wsród podanych liczb znajdź wartość największą--&gt; &lt;script&gt; let tab = [], i = 0, max, min; //wczytywanie danych do { tab[i] = parseInt(prompt(&quot;Podaj jakąś wartość. \n Zero kończy wprowadzanie danych:&quot;)); i++; } while(tab[i-1]); max = tab[0]; min = tab[0]; for(i=1; i &lt; tab.length-1; i++) { if(tab[i]&gt;max) max = tab[i]; } document.write() &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How to fix it?</p> <p>if,else it should show the biggest and the lowest typed number</p>
[ { "answer_id": 74654653, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": 0, "selected": false, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Check if the store is closing at 12:30AM or 6:30PM\n if ((hour == 12 || hour == 18) && minute > 30) {\n hour += 12; // Add 12 hours to the current hour\n minute = 0; // Set the minutes to 0\n }\n\n // Lundi à Vendredi\n if (day < 6) {\n if (hour >= 9 && hour <= 12) {\n console.log(\"Open\")\n } else if (hour >= 14 && hour <= 18) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else if (day == 6) {\n if (hour >= 10 && hour <= 16) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else {console.log(\"Close\")}\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n} etatMagasin()\n" }, { "answer_id": 74654685, "author": "Nicolás Guglielmi Manent", "author_id": 5577208, "author_profile": "https://Stackoverflow.com/users/5577208", "pm_score": 2, "selected": true, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Convert the hour and minute into a total number of minutes since midnight\n let totalMinutes = hour * 60 + minute\n\n // Lundi à Vendredi\n if (day < 6) {\n if (totalMinutes >= 540 && totalMinutes <= 750) {\n console.log(\"Open\")\n } else if (totalMinutes >= 840 && totalMinutes <= 1110) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else if (day == 6) {\n if (totalMinutes >= 600 && totalMinutes <= 960) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else {\n console.log(\"Close\")\n }\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20627074/" ]
74,654,682
<p>I have an orphan branch (let's call it output) which contains the documents generated by templates stored on my main branch. I would like to checkout the commit on output that correspond to a specific commit on main.</p> <p>I settled on using <code>git commit --trailer 'Source: xxxxx'</code> when committing on output where <code>xxxxx</code> is the corresponding commit on main.</p> <p>Is it possible to checkout a commit on output knowing only the value of its trailer?</p>
[ { "answer_id": 74654653, "author": "AschenAI", "author_id": 20665111, "author_profile": "https://Stackoverflow.com/users/20665111", "pm_score": 0, "selected": false, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Check if the store is closing at 12:30AM or 6:30PM\n if ((hour == 12 || hour == 18) && minute > 30) {\n hour += 12; // Add 12 hours to the current hour\n minute = 0; // Set the minutes to 0\n }\n\n // Lundi à Vendredi\n if (day < 6) {\n if (hour >= 9 && hour <= 12) {\n console.log(\"Open\")\n } else if (hour >= 14 && hour <= 18) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else if (day == 6) {\n if (hour >= 10 && hour <= 16) {\n console.log(\"Open\")\n } else {console.log(\"Close\")}\n } else {console.log(\"Close\")}\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n} etatMagasin()\n" }, { "answer_id": 74654685, "author": "Nicolás Guglielmi Manent", "author_id": 5577208, "author_profile": "https://Stackoverflow.com/users/5577208", "pm_score": 2, "selected": true, "text": "function etatMagasin() {\n let today = new Date()\n let day = today.getDay()\n let hour = today.getHours()\n let minute = today.getMinutes()\n let second = today.getSeconds()\n\n // Convert the hour and minute into a total number of minutes since midnight\n let totalMinutes = hour * 60 + minute\n\n // Lundi à Vendredi\n if (day < 6) {\n if (totalMinutes >= 540 && totalMinutes <= 750) {\n console.log(\"Open\")\n } else if (totalMinutes >= 840 && totalMinutes <= 1110) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else if (day == 6) {\n if (totalMinutes >= 600 && totalMinutes <= 960) {\n console.log(\"Open\")\n } else {\n console.log(\"Close\")\n }\n } else {\n console.log(\"Close\")\n }\n\n console.log(day + \":\" + hour + \":\" + minute + \":\" + second)\n\n t = setTimeout(function() {etatMagasin()}, 1000)\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719845/" ]
74,654,696
<p>I'll start by saying I am a Python beginner, I did try and find an answer to this via similar questions but I'm struggling to grasp some of the solutions in order to tailor them for my own use.</p> <p>If I have a Pandas dataframe as follows:</p> <p><a href="https://i.stack.imgur.com/ChZCL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ChZCL.png" alt="enter image description here" /></a></p> <p>What code would I need in order to sort it as per the below whilst excluding the 0 value. I would ideally want to grab the value closest to zero (assuming this is possible).</p> <p><a href="https://i.stack.imgur.com/rdqaz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rdqaz.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74654851, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 3, "selected": true, "text": "abs pandas.DataFrame.sort_values out = df.sort_values(by=\"Score\", key=abs)\n print(out)\n\n Name Score\n3 maggie 0\n2 sally -5\n1 jane -10\n4 peter 15\n6 andy 25\n0 bob -30\n5 mike 50\n" }, { "answer_id": 74654897, "author": "Marty_C137", "author_id": 15417368, "author_profile": "https://Stackoverflow.com/users/15417368", "pm_score": 1, "selected": false, "text": "abs import pandas as pd\n\ndf = pd.DataFrame({'Name': ['Bob', 'Jane', 'Sally', 'Maggie', 'Peter', 'Mike', 'Andy'],\n 'Score': [-30, -10, -5, 0, 15, 50, 25]})\n\ndf.sort_values('Score', key = abs)\n df.reindex(df['Score'].abs().sort_values().index)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711360/" ]
74,654,716
<p>I have a wordpress site/elementor and i want to extend a section/div to the right side outside the main div like in the picture below.</p> <p>At the moment the div has a fixed width of 1600px but the div goes beyond the page, which isn't really best practice and not really responsive.</p> <p>A size of 100% covers only the main div.<a href="https://i.stack.imgur.com/0rSTh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0rSTh.png" alt="enter image description here" /></a></p> <p>Does anyone have a idea how to fix this in css?</p>
[ { "answer_id": 74654851, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 3, "selected": true, "text": "abs pandas.DataFrame.sort_values out = df.sort_values(by=\"Score\", key=abs)\n print(out)\n\n Name Score\n3 maggie 0\n2 sally -5\n1 jane -10\n4 peter 15\n6 andy 25\n0 bob -30\n5 mike 50\n" }, { "answer_id": 74654897, "author": "Marty_C137", "author_id": 15417368, "author_profile": "https://Stackoverflow.com/users/15417368", "pm_score": 1, "selected": false, "text": "abs import pandas as pd\n\ndf = pd.DataFrame({'Name': ['Bob', 'Jane', 'Sally', 'Maggie', 'Peter', 'Mike', 'Andy'],\n 'Score': [-30, -10, -5, 0, 15, 50, 25]})\n\ndf.sort_values('Score', key = abs)\n df.reindex(df['Score'].abs().sort_values().index)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74654716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11480274/" ]