qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,657,044
<p>My task is to insert or update rows in a table2. Table1 contains id's of all employees. That id matches the ID in the table2. Some of the employees in table2 already have the rows I need but some don't. Table2 doesn't contain the ID's of the employees that don't have those rows.</p> <p>My task is to update the rows for the existing ID's and insert for the ones that don't have those rows.</p> <p>I have tried the following statement:</p> <pre><code>MERGE INTO dbo.table2 AS TGT USING (SELECT table1ID FROM dbo.table1) AS SRC ON SRC.table1ID = TGT.table2ID WHEN MATCHED AND table2Code = 'ValueToInsertOrUpdateCode' THEN UPDATE SET table2Value= 'ValueToInsertOrUpdateValue' WHEN NOT MATCHED BY TARGET THEN INSERT (table2Code, table2ID, table2Value) VALUES ('ValueToInsertOrUpdateCode', src.table1ID, 'ValueToInsertOrUpdateValue'); </code></pre> <p>This currently only updates the rows that exist, but doesn't insert the rows for ID's that don't have existing rows.</p>
[ { "answer_id": 74657108, "author": "Dylan Delobel", "author_id": 8338464, "author_profile": "https://Stackoverflow.com/users/8338464", "pm_score": -1, "selected": false, "text": "window.close() window.close() <button onclick=\"window.close()\">Close Window</button>\n button onclick window.close() window.close() window.open() window.close()" }, { "answer_id": 74658640, "author": "Will", "author_id": 19389806, "author_profile": "https://Stackoverflow.com/users/19389806", "pm_score": 0, "selected": false, "text": "button button close__button <button id=\"close__button\" type=\"button\" class=\"close__button\">&times;</button> click \n function close() {\n const popup = document.getElementById('popup').style.display = \"none\";\n }```\n\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18209333/" ]
74,657,057
<p>I am recently want to see and run some other developers code in github and clone it to run in my emulator but it showing some error like this</p> <p>&quot;Running &quot;flutter pub get&quot; in budgex...<br /> Because budgex depends on basic_utils from path which doesn't exist (could not find package basic_utils at &quot;..\packages\basic-utils-3.3.3&quot;), version solving failed. pub get failed (66; Because budgex depends on basic_utils from path which doesn't exist (could not find package basic_utils at &quot;..\packages\basic-utils-3.3.3&quot;), version solving failed.)&quot;</p> <p>i am was trying to install basic_utils package but seem failed how to solve this problem?</p>
[ { "answer_id": 74657108, "author": "Dylan Delobel", "author_id": 8338464, "author_profile": "https://Stackoverflow.com/users/8338464", "pm_score": -1, "selected": false, "text": "window.close() window.close() <button onclick=\"window.close()\">Close Window</button>\n button onclick window.close() window.close() window.open() window.close()" }, { "answer_id": 74658640, "author": "Will", "author_id": 19389806, "author_profile": "https://Stackoverflow.com/users/19389806", "pm_score": 0, "selected": false, "text": "button button close__button <button id=\"close__button\" type=\"button\" class=\"close__button\">&times;</button> click \n function close() {\n const popup = document.getElementById('popup').style.display = \"none\";\n }```\n\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20564203/" ]
74,657,064
<p>I have a file with multiple columns. I want to check the following conditions :</p> <p>file.csv</p> <pre><code>A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2 AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY AIT-A;Y9A;RAIT;VIR;67;217;X;X </code></pre> <ul> <li>if $4 contains <code>UNKNOWN</code> print in a new <code>error</code> column &quot;<code>XTRUC</code> is UNKNOWN &quot;</li> </ul> <p>Example :</p> <pre><code> A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;&quot;XTRUC is UNKNOWN.&quot; </code></pre> <ul> <li>if for the same value in $3 we have different values in $4 print in a new column &quot;multiple <code>XTRUC</code> value for the same <code>FNAME</code>&quot; and if the previous error exist print the new error in a new line in the same cell.</li> </ul> <p>Example :</p> <pre><code>A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;&quot;XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME.&quot; AIT-A;Y9A;RAIT;VIR;67;217;X;X;&quot;multiple XTRUC value for the same FNAME&quot; </code></pre> <ul> <li>if $5 and $6 do not match or one of them or both contain something other tan numbers print the error in a new column &quot;<code>XIZE</code> NOK&quot; and/or &quot;XIZE2 NOK&quot; and/or &quot;XIZE and XIZE2 don't match&quot; in a new line if previous errors exist in the same cell.</li> </ul> <p>Example :</p> <pre><code>A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;&quot;XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK.&quot; AIT-A;Y9A;RAIT;VIR;67;217;X;X;&quot;multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match.&quot; </code></pre> <ul> <li>if $7 and $8 do not match print the error in a new column &quot;ORG and ORG2 don't match&quot; in a new line if previous errors exist in the same cell.</li> </ul> <p>Example and expected result:</p> <pre><code>A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;X;&quot;XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK.&quot; AIT-A;Y9A;RAIT;VIR;67;217;X;X Y;&quot;multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match. ORG and ORG2 don't match.&quot; </code></pre> <p>Visual result from CSV file :</p> <p><a href="https://i.stack.imgur.com/hV4hF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hV4hF.png" alt="enter image description here" /></a></p> <p>I tried to use multiple awk commands like :</p> <pre><code>awk '{if($5!=$6) print &quot;XIZE and XIZE2 do not match&quot; ; elif($5!='^[0-9]+$' print &quot;`XIZE` NOK&quot; ; elif($6!=&quot;^-\?[0-9]+$&quot; print &quot;`XIZE` NOK&quot;}' file.csv </code></pre> <p>It didn't work and with multiple conditions i wonder if there's a simpler way to do it.</p>
[ { "answer_id": 74657537, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 2, "selected": true, "text": "awk -F ';' 'BEGIN {OFS = FS}\n{new_field = NF + 1}\n$5 != $6 {$new_field = $new_field \"XIZE and XIZE2 do not match\\n\"}\n$5 !~ \"^[0-9]+$\" {$new_field = $new_field \"`XIZE` NOK\\n\"}\n$6 !~ \"^-\\\\?[0-9]+$\" {$new_field = $new_field \"`XIZE` NOK\\n\"}\n{print}' file.csv > new-file.csv\n -F OFS !~ else if else awk -F ';' 'BEGIN {OFS = FS}\nNR == 1 {print; next}\n{new_field = NF + 1; delete arr; i = 0; d = \"\"; msg = \"\"}\n$5 != $6 {arr[i++] = \"XIZE and XIZE2 do not match\"}\n$5 !~ \"^[0-9]+$\" {arr[i++] = \"`XIZE` NOK\"}\n$6 !~ \"^-\\\\?[0-9]+$\" {arr[i++] = \"`XIZE` NOK\"}\n{\n if (i > 0) {\n msg = \"\\\"\";\n for (idx in arr) {\n msg = d msg arr[idx];\n d = \"\\n\";\n }\n msg = msg \"\\\"\";\n $new_field = msg;\n };\n \n print\n}' file.csv > new-file.csv\n" }, { "answer_id": 74657711, "author": "petrus4", "author_id": 2953345, "author_profile": "https://Stackoverflow.com/users/2953345", "pm_score": -1, "selected": false, "text": "printf \"AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY\" | tr ';' '\\n' > stack\n\n[[ $(sed -n '/UNKNOWN/p' stack) ]] && printf \"\\\"XTRUC is UNKNOWN\\\"\" >> stack\n\ntr '\\n' ';' < stack > s2\n" }, { "answer_id": 74662994, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "$ cat tst.awk\nBEGIN { FS=OFS=\";\" }\nNR == 1 { print $0, \"error\"; next }\n\n{ numErrs = 0 }\n($4 == \"UNKNOWN\") { errs[++numErrs] = \"XTRUC is UNKNOWN\" }\n($3 != $4) { errs[++numErrs] = \"multiple XTRUC value for the same FNAME\" }\n($5 != $6) || ($5+0 != $5) || ($6+0 != $6) { errs[++numErrs] = \"XIZE and XIZE2 don't match\" }\n($7 != $8) { errs[++numErrs] = \"ORG and ORG2 don't match\" }\n{\n printf \"%s%s\\\"\", $0, OFS\n for ( errNr=1; errNr<=numErrs; errNr++ ) {\n printf \"%s%s\", (errNr>1 ? \"\\n\\t\\t\\t\\t\" : \"\"), errs[errNr]\n }\n print \"\\\"\"\n}\n $ awk -f tst.awk file.csv\nA.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error\nAIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;\"XTRUC is UNKNOWN\n multiple XTRUC value for the same FNAME\n XIZE and XIZE2 don't match\n ORG and ORG2 don't match\"\nAIT-A;Y9A;RAIT;VIR;67;217;X;X;\"multiple XTRUC value for the same FNAME\n XIZE and XIZE2 don't match\"\n \\t\\t\\t\\t \\n printf \"%s%s\", (errNr>1 ? \"\\n\" : \"\"), errs[errNr] ORS \\n ORS=\"\\r\\n\" BEGIN printf \\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11363473/" ]
74,657,065
<p>I am building a CRUD app with React. For the Product Edit page where I want to edit a specific product(clicked product), I need to grab the product's Id. I use the dollar symbol in the code but it doesn't get blue(it doesn't work). I need the URL to change the specific product showing its id when clicked. How to do that? What am I doing wrong?</p> <p>`</p> <pre><code>&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' to={&quot;/product/edit/${product.id}&quot;}&gt;Edit&lt;/Link&gt; &lt;Link className='btn btn-danger m-2'&gt;Delete&lt;/Link&gt; </code></pre> <p>`</p> <pre><code>const onSubmit = async e =&gt; { e.preventDefault(); await axios.put('http://localhost:3001/products/${id}', product); navigate.push(&quot;/&quot;); }; </code></pre> <p>``</p> <p>I thought when I clicked the Edit button I could see the Edit page for the specific product but instead it shows like this: http://localhost:3000/product/edit/$%7Bproduct.id%7D. Not an id after the editing part.</p>
[ { "answer_id": 74657114, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": false, "text": "'' await axios.put(`http://localhost:3001/products/${id}`, product);\n" }, { "answer_id": 74657133, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 1, "selected": false, "text": "` let x = \"def\"\nconsole.log(`abc${x}`);\n// Prints: \"abcdef\"\n let x = \"def\"\nconsole.log(\"abc${x}\");\n// Prints: \"abc${x}\"\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14958858/" ]
74,657,070
<p>I am using Github codespace for creating an automated web scraping application using Webdriver-manager <a href="https://pypi.org/project/webdriver-manager/" rel="nofollow noreferrer">webdriver-manager</a> with Selenium.</p> <p>I have tried: <a href="https://stackoverflow.com/questions/51046454/how-can-we-use-selenium-webdriver-in-colab-research-google-com">How can we use Selenium Webdriver in collab.research.google.com?</a></p> <pre><code>!pip install selenium !apt-get update # to update ubuntu to correctly run apt install !apt install chromium-chromedriver !cp /usr/lib/chromium-browser/chromedriver /usr/bin import sys sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver') from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') wd = webdriver.Chrome('chromedriver',options=chrome_options) wd.get(&quot;https://www.webite-url.com&quot;) </code></pre> <p>But it did not work!<br /> Can you help me in setting up Webdriver-manager github codespaces or share some link?</p>
[ { "answer_id": 74657114, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": false, "text": "'' await axios.put(`http://localhost:3001/products/${id}`, product);\n" }, { "answer_id": 74657133, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 1, "selected": false, "text": "` let x = \"def\"\nconsole.log(`abc${x}`);\n// Prints: \"abcdef\"\n let x = \"def\"\nconsole.log(\"abc${x}\");\n// Prints: \"abc${x}\"\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20148546/" ]
74,657,136
<p>I am trying to return a <code>value</code> from <code>get_queryset</code>.</p> <pre><code>def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') print(self.request.data) last_price = StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price print(last_price) return last_price </code></pre> <p>last price gets printed without an issue.</p> <p>In <code>return</code> I get various errors:</p> <blockquote> <p>TypeError at /api/stock-prices-upload/ 'float' object is not iterable</p> </blockquote> <p>If I try to <code>return</code> till:</p> <pre><code>StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time') </code></pre> <p>It works.</p> <p>As soon as I try to return just the <code>0</code> position queryset I get errors.</p> <p>I assume this is because <code>get_queryset</code> is supposed to return a <code>queryset</code>. Not sure how to return just the value.</p> <p>Edit:</p> <p>I am now trying to get only the latest row i.e. <code>[0]</code> form the data but still getting the same errors i.e.</p> <blockquote> <p>StockPriceModel object is not iterable</p> </blockquote> <pre><code># The current output if I don't add the [0] i.e. try to get the last row of data [{&quot;id&quot;:23,&quot;last_price&quot;:&quot;395.2&quot;,&quot;name&quot;:null,&quot;country&quot;:null,&quot;sector&quot;:null,&quot;industry&quot;:null,&quot;ticker&quot;:&quot;HINDALCO&quot;,&quot;high_price&quot;:null,&quot;last_date_time&quot;:&quot;2022-10-20T15:58:26+04:00&quot;,&quot;created_at&quot;:&quot;2022-10-20T23:20:37.499166+04:00&quot;},{&quot;id&quot;:1717,&quot;last_price&quot;:&quot;437.5&quot;,&quot;name&quot;:null,&quot;country&quot;:null,&quot;sector&quot;:null,&quot;industry&quot;:null,&quot;ticker&quot;:&quot;HINDALCO&quot;,&quot;high_price&quot;:438.9,&quot;last_date_time&quot;:&quot;2022-11-07T15:53:41+04:00&quot;,&quot;created_at&quot;:&quot;2022-11-07T14:26:40.763060+04:00&quot;}] </code></pre> <p>Expected response:</p> <pre><code> [{&quot;id&quot;:1717,&quot;last_price&quot;:&quot;437.5&quot;,&quot;name&quot;:null,&quot;country&quot;:null,&quot;sector&quot;:null,&quot;industry&quot;:null,&quot;ticker&quot;:&quot;HINDALCO&quot;,&quot;high_price&quot;:438.9,&quot;last_date_time&quot;:&quot;2022-11-07T15:53:41+04:00&quot;,&quot;created_at&quot;:&quot;2022-11-07T14:26:40.763060+04:00&quot;}] </code></pre> <p>I have tried using <code>last</code>, <code>get</code> etc. Just won't work.</p>
[ { "answer_id": 74657114, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": false, "text": "'' await axios.put(`http://localhost:3001/products/${id}`, product);\n" }, { "answer_id": 74657133, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 1, "selected": false, "text": "` let x = \"def\"\nconsole.log(`abc${x}`);\n// Prints: \"abcdef\"\n let x = \"def\"\nconsole.log(\"abc${x}\");\n// Prints: \"abc${x}\"\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6387095/" ]
74,657,168
<p>I have a web-app I'm allowing users to add scripts to. These scripts are written in JavaScript and run in the user's browser. When developing new scripts to run locally, I've added a button to the app that allows you to load it from a locally running web server, (i.e. so you'd click on it and enter <a href="http://path.to.my.pc:12345/script.js" rel="nofollow noreferrer">http://path.to.my.pc:12345/script.js</a>). My app will fetch this script and append to the DOM.</p> <p>These scripts are assumed to be ES6 modules and Chrome happily handles those, recursively importing correctly.</p> <p>However when running locally, I also wanted the ability for users to &quot;refresh&quot; as they're developing such that the app will hit their server again to redownload the scripts. Chrome does not seem to want to do this. Specifically, despite the fact that my local test server has specified no-store as Cache-Control, Chrome doesn't care. Even if I cacheBust script.js (i.e.http://blah/script.js?cb=randomInt), this cacheBust parameter is not recursively passed to the imports.</p> <p>Here's the text of my locally running dev server:</p> <pre><code>const express = require(&quot;express&quot;); const serveStatic = require(&quot;serve-static&quot;); const morgan = require(&quot;morgan&quot;); function setHeaders(res, path) { res.setHeader('Cache-Control', 'no-store'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', '*'); } const app = express(); app.use(morgan('combined')); app.use(serveStatic('./', { setHeaders }); app.listen(12345); </code></pre> <p>Is there something else I can do? I really don't want to force my users to run webpack. The idea is to keep this as simple and stupid as possible so they can just focus on writing their scripts.</p> <p>Edit Update: Checking 'Disable Caching' in Devtools also does not cause Chrome to actually... not cache.</p>
[ { "answer_id": 74657114, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": false, "text": "'' await axios.put(`http://localhost:3001/products/${id}`, product);\n" }, { "answer_id": 74657133, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 1, "selected": false, "text": "` let x = \"def\"\nconsole.log(`abc${x}`);\n// Prints: \"abcdef\"\n let x = \"def\"\nconsole.log(\"abc${x}\");\n// Prints: \"abc${x}\"\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2132/" ]
74,657,182
<p>When measuring elapsed time in Python, I use the following method.</p> <pre><code>import time startTime = time.time() nowTime = time.time() - startTime </code></pre> <p>I think this code gets UNIX time in seconds.</p> <p>time.time() returns a Float Value such as this.</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.time() 1541317313.336098 </code></pre> <p>How can I use the same measurement technique in C++ as in Python?</p> <p>I intend to use C++ in a WIndows 64-bit limited environment.</p>
[ { "answer_id": 74657253, "author": "Ram", "author_id": 2756820, "author_profile": "https://Stackoverflow.com/users/2756820", "pm_score": 0, "selected": false, "text": "double now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n" }, { "answer_id": 74657439, "author": "Aconcagua", "author_id": 1312382, "author_profile": "https://Stackoverflow.com/users/1312382", "pm_score": 2, "selected": false, "text": "std::chrono::steady_clock std::chrono::system_clock auto startTime = std::chrono::steady_clock::now();\n\n// work of which the duration is to be measured\n\nauto duration = std::chrono::steady_clock::now() - startTime;\n auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n std::chrono::steady_clock std::system_clock" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12104604/" ]
74,657,195
<p>I am calling an array of all the comments of a poll by using the following code:</p> <pre><code>$poll = Poll::find($id); return view('pages.poll', ['poll' =&gt; $poll, 'comments' =&gt; $poll-&gt;comments]); </code></pre> <p>and the links between Comments and Polls are the following:</p> <p><strong>Comment.php</strong></p> <pre><code>public function poll() { return $this-&gt;belongsTo(Poll::class, 'poll_id'); } </code></pre> <p><strong>Poll.php</strong></p> <pre><code>public function comments() { return $this-&gt;hasMany(Comment::class, 'poll_id'); } </code></pre> <p>Finally, I would like to sort the array <code>comments</code> coming from <code>$poll-&gt;comment</code> by the column <code>likes</code> in the Comment table, something like <code>DB::table('comment')-&gt;orderBy('likes')-&gt;get();</code>.</p> <p><strong>Is there any way to do that?</strong></p>
[ { "answer_id": 74657253, "author": "Ram", "author_id": 2756820, "author_profile": "https://Stackoverflow.com/users/2756820", "pm_score": 0, "selected": false, "text": "double now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n" }, { "answer_id": 74657439, "author": "Aconcagua", "author_id": 1312382, "author_profile": "https://Stackoverflow.com/users/1312382", "pm_score": 2, "selected": false, "text": "std::chrono::steady_clock std::chrono::system_clock auto startTime = std::chrono::steady_clock::now();\n\n// work of which the duration is to be measured\n\nauto duration = std::chrono::steady_clock::now() - startTime;\n auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n std::chrono::steady_clock std::system_clock" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15775091/" ]
74,657,266
<p>here little example of my data.</p> <pre><code>sales.data=structure(list(MDM_Key = c(370L, 370L, 370L, 370L, 370L, 370L, 370L, 371L, 371L, 371L, 371L, 371L, 371L, 371L), sale_count = c(30L, 32L, 32L, 24L, 20L, 15L, 23L, 30L, 32L, 32L, 24L, 20L, 15L, 23L ), iek_disc_price = c(38227.08, 38227.08, 33739.7, 38227.08, 38227.08, 28844.16, 31649.255, 38227.08, 38227.08, 33739.7, 38227.08, 38227.08, 28844.16, 31649.255)), class = &quot;data.frame&quot;, row.names = c(NA, -14L)) </code></pre> <p>i perform regression analysis</p> <pre><code>str(sales.data) m1&lt;-lm(formula=sale_count~iek_disc_price,data=sales.data) summary(m1) </code></pre> <p>But the main difficulty is that for each group (MDM_Key) I don't need all the regression results from the <code>summary</code>, but only one <code>beta</code> coefficient.</p> <p>here</p> <pre><code>B=0.0008559. </code></pre> <p>but then i need calculate mean value for sale_count and the mean for iek_disc_price (also for each mdm key group)</p> <p>so the desired result would be like this</p> <pre><code>MDM_Key beta mean(sale_count) mean(iek_disc_price) 370 0.0008559 25.14 35305 371 0.0008559 25.14 35305 </code></pre> <p>How to take only beta (nor intercept)regression coefficient for each group <code>mdm_key</code> and also for each group, calculate the mean values for sale_count and iek_disc_price to get the summary table indicated above.</p> <p>Thank you for your help.</p>
[ { "answer_id": 74657356, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 2, "selected": false, "text": "MDM_Key library(dplyr)\nlibrary(purrr)\nlibrary(broom)\n\nsales.data %>% \n group_by(MDM_Key) %>% \n mutate(\n mean_sale_count = mean(sale_count),\n mean_iek_disc_price = mean(iek_disc_price)\n ) %>% \n nest(-MDM_Key,-mean_sale_count,-mean_iek_disc_price) %>% \n mutate(\n coefs = map(.x = data,.f = ~tidy(lm(formula=.$sale_count~.$iek_disc_price,data=.)))\n ) %>%\n unnest(coefs) %>% \n filter(term != \"(Intercept)\") %>% \n select(MDM_Key,beta = estimate,mean_sale_count,mean_iek_disc_price)\n\n\n# A tibble: 2 x 4\n# Groups: MDM_Key [2]\n MDM_Key beta mean_sale_count mean_iek_disc_price\n <int> <dbl> <dbl> <dbl>\n1 370 0.000856 25.1 35306.\n2 371 0.000856 25.1 35306.\n" }, { "answer_id": 74657383, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "do.call(rbind, lapply(split(sales.data, sales.data$MDM_Key), function(i) {\n c(beta=coef(lm(sale_count~iek_disc_price, data=i))[2],\n sale_count_mean=mean(i$sale_count), \n iek_disc_price_mean=mean(i$iek_disc_price))\n} ))\n\n beta.iek_disc_price sale_count_mean iek_disc_price_mean\n370 0.0008558854 25.14286 35305.92\n371 0.0008558854 25.14286 35305.92\n" }, { "answer_id": 74658266, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": false, "text": "aggregate lmList [, c(2:1, 3:4)] library(nlme) # lmList\n\nmeans <- aggregate(. ~ MDM_Key, sales.data, mean)\nfm <- lmList(sale_count ~ iek_disc_price | MDM_Key, sales.data)\ncbind(beta = coef(fm)[, 2], means)[, c(2:1, 3:4)]\n\n## MDM_Key beta sale_count iek_disc_price\n## 1 370 0.0008558854 25.14286 35305.92\n## 2 371 0.0008558854 25.14286 35305.92\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4529548/" ]
74,657,268
<p>I want to calculate the minimum and maximum values of array <code>A</code> but I want to exclude all values less than <code>1e-12</code>. I present the current and expected outputs.</p> <pre><code>import numpy as np A=np.array([[9.49108487e-05], [1.05634586e-19], [5.68676707e-17], [1.02453254e-06], [2.48792902e-16], [1.02453254e-06]]) Min=np.min(A) Max=np.max(A) print(Min,Max) </code></pre> <p>The current output is</p> <pre><code>1.05634586e-19 9.49108487e-05 </code></pre> <p>The expected output is</p> <pre><code>1.02453254e-06 9.49108487e-05 </code></pre>
[ { "answer_id": 74657290, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "B = A[A>1e-12]\nMin = np.min(B)\nMax = np.max(B)\nprint(Min, Max)\n 1.02453254e-06 9.49108487e-05 B array([9.49108487e-05, 1.02453254e-06, 1.02453254e-06])" }, { "answer_id": 74657294, "author": "sj95126", "author_id": 13843268, "author_profile": "https://Stackoverflow.com/users/13843268", "pm_score": 2, "selected": false, "text": "1e-12 >>> A[A > 1e-12].min()\n1.02453254e-06\n>>> A[A > 1e-12].max()\n9.49108487e-05\n" }, { "answer_id": 74657566, "author": "Raza Ahmed", "author_id": 11578988, "author_profile": "https://Stackoverflow.com/users/11578988", "pm_score": 1, "selected": false, "text": "arr = np.array([9.49108487e-05,1.05634586e-19,5.68676707e-17,1.02453254e-06,2.48792902e-16,1.02453254e-06]) \nmask = arr > 1e-12 \nMin = np.min(arr[mask]) \nMax = np.max(arr[mask])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20032724/" ]
74,657,295
<p>I've been playing around with reducers in this years's first advent of code challenge, and this code works fine:</p> <pre><code>export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const sumInventoriesReducer = ( acc: number[], element: number[] ): number[] =&gt; [...acc, this.sumCalories(element)]; return Math.max(...elfInventories.reduce(sumInventoriesReducer, [])); } private static sumCalories(inventory: number[]): number { return inventory.reduce((a: number, b: number) =&gt; a + b, 0); } } </code></pre> <p>I then tried to split out the sumInventoriesReducer into it's own private function in the same class. This code does not work:</p> <pre><code>export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, [])); } private static sumInventoriesReducer( acc: number[], element: number[] ): number[] { return [...acc, this.sumCalories(element)]; } private static sumCalories(inventory: number[]): number { return inventory.reduce((a: number, b: number) =&gt; a + b, 0); } } </code></pre> <p>The logic is exactly the same, all that's changed is that it's passed in as a private function (the fact that it's static isn't the reason, tried it without static and got the same error).</p> <p>This is the error:</p> <pre><code> TypeError: Cannot read property 'sumCalories' of undefined 20 | element: number[] 21 | ): number[] { &gt; 22 | return [...acc, this.sumCalories(element)]; | ^ 23 | } 24 | 25 | private static sumCalories(inventory: number[]): number { </code></pre> <p>I want to do this in an OOP way if I can, aware reducers are a staple of functional programming but I feel like I should be able to get this work using a private class function. Can anyone help?</p>
[ { "answer_id": 74657511, "author": "Inbar Azulay", "author_id": 6949373, "author_profile": "https://Stackoverflow.com/users/6949373", "pm_score": -1, "selected": false, "text": "this.sumCalories(element) this.sumCalories(element) number[] return [...acc, ...this.sumCalories(element)];" }, { "answer_id": 74657515, "author": "Nick", "author_id": 17264570, "author_profile": "https://Stackoverflow.com/users/17264570", "pm_score": 2, "selected": true, "text": "constructor() constructor() this instance this export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, this.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n this.sumCalories(element) CalorieCounter.sumCalories(element) export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n calculateMaxInventoryValue export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(CalorieCounter.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12233328/" ]
74,657,323
<pre><code>private void pictureBox2_Paint(object sender, PaintEventArgs e) { Bitmap bmp = new Bitmap(pictureBox1.Image); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. //for (int counter = 2; counter &lt; rgbValues.Length; counter +=64) // rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 0); } </code></pre> <p>i mean to see in pictureBox2 the image get fill slowly like a paint get painted each time a bit. and not at once. with the original colors of the image in pictureBox1 to copy the image in pictureBox1 to pictureBox2 buti nstead in once to make it slowly and each time copy some pixels or one by one until the whole image paint is completed in pictureBox2.</p> <p>I tried this.</p> <p>in time tick event :</p> <pre><code>int cc = 0; private void timer1_Tick(object sender, EventArgs e) { cc++; pictureBox2.Invalidate(); } </code></pre> <p>in pictureBox2 paint event</p> <pre><code>private void pictureBox2_Paint(object sender, PaintEventArgs e) { Bitmap bmp = new Bitmap(pictureBox1.Image); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * cc;//bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 0); } </code></pre> <p>but the code in the pictureBox2 paint event delete the image in the pictureBox2 delete slowly from the top to the bottom.</p> <p>but i want the opposite that it will start that the pictureBox2 is clear and then the image will be painted slowly.</p> <p>i tried to change the line :</p> <pre><code>Bitmap bmp = new Bitmap(pictureBox1.Image); </code></pre> <p>to</p> <pre><code>Bitmap bmp = new Bitmap(512, 512); </code></pre> <p>but then it does nothing in the pictureBox2.</p>
[ { "answer_id": 74657511, "author": "Inbar Azulay", "author_id": 6949373, "author_profile": "https://Stackoverflow.com/users/6949373", "pm_score": -1, "selected": false, "text": "this.sumCalories(element) this.sumCalories(element) number[] return [...acc, ...this.sumCalories(element)];" }, { "answer_id": 74657515, "author": "Nick", "author_id": 17264570, "author_profile": "https://Stackoverflow.com/users/17264570", "pm_score": 2, "selected": true, "text": "constructor() constructor() this instance this export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, this.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n this.sumCalories(element) CalorieCounter.sumCalories(element) export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n calculateMaxInventoryValue export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(CalorieCounter.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14694568/" ]
74,657,326
<p>Im looking to improve my skills with Playwright and I am creating this code to make an &quot;1way-3ways-final way&quot;.</p> <p>error:</p> <blockquote> <p>page.goto: net::ERR_ABORTED at <a href="https://computer-database.gatling.io/computers" rel="nofollow noreferrer">https://computer-database.gatling.io/computers</a> at tests\ways1-3-1.spec.ts:25:18</p> </blockquote> <p>Can anyone help me? </p> <pre><code> test('1 way to 3 and finish in 1', async ({ page }) =&gt; { await page.goto('https://large-type.com/#starting'); await page.waitForTimeout(2000); computerData.forEach(async data =&gt; { await page.goto(&quot;https://computer-database.gatling.io/computers&quot;); await page.click(&quot;#add&quot;); await page.fill(&quot;#name&quot;, data.name); await page.selectOption(&quot;#company&quot;, {label: data.manufacture}); await page.click(&quot;input[type='submit']&quot;); await expect(page.locator(&quot;div.alert-message.warning&quot;)).toContainText(`Done ! Computer ${data.name} has been created`); }); await page.goto('https://large-type.com/#finished'); await page.waitForTimeout(2000); }); </code></pre>
[ { "answer_id": 74657511, "author": "Inbar Azulay", "author_id": 6949373, "author_profile": "https://Stackoverflow.com/users/6949373", "pm_score": -1, "selected": false, "text": "this.sumCalories(element) this.sumCalories(element) number[] return [...acc, ...this.sumCalories(element)];" }, { "answer_id": 74657515, "author": "Nick", "author_id": 17264570, "author_profile": "https://Stackoverflow.com/users/17264570", "pm_score": 2, "selected": true, "text": "constructor() constructor() this instance this export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, this.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n this.sumCalories(element) CalorieCounter.sumCalories(element) export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(this.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n calculateMaxInventoryValue export default class CalorieCounter {\n public static calculateMaxInventoryValue(elfInventories: number[][]): number {\n return Math.max(...elfInventories.reduce(CalorieCounter.sumInventoriesReducer, []));\n }\n\n private static sumInventoriesReducer(\n acc: number[],\n element: number[]\n ): number[] {\n return [...acc, CalorieCounter.sumCalories(element)]; // The problem is here\n }\n\n private static sumCalories(inventory: number[]): number {\n return inventory.reduce((a: number, b: number) => a + b, 0);\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667346/" ]
74,657,339
<p>On <a href="https://en.cppreference.com/w/cpp/ranges" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/ranges</a>, <strong>std::views::counted</strong> is listed in the <strong>range adaptors</strong> section. However, it is not tagged as range adaptor object.</p> <p>I guess that why I can't write using the pipe operator like:</p> <pre><code>std::vector&lt;size_t&gt; vec = {1, 2, 3, 4, 5}; auto view = vec | std::ranges::counted(... ; // does not compile </code></pre> <p>My questions are:</p> <ul> <li>what is a <strong>std::ranges::counted?</strong> Why is it listed in the range adaptor section?</li> <li>what are the use cases? what are the advantages over using <strong>take</strong> and <strong>drop</strong>?</li> </ul>
[ { "answer_id": 74657467, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 1, "selected": false, "text": "#include <ranges>\n#include <iostream>\n \nint main()\n{\n const int a[] = {1, 2, 3, 4, 5, 6, 7};\n for(int i : std::views::counted(a, 3))\n std::cout << i << ' ';\n std::cout << '\\n';\n \n const auto il = {1, 2, 3, 4, 5};\n for (int i : std::views::counted(il.begin() + 1, 3))\n std::cout << i << ' ';\n std::cout << '\\n';\n}\n 1 2 3\n2 3 4\n std::ranges::views::take std::ranges::views::drop std::ranges::views::counted" }, { "answer_id": 74657604, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": false, "text": "views::counted views::counted views::counted subrange(it, it + n) n take_view take_view counted counted n take_view take_view n" }, { "answer_id": 74659162, "author": "康桓瑋", "author_id": 11638718, "author_profile": "https://Stackoverflow.com/users/11638718", "pm_score": 0, "selected": false, "text": "views::counted views::take views::counted views::take auto ints = views::istream<int>(std::cin);\n\nauto counted = views::counted(ints.begin(), 4);\nauto take = views::take(ints, 4);\n\nstatic_assert(ranges::sized_range<decltype(counted)>); // ok\nstatic_assert(ranges::sized_range<decltype(take)>); // failed\n views::take n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15175771/" ]
74,657,346
<p>my list is like this, in example the string is 'a' and 'b' ; i want to return the index of string 'a' and for 'b' then i want to calculate how many time is 'a' repeated in the list1 :</p> <p><code>list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']</code></p> <p>i want to return the order of evry 'a' in list1 the result should be like this :</p> <p><code>a_position=[1,2,4,5,7,8,10,12,13]</code></p> <p>and i want to calculate how many time 'a' is repeated in list1: <code>a_rep=9</code></p>
[ { "answer_id": 74657395, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']\npos = {}\nfor i,c in enumerate(list1, start=1): # 1-based indexing\n pos.setdefault(c, []).append(i)\npos\n# {'a': [1, 2, 4, 5, 7, 8, 10, 12, 13],\n# 'b': [3, 6, 9, 11]}\n\ncounts = {k: len(v) for k,v in pos.items()}\n# {'a': 9, 'b': 4}\n" }, { "answer_id": 74657692, "author": "SomeDude", "author_id": 1410303, "author_profile": "https://Stackoverflow.com/users/1410303", "pm_score": 3, "selected": true, "text": "a_positions = [idx + 1 for idx, el in enumerate(list1) if el == 'a']\na_repitition = len(a_positions)\n [1, 2, 4, 5, 7, 8, 10, 12, 13]\n 9\n collections.Counter from collections import Counter\ncounter = Counter(list1)\n 9\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15068171/" ]
74,657,348
<p>I have a doubt about reading files in C using fgets(). I've seen people use loops in order to do this, but I skip the loop part, doing this instead.</p> <p>What's the difference between using a loop and my way?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { FILE *file = NULL; char string[30]; file = fopen(&quot;test.txt&quot;, &quot;r&quot;); //test.txt contains &quot;Hello world!&quot; if (file == NULL) { puts(&quot;ERROR&quot;); return 1; } fgets(string, 30, file); puts(string); fclose(file); return 0; } </code></pre> <p>Outputs: <code>Hello world!</code></p>
[ { "answer_id": 74657395, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']\npos = {}\nfor i,c in enumerate(list1, start=1): # 1-based indexing\n pos.setdefault(c, []).append(i)\npos\n# {'a': [1, 2, 4, 5, 7, 8, 10, 12, 13],\n# 'b': [3, 6, 9, 11]}\n\ncounts = {k: len(v) for k,v in pos.items()}\n# {'a': 9, 'b': 4}\n" }, { "answer_id": 74657692, "author": "SomeDude", "author_id": 1410303, "author_profile": "https://Stackoverflow.com/users/1410303", "pm_score": 3, "selected": true, "text": "a_positions = [idx + 1 for idx, el in enumerate(list1) if el == 'a']\na_repitition = len(a_positions)\n [1, 2, 4, 5, 7, 8, 10, 12, 13]\n 9\n collections.Counter from collections import Counter\ncounter = Counter(list1)\n 9\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18182271/" ]
74,657,363
<p>I try to combine a list of string to string using reduce function but it doesn't work. I prefer to use reduce function anyway how do I fix this?</p> <pre><code>&gt;&gt; reduce(lambda x, y: x + y + &quot;\n&quot;, [&quot;dog&quot;, &quot;cat&quot;]) # this doesn't work # dogcat &gt;&gt; &quot;\n&quot;.join([&quot;dog&quot;, &quot;cat&quot;]) # this works # dog # cat </code></pre>
[ { "answer_id": 74657394, "author": "azro", "author_id": 7212686, "author_profile": "https://Stackoverflow.com/users/7212686", "pm_score": 2, "selected": false, "text": "reduce(lambda x, y: x + \"\\n\" + y, [\"dog\", \"cat\"])\n" }, { "answer_id": 74657451, "author": "abo", "author_id": 20002585, "author_profile": "https://Stackoverflow.com/users/20002585", "pm_score": 0, "selected": false, "text": "###################### METHOD 1 ######################\n\nstrings = [\"This\", \"is\", \"a\", \"list\", \"of\", \"strings\"]\n\n# join the strings using lambda\njoined = lambda strings: \"\\n\".join(strings)\nprint(joined(strings))\n\n###################### METHOD 2 ######################\n\nmylist = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\n# use list comprehension to join the list of strings\nmystring = \"\\n\".join([str(x) for x in mylist])\nprint(mystring)\n\nstrings = [\"This\", \"is\", \"a\", \"list\", \"of\", \"strings\"]\n\n###################### METHOD 3 ######################\nimport functools\nlist_of_strings = [\"a\", \"b\", \"c\"]\nprint(functools.reduce(lambda x, y: x + \"\\n\" + y, list_of_strings))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9740664/" ]
74,657,402
<p>Code(python):</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk root = tk.Tk() root.geometry(&quot;600x400&quot;) message_var2 = tk.StringVar() def page2(message): print(f'test\n{message}') def getInputtemp(): global message message = message_var2.get() message_var2.set(&quot;&quot;) message_entryi = tk.Entry(root, textvariable=message_var2, font=('calibre', 10, 'normal')) message_entryi.pack() save_btn2 = tk.Button(root, text='Send', command=getInputtemp) save_btn2.pack() if message in ['1886', '2022']: page2(message) root.mainloop() </code></pre> <p>I want to use the variable 'message' outside of the function but it keeps giving me the not defined error</p> <p>Even though I made it a global variable and I'm calling the function before trying to use it I still get the error, Even though after making it global and calling it worked in the past with other things its not working here am I doing something wrong? Did I forget some small tiny detail?</p>
[ { "answer_id": 74657553, "author": "TKirishima", "author_id": 14300637, "author_profile": "https://Stackoverflow.com/users/14300637", "pm_score": 1, "selected": false, "text": "global message None message None ...\nroot.geometry(\"600x400\")\nmessage_var2 = tk.StringVar()\nmessage = None # <<<<<<<<<<\n\ndef page2(message):\n print(f'test\\n{message}')\n...\n" }, { "answer_id": 74657614, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 3, "selected": true, "text": "getInputtemp save_btn2 if if getInputtemp def getInputtemp():\n #global message \n #Then you would no longer need message as a global variable\n message = message_var2.get()\n message_var2.set(\"\")\n if message in ['1886', '2022']:\n page2(message)\n if getInputtemp() #The function is called to create message as global variable\nif message in ['1886', '2022']:\n page2(message)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533292/" ]
74,657,407
<p>In Google Sheet, I would like to take the input of a cell, make a calculation, and display the result in the same cell in a different format. This would likely always be a percentage value that I would use conditional formatting to color the cell to provide a 'dashboard' view of statistics.</p> <p>Example would be usage statistics for a month.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Assets</th> <th>Records</th> </tr> </thead> <tbody> <tr> <td>limit</td> <td>50</td> <td>1000</td> </tr> <tr> <td>November</td> <td>29</td> <td>295</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Assets</th> <th>Records</th> </tr> </thead> <tbody> <tr> <td>limit</td> <td>50</td> <td>1000</td> </tr> <tr> <td>November</td> <td>58%</td> <td>30%</td> </tr> </tbody> </table> </div> <p>I found a Quora post detailing how to create your own scripts, so I believe I have the baseline of taking and modifying content of a cell:</p> <pre><code>function onEdit() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var cell = ss.getActiveSelection(); var cell_input = cell.getValue(); var cell_address = cell.getA1Notation() var cell2 = ss.getRange(cell_address); cell2.setFormula('=2*'+cell_input) } </code></pre> <p>In this example, I'm unsure how to reference the cell it should be dividing against.</p>
[ { "answer_id": 74657553, "author": "TKirishima", "author_id": 14300637, "author_profile": "https://Stackoverflow.com/users/14300637", "pm_score": 1, "selected": false, "text": "global message None message None ...\nroot.geometry(\"600x400\")\nmessage_var2 = tk.StringVar()\nmessage = None # <<<<<<<<<<\n\ndef page2(message):\n print(f'test\\n{message}')\n...\n" }, { "answer_id": 74657614, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 3, "selected": true, "text": "getInputtemp save_btn2 if if getInputtemp def getInputtemp():\n #global message \n #Then you would no longer need message as a global variable\n message = message_var2.get()\n message_var2.set(\"\")\n if message in ['1886', '2022']:\n page2(message)\n if getInputtemp() #The function is called to create message as global variable\nif message in ['1886', '2022']:\n page2(message)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4297385/" ]
74,657,410
<p>I'm beginning my path in Typescript and got a problem that i can solve. I'm trying to acess one index of one array inside the return of a API call. In the console the value is printed perfectly, but appears this message of error.</p> <p>This is the interface i made :</p> <pre><code> interface Data { list: [{ main: { temp: number; temp_min: number; temp_max: number; } weather: [{ main: string; description: string; }] clouds: [{ all: number; }] dt_txt: string; }] dt: number; } </code></pre> <p>And that is the console.log I'm using:</p> <pre><code> data?.list[1].main.temp_min </code></pre> <p>This is the error that appears:</p> <blockquote> <pre><code>TS2532: Object is possibly 'undefined'. 109 | 110 | &lt;&gt; &gt; 111 | {console.log(data?.list[1].main.temp_min)} | ^^^^^^^^^^^^^ 112 | {console.log(data?.list[3]?.main)} 113 | 114 | &lt;/&gt; </code></pre> </blockquote> <p>And that is the return value from the <code>console.log</code>:</p> <p><img src="https://i.stack.imgur.com/nYz9J.png" alt="enter image description here" /></p> <p>Could you guys help me?</p>
[ { "answer_id": 74657553, "author": "TKirishima", "author_id": 14300637, "author_profile": "https://Stackoverflow.com/users/14300637", "pm_score": 1, "selected": false, "text": "global message None message None ...\nroot.geometry(\"600x400\")\nmessage_var2 = tk.StringVar()\nmessage = None # <<<<<<<<<<\n\ndef page2(message):\n print(f'test\\n{message}')\n...\n" }, { "answer_id": 74657614, "author": "Sam", "author_id": 16660603, "author_profile": "https://Stackoverflow.com/users/16660603", "pm_score": 3, "selected": true, "text": "getInputtemp save_btn2 if if getInputtemp def getInputtemp():\n #global message \n #Then you would no longer need message as a global variable\n message = message_var2.get()\n message_var2.set(\"\")\n if message in ['1886', '2022']:\n page2(message)\n if getInputtemp() #The function is called to create message as global variable\nif message in ['1886', '2022']:\n page2(message)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20132466/" ]
74,657,428
<p>It’s tedious that I have to copy-paste a function like loadInitialValue(), loadInitialValue2(), loadInitialValue3(), so on and so forth. This is my repetitive code (if you click “Mark as Read,” the title of the short story grays out; otherwise, it goes back to white again):</p> <pre><code>function readunread() { // Short Story 1 currentvalue = document.getElementById(&quot;readunread&quot;).value; if (currentvalue == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread&quot;).value = &quot;Mark as Read&quot;; document.getElementsByClassName(&quot;read&quot;).value = &quot;White&quot;; localStorage.setItem(&quot;readunread&quot;, &quot;Mark as Read&quot;); localStorage.setItem(&quot;read&quot;, &quot;White&quot;); } else { document.getElementById(&quot;readunread&quot;).value = &quot;Mark as Unread&quot;; document.getElementsByClassName(&quot;read&quot;).value = &quot;Gray&quot;; localStorage.setItem(&quot;readunread&quot;, &quot;Mark as Unread&quot;); localStorage.setItem(&quot;read&quot;, &quot;Gray&quot;); } } function readunread2() { // Short Story 2 currentvalue2 = document.getElementById(&quot;readunread2&quot;).value; if (currentvalue2 == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread2&quot;).value = &quot;Mark as Read&quot;; document.getElementsByClassName(&quot;read2&quot;).value = &quot;White&quot;; localStorage.setItem(&quot;readunread2&quot;, &quot;Mark as Read&quot;); localStorage.setItem(&quot;read2&quot;, &quot;White&quot;); } else { document.getElementById(&quot;readunread2&quot;).value = &quot;Mark as Unread&quot;; document.getElementsByClassName(&quot;read2&quot;).value = &quot;Gray&quot;; localStorage.setItem(&quot;readunread2&quot;, &quot;Mark as Unread&quot;); localStorage.setItem(&quot;read2&quot;, &quot;Gray&quot;); } } function readunread3() { // Short Story 3 currentvalue3 = document.getElementById(&quot;readunread3&quot;).value; if (currentvalue3 == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread3&quot;).value = &quot;Mark as Read&quot;; document.getElementsByClassName(&quot;read3&quot;).value = &quot;White&quot;; localStorage.setItem(&quot;readunread3&quot;, &quot;Mark as Read&quot;); localStorage.setItem(&quot;read3&quot;, &quot;White&quot;); } else { document.getElementById(&quot;readunread3&quot;).value = &quot;Mark as Unread&quot;; document.getElementsByClassName(&quot;read3&quot;).value = &quot;Gray&quot;; localStorage.setItem(&quot;readunread3&quot;, &quot;Mark as Unread&quot;); localStorage.setItem(&quot;read3&quot;, &quot;Gray&quot;); } } function loadInitialValue() { // Short Story 1 const localValue = localStorage.getItem(&quot;readunread&quot;); console.log(localValue); if (localValue == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread&quot;).value = &quot;Mark as Unread&quot;; } else { document.getElementById(&quot;readunread&quot;).value = &quot;Mark as Read&quot;; } } function loadInitialValue2() { // Short Story 2 const localValue2 = localStorage.getItem(&quot;readunread2&quot;); console.log(localValue2); if (localValue2 == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread2&quot;).value = &quot;Mark as Unread&quot;; } else { document.getElementById(&quot;readunread2&quot;).value = &quot;Mark as Read&quot;; } } function loadInitialValue3() { // Short Story 3 const localValue3 = localStorage.getItem(&quot;readunread3&quot;); console.log(localValue3); if (localValue3 == &quot;Mark as Unread&quot;) { document.getElementById(&quot;readunread3&quot;).value = &quot;Mark as Unread&quot;; } else { document.getElementById(&quot;readunread3&quot;).value = &quot;Mark as Read&quot;; } } function loadFontColor() { const localValue = localStorage.getItem(&quot;read&quot;); const localValue2 = localStorage.getItem(&quot;read2&quot;); const localValue3 = localStorage.getItem(&quot;read3&quot;); const fontColor = document.getElementsByClassName(&quot;read&quot;); const fontColor2 = document.getElementsByClassName(&quot;read2&quot;); const fontColor3 = document.getElementsByClassName(&quot;read3&quot;); console.log(localValue); console.log(localValue2); console.log(localValue3); if (localValue == &quot;Gray&quot;) { // Short Story 1 document.getElementsByClassName(&quot;read&quot;).value = &quot;Gray&quot;; fontColor[0].style.color = &quot;gray&quot;; } else { document.getElementsByClassName(&quot;read&quot;).value = &quot;White&quot;; fontColor[0].style.color = &quot;&quot;; } if (localValue2 == &quot;Gray&quot;) { // Short Story 2 document.getElementsByClassName(&quot;read2&quot;).value = &quot;Gray&quot;; fontColor2[0].style.color = &quot;gray&quot;; } else { document.getElementsByClassName(&quot;read2&quot;).value = &quot;White&quot;; fontColor2[0].style.color = &quot;&quot;; } if (localValue3 == &quot;Gray&quot;) { // Short Story 3 document.getElementsByClassName(&quot;read3&quot;).value = &quot;Gray&quot;; fontColor3[0].style.color = &quot;gray&quot;; } else { document.getElementsByClassName(&quot;read3&quot;).value = &quot;White&quot;; fontColor3[0].style.color = &quot;&quot;; } } </code></pre> <pre><code>body { background:black; } .button { border: none; color: white; font-family: Corbel; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; background-color: black; } input[type=button] { font-size: 20px; font-family: Corbel; text-decoration: none; color: white; border: none; background: none; cursor: pointer; margin: 0; padding: 0; .shortstories { font-family: Corbel; font-size: 25px; } </code></pre> <pre><code>&lt;input type = &quot;button&quot; value = &quot;Mark as Read&quot; id = &quot;readunread&quot; onclick = &quot;readunread();&quot;&gt; &lt;input type = &quot;button&quot; value = &quot;Mark as Read&quot; id = &quot;readunread2&quot; onclick = &quot;readunread2();&quot;&gt; &lt;input type = &quot;button&quot; value = &quot;Mark as Read&quot; id = &quot;readunread3&quot; onclick = &quot;readunread3();&quot;&gt; &lt;script&gt; loadInitialValue(); &lt;/script&gt; &lt;script&gt; loadInitialValue2(); &lt;/script&gt; &lt;script&gt; loadInitialValue3(); &lt;/script&gt; &lt;div class = &quot;shortstories&quot;&gt; &lt;table cellspacing = &quot;50&quot; cellpadding = &quot;5&quot; border-collapse = &quot;collapse&quot;, border = &quot;0&quot;, style = &quot;text-align: justify;&quot;&gt; &lt;tr&gt; &lt;td class = &quot;read&quot;&gt;&lt;p&gt;&lt;a href = &quot;shortstory1.html&quot;&gt; Short Story 1 &lt;/a&gt;&lt;/p&gt;&lt;/td&gt; &lt;td class = &quot;read2&quot;&gt;&lt;p&gt;&lt;a href = &quot;shortstory2.html&quot;&gt; Short Story 2 &lt;/a&gt;&lt;/p&gt;&lt;/td&gt; &lt;td class = &quot;read3&quot;&gt;&lt;p&gt;&lt;a href = &quot;shortstory3.html&quot;&gt; Short Story 3 &lt;/a&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;script&gt; loadFontColor(); &lt;/script&gt; </code></pre> <p>Do I have no choice but to replicate values over and over again? I think it’ll be hard if there are 100 short stories; I’ll write a function like “loadInitialValue100().” Is there a dynamic way to do this?</p>
[ { "answer_id": 74657459, "author": "Emilien", "author_id": 18143359, "author_profile": "https://Stackoverflow.com/users/18143359", "pm_score": 3, "selected": true, "text": "function readunread(a) { // Short Story \n const elemId = \"readunread\"+a;\n currentvalue = document.getElementById(elemId).value;\n if (currentvalue == \"Mark as Unread\") {\n document.getElementById(elemId).value = \"Mark as Read\";\n document.getElementsByClassName(\"read\"+a).value = \"White\";\n localStorage.setItem(elemId, \"Mark as Read\");\n localStorage.setItem(\"read\"+a, \"White\");\n } else {\n document.getElementById(elemId).value = \"Mark as Unread\";\n document.getElementsByClassName(\"read\"+a).value = \"Gray\";\n localStorage.setItem(elemId, \"Mark as Unread\");\n localStorage.setItem(\"read\"+a, \"Gray\");\n }\n}\n// and instead of calling readunread3(), you call readunread(3)\n for(let i = 1;i<=100;i++)\n{\n loadinitialvalues(i);\n}\n" }, { "answer_id": 74657793, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "function readunread(id,cls,valToCheck,color,bool) { \n currentvalue3 = document.getElementById(id).value;\n if (bool && currentvalue3 == valToCheck) {\n document.getElementById(id).value = valToCheck;\n document.getElementsByClassName(cls).value = color;\n localStorage.setItem(id, valToCheck);\n localStorage.setItem(cls, color);\n return;\n } \n \n document.getElementById(\"readunread3\").value = valToCheck;\n document.getElementsByClassName(\"read3\").value = color;\n localStorage.setItem(\"readunread3\", valToCheck);\n localStorage.setItem(\"read3\", color);\n}\n\n//works for if\nreadunread(\"readunread3\",\"read3\",\"Mark as Unread\",\"White\",true);\n\n//works for else\nreadunread(\"readunread3\",\"read3\",\"Mark as Unread\",\"Grey\",false);" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20615177/" ]
74,657,444
<p>I just want to clear my doubts on the <strong>fromIntegral</strong> type in Haskell.</p> <p>The output for these 2 euclidean distance functions are the same, so what's the point of putting fromIntegral? Like they both give floating point values of the euclidean distances.</p> <p>Also, for the type definition of my function distance2 which uses the fromIntegral type, why is it (Floating a1, Integral a2) and then =&gt; (a2, a2) -&gt; (a2, a2) -&gt; a1? I just don't quite get the interpretation of it here.</p> <pre><code>distance2 :: (Floating a1, Integral a2) =&gt; (a2, a2) -&gt; (a2, a2) -&gt; a1 distance2 (x1, y1) (x2, y2) = sqrt (fromIntegral ((x2-x1)^2 + (y2 - y1)^2)) distance3 :: Floating a =&gt; (a, a) -&gt; (a, a) -&gt; a distance3 (x1, y1) (x2, y2) = sqrt ((x2-x1)^2 + (y2 - y1)^2) </code></pre> <p>Could someone please help with an explanation, thank you :)</p>
[ { "answer_id": 74657613, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "fromIntegral Integral a => a Floating a => a sqrt fromIntegral (Integral a, Num b) => a -> b Integral a b Num Floating Num Fractional fromIntegral Floating a => a" }, { "answer_id": 74657911, "author": "Daniel Wagner", "author_id": 791604, "author_profile": "https://Stackoverflow.com/users/791604", "pm_score": 2, "selected": false, "text": "> distance3 (pi, 0) (0, 0)\n3.141592653589793\n> distance2 (pi, 0) (0, 0)\n<interactive>:2:1: error:\n • Could not deduce (Integral a20) arising from a use of ‘distance2’\n from the context: Floating a1\n bound by the inferred type of it :: Floating a1 => a1\n<snipped considerable additional error text>\n distance2 fromIntegral sqrt distance2 (Int, Int) -> (Int, Int) -> Double\n(Integer, Integer) -> (Integer, Integer) -> Double\n(Word, Word) -> (Word, Word) -> Float\n distance2 (Floating float, Integral int) => (int, int) -> (int, int) -> float\n" }, { "answer_id": 74663106, "author": "comingstorm", "author_id": 210211, "author_profile": "https://Stackoverflow.com/users/210211", "pm_score": 0, "selected": false, "text": "Integral Integral toInteger Integer Num Num fromInteger Integer Num fromIntegral fromIntegral = fromInteger . toInteger\n Integral Num Integral fromIntegral toInteger Integral Floating sqrt fromIntegral fromInteger Num" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20613671/" ]
74,657,455
<p>i have a problem with my sed command. I have the following file and want to replace line number 4.</p> <p>text.txt content:</p> <pre><code> 1 Hi World! 2 Okey 3 Test 4 ;date.timezone = </code></pre> <p>cmd command:</p> <pre><code>sed -i -e &quot;s/;date.timezone =/date.timezone = Europe/Berlin/&quot; text.txt </code></pre> <p>Because my replacement holds a / inside, the sed command cant execute properly because of <code>Europe/Berlin</code>.</p> <p>My Folder Structure:</p> <pre><code>folder structrure /Users/user/dev/repos/docker └── text.txt </code></pre> <p>My fix would be to ignore the / between Europe and Berlin. I didn't really find the answer in the web, that's why I reach out for you?</p> <p>Output:</p> <pre><code>sed: 1: &quot;s/;date.timezone =/date ...&quot;: bad flag in substitute command: 'B' </code></pre>
[ { "answer_id": 74657613, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 1, "selected": false, "text": "fromIntegral Integral a => a Floating a => a sqrt fromIntegral (Integral a, Num b) => a -> b Integral a b Num Floating Num Fractional fromIntegral Floating a => a" }, { "answer_id": 74657911, "author": "Daniel Wagner", "author_id": 791604, "author_profile": "https://Stackoverflow.com/users/791604", "pm_score": 2, "selected": false, "text": "> distance3 (pi, 0) (0, 0)\n3.141592653589793\n> distance2 (pi, 0) (0, 0)\n<interactive>:2:1: error:\n • Could not deduce (Integral a20) arising from a use of ‘distance2’\n from the context: Floating a1\n bound by the inferred type of it :: Floating a1 => a1\n<snipped considerable additional error text>\n distance2 fromIntegral sqrt distance2 (Int, Int) -> (Int, Int) -> Double\n(Integer, Integer) -> (Integer, Integer) -> Double\n(Word, Word) -> (Word, Word) -> Float\n distance2 (Floating float, Integral int) => (int, int) -> (int, int) -> float\n" }, { "answer_id": 74663106, "author": "comingstorm", "author_id": 210211, "author_profile": "https://Stackoverflow.com/users/210211", "pm_score": 0, "selected": false, "text": "Integral Integral toInteger Integer Num Num fromInteger Integer Num fromIntegral fromIntegral = fromInteger . toInteger\n Integral Num Integral fromIntegral toInteger Integral Floating sqrt fromIntegral fromInteger Num" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18246292/" ]
74,657,456
<p>I'm new to yml language and just setup a github actions flow which works well manually, however when I try to make it work on pushing of specific tag it doesn't work:</p> <p>I'm trying to have the yml execute after doing</p> <pre><code>git commit -am &quot;my commit&quot; git tag cicd11 git push </code></pre> <p>and my .yml starts with this:</p> <pre><code>on: push: tags: - cicd** </code></pre> <p>I've read many questions on SO, but noone seems to be doing push on tags and this is supposed to be possible according to the manual. Thank you.</p>
[ { "answer_id": 74657920, "author": "myz540", "author_id": 7829963, "author_profile": "https://Stackoverflow.com/users/7829963", "pm_score": 1, "selected": false, "text": "A tag named v2 (refs/tags/v2) **cicd** refs/tags/cicd**" }, { "answer_id": 74658330, "author": "David A", "author_id": 2606914, "author_profile": "https://Stackoverflow.com/users/2606914", "pm_score": 0, "selected": false, "text": "--tags git commit -am \"my commit\"\ngit tag cicd11\ngit push --tags\n on:\n push:\n tags:\n - cicd**\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2606914/" ]
74,657,464
<p>Simple Map here:</p> <pre><code>Map map = Map&lt;int, String&gt;{}; </code></pre> <p>I can populate it:</p> <pre><code>map = {1: 'c', 2: 'dart', 3: 'flutter'}; </code></pre> <p>Here I need to specify a KEY. I would like to know on how to get an auto key.</p> <p>I cannot use map.lenght because whenever I will delete e.g. the second item (2) the third will remain 3 and map.lenght will overwrite that key.</p> <p>As the @eamirho3ein answer I tried this:</p> <pre><code> //&amp; Maps Map map = &lt;int, Ingredient&gt;{}; Map&lt;int, T&gt; addToMap&lt;T&gt;(Map&lt;int, T&gt; map, T newItem) { var list = map.entries.map((e) =&gt; e.value).toList(); list.add(newItem); var newIndex = 1; return Map.fromIterable(list, key: (item) =&gt; newIndex++, value: (item) =&gt; item); } Map&lt;int, Ingredient&gt; result = addToMap&lt;Ingredient&gt;( map, //Error here Ingredient( name: &quot;Pizza&quot;, kcal: 100, carbohydrates: 50, proteins: 35, lipids: 23, fibers: 12, date: DateTime.now(), bottomTabIndex: 0, leftTabIndex: 0)); </code></pre> <p>But I receive this error on map(indicated):</p> <blockquote> <p>The argument type 'Map&lt;dynamic, dynamic&gt;' can't be assigned to the parameter type 'Map&lt;int, Ingredient&gt;'.</p> </blockquote> <p>This is my simple class:</p> <pre><code>class Ingredient { String? name; int? kcal; int? carbohydrates; int? proteins; int? lipids; int? fibers; int? leftTabIndex; int? bottomTabIndex; DateTime? date; Ingredient( {this.name, this.kcal, this.carbohydrates, this.proteins, this.lipids, this.fibers, this.leftTabIndex, this.bottomTabIndex, this.date}); } </code></pre>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4651768/" ]
74,657,469
<p>I'm pretty new parsing HTML documents and I'm stuck in this problem.</p> <p>Giving an HTML document made like this:</p> <pre><code>&lt;h3&gt;File: /home/finxadm/XMW.SET.OXF.CPP/LangCpp/oxf/OMMainThread.h&lt;/h3&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;h4&gt;Function: ::OMMainThread::destroyThread()&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;h3&gt;File: /home/finxadm/XMW.SET.OXF.CPP/LangCpp/oxf/OMNullValue.h&lt;/h3&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;h4&gt;Function: ::OMNullValue&lt;p{c::Ping}&gt;::get()&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;h4&gt;Function: ::OMNullValue&lt;p{c::Ping}&gt;::initNullBlock()&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;5&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;h4&gt;Function: ::OMNullValue&lt;p{c::Pong}&gt;::get()&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;h4&gt;Function: ::OMNullValue&lt;p{c::Pong}&gt;::initNullBlock()&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;5&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;h3&gt;File: /home/finxadm/XMW.SET.OXF.CPP/LangCpp/oxf/OMStaticArray.h&lt;/h3&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;h4&gt;Function: ::OMStaticArray&lt;p{c::Ping}&gt;::@constructor(,ni)&lt;/h4&gt; &lt;table class=&quot;metricstable&quot; width=&quot;100%&quot;&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Metric&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;CALLS (STCAL)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;v(G) (STCYC)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;GOTO (STGTO)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;RETURN (STM19)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;LEVEL (STMIF)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PARAM (STPAR)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;PATH (STPTH)&lt;/td&gt;&lt;td class=&quot;lightheader&quot; align=&quot;right&quot;&gt;STMT (STST3)&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class=&quot;lightheader&quot; align=&quot;left&quot;&gt;Values&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;4&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre> <p>what I need is to create a data structure made like this:</p> <p>&lt;Filename, function (related to that file), STCYC value of that function&gt;</p> <p>I tried iterating like this:</p> <pre><code>for files_and_functions in soup.find_all(['h3','h4','table']): for elem in files_and_functions: valore = elem.text </code></pre> <p>and asking for each elem if it's a function, a file or a STCYC value, but I can't get out of it. Is there anyone who can obtain these information from this terrible HTML? Thank you very much!</p>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17318257/" ]
74,657,502
<p>I need a predicate that gives me all the suffixes of a list on Prolog.</p> <p>For example:</p> <pre><code>?- suffixes([1,2,3], X). X = [[1, 2, 3], [2, 3], [3], []]. </code></pre> <p>I tried this and it works, but I can't use the findall function to get all of them in a single list.</p> <pre><code>suffix(Xs, Ys) :- append(_,Ys,Xs). suffixes(Xs, Ss) :- findall(S, suffix(Xs,S), Ss). </code></pre>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667440/" ]
74,657,554
<p>I have a question about the <code>STRING_SPLIT</code>. I need to separate phrases inside a String, separated by comma. The problem is that some of these phrases have around them, more commas.</p> <p>This is an example:</p> <ol> <li>Archiviazione, 2. Conservazione in archivi**,** ad accesso selezionato, 3. Conservazione in contenitori muniti di serratura, 4. Controllo degli accessi fisici, 5. Controllo degli accessi logici, 6. Custodia atti e documenti, 7. Formazione degli incaricati, 8. Sicurezza dei siti web</li> </ol> <p>As you can see, within item 2 there is a comma that hinders the process of division by comma. How can I overcome this situation?</p> <p>Another question would be: is there a way to pass a parameter to the <code>String_Split</code> where the number with dot next can serve as a separator instead of the comma?</p> <p>Thank you very much from now on!</p> <p>With the query:</p> <pre><code>select * from string_split('1. Archiviazione, 2. Conservazione in archivi, ad accesso selezionato, 3. Conservazione in contenitori muniti di serratura, 4. Controllo degli accessi fisici, 5. Controllo degli accessi logici, 6. Custodia atti e documenti, 7. Formazione degli incaricati, 8. Sicurezza dei siti web', ',') </code></pre> <p>I got this result:</p> <p><img src="https://i.stack.imgur.com/EJQmp.png" alt="enter image description here" /></p>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667137/" ]
74,657,570
<p>I have a listbox and a (annual holiday) date picker. The user chooses the date and adds it to the Listbox. I then want to sort the Listbox from earliest to latest date. I tried using sorted Listbox but that did not work as it sorts like they are alphabetic strings. I then used unsorted Listbox and found some code and changed it to sort the box manually but again this is alphabetical. I am using the date as dd/mm/yyyy each date on a new line e.g.</p> <p>If I have:</p> <pre><code>01/01/2023 02/12/2022 23/12/2022 24/12/2022 </code></pre> <p>then I want the listbox to show me</p> <pre><code>02/12/2022 23/12/2022 24/12/2022 01/01/2023 </code></pre> <p>what I get is the following where it sorts from left to right rather than year then month then day</p> <pre><code>01/01/2023 02/12/2022 23/12/2022 24/12/2022 </code></pre> <p>At present I use the following code to add and then sort but there must be an easy way to sort this.</p> <pre><code>void Btn_add_holidayClick(object sender, EventArgs e) { lstbx_annual_hol.Items.Add(DatePick_Hol_Date.Value.Day.ToString(&quot;D2&quot;) + &quot;/&quot; + DatePick_Hol_Date.Value.Month.ToString(&quot;D2&quot;) + &quot;/&quot; + DatePick_Hol_Date.Value.Year.ToString() +&quot;\n&quot;); SortAnnualHoliday(); } void SortAnnualHoliday() { ArrayList arList = new ArrayList(); foreach (object obj in lstbx_annual_hol.Items) { arList.Add(obj); } arList.Sort(); lstbx_annual_hol.Items.Clear(); foreach(object obj in arList) { lstbx_annual_hol.Items.Add(obj); } } </code></pre> <p>Thanks in advance for any advice and solutions even if you think I should do it a completely different way.</p>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3884423/" ]
74,657,579
<p>Here is my code</p> <pre><code>&lt;Image resizeMode=&quot;contain&quot; source={require('../../assets/splash.gif')} style={{ width: '100%', alignSelf: 'center' }} /&gt; </code></pre> <p>How can I control the gif to loop only once while first render? thanks.</p>
[ { "answer_id": 74657622, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "index autoKey() int index = 0;\nautoKey() {\n return ++index;\n}\n\nMap<int, String> map = {};\nmap = {autoKey(): 'c', autoKey(): 'dart', autoKey(): 'flutter'};\n\nprint(map); {1: c, 2: dart, 3: flutter}\n" }, { "answer_id": 74657714, "author": "Emc2Theory", "author_id": 4651768, "author_profile": "https://Stackoverflow.com/users/4651768", "pm_score": 0, "selected": false, "text": "int getNewKey(Map map) {\n if (map.isEmpty) {\n return 0; // or 1, this is the first item I insert\n } else {\n return map.keys.last + 1;\n }\n}\n {(map.keys.last + 1) : 'c', (map.keys.last + 1) : 'dart', (map.keys.last + 1) : 'flutter'}\n" }, { "answer_id": 74657724, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 3, "selected": true, "text": "Map<int, T> removeFromMap<T>(Map<int, T> map, int index) {\n var list = map.entries.map((e) => e.value).toList();\n list.removeAt(index);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n } \n var result = removeFromMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 1);\nprint(\"result = $result\"); //result = {1: c, 2: flutter}\n Map<int, T> addToMap<T>(Map<int, T> map, T newItem) {\n var list = map.entries.map((e) => e.value).toList();\n list.add(newItem);\n var newIndex = 1;\n\n return Map.fromIterable(list,\n key: (item) => newIndex++, value: (item) => item);\n }\n var result = addToMap<String>({1: 'c', 2: 'dart', 3: 'flutter'}, 'B');\nprint(\"result = $result\"); //result = {1: c, 2: dart, 3: flutter, 4: B}\n" }, { "answer_id": 74657934, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": -1, "selected": false, "text": "class hashCode class nonEqualKey {\n \n @override\n int get hashCode => 0;\n \n @override\n operator ==(covariant nonEqualKey other) {\n return other.hashCode != hashCode;\n }\n @override\n toString() {\n return \"unique\";\n }\n}\n\nMap map = {};\nmap = {nonEqualKey(): 'c', nonEqualKey(): 'dart', nonEqualKey(): 'flutter'};\nprint(map); // {unique: c, unique: dart, unique: flutter}\n hashCode 0 == hashCode 0!=0 false class Map" }, { "answer_id": 74662768, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 0, "selected": false, "text": "Map List Map List List.asMap var map = [\n 'c',\n 'dart',\n 'flutter',\n ].asMap();\n\nprint(map); // Prints: {0: c, 1: dart, 2: flutter}\n List.asMap var map = Map.of([\n 'c',\n 'dart',\n 'flutter',\n ].asMap());\n Map var map = Map.of([\n '',\n 'c',\n 'dart',\n 'flutter',\n ].asMap())\n ..remove(0);\n\nprint(map); // Prints: {1: c, 2: dart, 3: flutter}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12317652/" ]
74,657,605
<p>In Python I can do something like:</p> <pre class="lang-py prettyprint-override"><code>def add_postfix(name: str, postfix: str = None): if base is None: postfix = some_computation_based_on_name(name) return name + postfix </code></pre> <p>So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for <code>postfix</code>. It needs to be calculated. (which is why I can't just have a default value).</p> <p>In C++ I reached for std::optional and tried:</p> <pre class="lang-cpp prettyprint-override"><code>std::string add_postfix(const std::string&amp; name, std::optional&lt;const std::string&amp;&gt; postfix) { if (!postfix.has_value()) { postfix.emplace(&quot;2&quot;) }; return name + postfix; } </code></pre> <p>I'm now aware that this won't work because <code>std::optional&lt;T&amp;&gt;</code> is not a thing in C++. I'm fine with that.</p> <p>But now what mechanism should I use to achieve the following:</p> <ul> <li>Maintain the benefits of const T&amp;: no copy and don't modify the original.</li> <li>Don't have to make some other <code>postfix_</code> so that I have the optional one and the final one.</li> <li>Don't have to overload.</li> <li>Have multiple of these optional parameters in one function signature.</li> </ul>
[ { "answer_id": 74657690, "author": "NarekMeta", "author_id": 11340026, "author_profile": "https://Stackoverflow.com/users/11340026", "pm_score": 1, "selected": false, "text": "std::string add_postfix(const std::string& name, const std::string& postfix = \"default value\")\n{\n return name + postfix;\n}\n" }, { "answer_id": 74657876, "author": "Pete Becker", "author_id": 1593860, "author_profile": "https://Stackoverflow.com/users/1593860", "pm_score": 2, "selected": false, "text": "std::string add_postfix(const std::string& name, const std::string& postfix) {\n// whatever\n}\n\nstd::string add_default_postfix(const std::string& name) {\nreturn add_postfix(name, \"2\");\n}\n add_postfix" }, { "answer_id": 74657926, "author": "Jarod42", "author_id": 2684539, "author_profile": "https://Stackoverflow.com/users/2684539", "pm_score": 1, "selected": false, "text": "value_or std::string add_postfix(const std::string& name,\n const std::optional<std::string>& postfix)\n{\n return name + postfix.value_or(\"2\");\n}\n optional<T&> optional<reference_wrapper<T>> std::string add_postfix(const std::string& name,\n const std::optional<std::reference_wrapper<const std::string>>& postfix)\n{\n#if 1\n const std::string postfix_ = \"2\";\n return name + postfix.value_or(postfix_).get();\n#else // or\n return name + (postfix.has_value() ? postfix->get() : \"2\");\n#endif\n}\n" }, { "answer_id": 74658314, "author": "Nathan Pierson", "author_id": 12334309, "author_profile": "https://Stackoverflow.com/users/12334309", "pm_score": 3, "selected": true, "text": "std::string const* const std::string std::string add_postfix(const std::string& name, std::string const* postfix = nullptr) \n{\n std::string derivedSuffix;\n if(!postfix) \n { \n derivedSuffix = some_computation(name); \n postfix = &derivedSuffix;\n }\n return name + *postfix;\n}\n derivedSuffix postfix if(!postfix) *postfix std::string postfix nullptr std::string" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4391249/" ]
74,657,651
<p>I am using Dart but i am facing null safty issue with following code</p> <pre><code>RxMap&lt;Product,int&gt;cartItems=Map&lt;Product,int&gt;().obs; </code></pre> <pre><code>void updateCart(Product product,String type){ if(type==&quot;plus&quot;) { cartItems.value[product]++; } else { cartItems.value[product]--; } } </code></pre> <p>i got the following error message</p> <blockquote> <p>the method '+' can't be unconditionally invoked because the receiver can be 'null'</p> </blockquote> <p>i tried to add null check to the target as following</p> <pre><code>cartItems.value![product]++; </code></pre>
[ { "answer_id": 74657705, "author": "Gowtham K K", "author_id": 9248098, "author_profile": "https://Stackoverflow.com/users/9248098", "pm_score": 2, "selected": false, "text": "cartItems.value[product]??0 +1\n cartItems.value[product]!+1\n" }, { "answer_id": 74657834, "author": "LorenzOliveto", "author_id": 2290372, "author_profile": "https://Stackoverflow.com/users/2290372", "pm_score": 1, "selected": false, "text": "cartItems.value cartItems.value[product] null 1 null if (type == \"plus\") {\n cartItems.value[product] = (cartItems.value[product] ?? 0) + 1;\n} else {\n cartItems.value[product] = (cartItems.value[product] ?? 0) - 1;\n}\n (cartItems.value[product] ?? 0) cartItems.value[product] null cartItems.value[product] == null int? currentValue = cartItems.value[product];\nif (currentValue == null) {\n throw Exception('Trying to remove on a null object');\n}\ncartItems.value[product] = currentValue - 1;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13486465/" ]
74,657,670
<p>I have an array of index ranges and a string:</p> <pre class="lang-js prettyprint-override"><code>const ranges = [[2,5], [11, 14]] const str = 'brave new world' </code></pre> <p>I'm trying to write a function to interpolate and wrap the characters at those ranges.</p> <pre class="lang-js prettyprint-override"><code>const magic = (str, ranges, before='&lt;bold&gt;', after='&lt;/bold&gt;') =&gt; { // magic here return 'br&lt;bold&gt;ave&lt;/bold&gt; new w&lt;bold&gt;orl&lt;/bold&gt;d' } </code></pre>
[ { "answer_id": 74657737, "author": "upo", "author_id": 7497935, "author_profile": "https://Stackoverflow.com/users/7497935", "pm_score": 0, "selected": false, "text": "const magic = (str, ranges, before='<bold>', after='</bold>') => {\n // Create an array of characters from the input string\n const chars = str.split('');\n\n // Iterate over the ranges\n for (const [start, end] of ranges) {\n // Insert the before and after strings at the start and end indices\n chars.splice(end, 0, after);\n chars.splice(start, 0, before);\n }\n\n // Join the characters and return the resulting string\n return chars.join('');\n}\n\nconst ranges = [[2, 5], [11, 14]];\nconst str = 'brave new world';\nconst wrappedString = magic(str, ranges);\n\nconsole.log(wrappedString); // \"br<bold>ave</bold> new w<bold>orl</bold>d\"" }, { "answer_id": 74657883, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 1, "selected": false, "text": "before after const magic = (str, ranges, before='<bold>', after='</bold>') => {\n let result = \"\";\n let lastIndex = 0;\n \n for(const [start, end] of ranges) {\n result += str.slice(lastIndex, start);\n const wrap = str.slice(start, end);\n result += before + wrap + after;\n lastIndex = end;\n }\n \n result += str.slice(lastIndex);\n \n return result;\n}\n\nconst ranges = [[2,5], [11, 14]]\nconst str = 'brave new world'\nconsole.log(magic(str, ranges));" }, { "answer_id": 74658167, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 0, "selected": false, "text": ".reverse() // Wraps one range\nfunction wrap(str, [i, j]) {\n return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);\n}\n[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')\n function magic(str, ranges, b='<bold>', a='</bold>') {\n const wrap = (str, [i, j]) => str.substring(0, i) + b + \n str.substring(i, j) + a + str.substring(j);\n return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428445/" ]
74,657,673
<p>Today we have faced an specific error about a dependency of aws cli called botocore. We are using pip from a bitbucket caches like in this yml below:</p> <pre><code> - step: &amp;build-and-publish name: Build and Publish services: - docker caches: - pip script: - pip3 install awscli </code></pre> <p>During the building process, the following error happens: <strong>ERROR: Could not find a version that satisfies the requirement botocore==1.29.21 (from awscli)</strong> .</p>
[ { "answer_id": 74657737, "author": "upo", "author_id": 7497935, "author_profile": "https://Stackoverflow.com/users/7497935", "pm_score": 0, "selected": false, "text": "const magic = (str, ranges, before='<bold>', after='</bold>') => {\n // Create an array of characters from the input string\n const chars = str.split('');\n\n // Iterate over the ranges\n for (const [start, end] of ranges) {\n // Insert the before and after strings at the start and end indices\n chars.splice(end, 0, after);\n chars.splice(start, 0, before);\n }\n\n // Join the characters and return the resulting string\n return chars.join('');\n}\n\nconst ranges = [[2, 5], [11, 14]];\nconst str = 'brave new world';\nconst wrappedString = magic(str, ranges);\n\nconsole.log(wrappedString); // \"br<bold>ave</bold> new w<bold>orl</bold>d\"" }, { "answer_id": 74657883, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 1, "selected": false, "text": "before after const magic = (str, ranges, before='<bold>', after='</bold>') => {\n let result = \"\";\n let lastIndex = 0;\n \n for(const [start, end] of ranges) {\n result += str.slice(lastIndex, start);\n const wrap = str.slice(start, end);\n result += before + wrap + after;\n lastIndex = end;\n }\n \n result += str.slice(lastIndex);\n \n return result;\n}\n\nconst ranges = [[2,5], [11, 14]]\nconst str = 'brave new world'\nconsole.log(magic(str, ranges));" }, { "answer_id": 74658167, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 0, "selected": false, "text": ".reverse() // Wraps one range\nfunction wrap(str, [i, j]) {\n return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);\n}\n[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')\n function magic(str, ranges, b='<bold>', a='</bold>') {\n const wrap = (str, [i, j]) => str.substring(0, i) + b + \n str.substring(i, j) + a + str.substring(j);\n return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6005116/" ]
74,657,676
<p>I'm using Splunk classic dashboards where I have 2 time range inputs. I want to compare data for 2 time frames in a single table. Essentially, I want to perform query which counts errors by type for period A and B, then join the searches by error type so that I can see how many errors of each type there were in period A as opposed to period B.</p> <p>I added a panel as follows:</p> <p><a href="https://i.stack.imgur.com/zbOjj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zbOjj.png" alt="enter image description here" /></a></p> <p>because I want to use tokens from both time inputs for the query:</p> <pre><code>(index=myindex) earliest=&quot;$runATimeInput.earliest$&quot; latest=&quot;$runATimeInput.latest$&quot; environment=&quot;$runAEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier | sort count desc | join left=L right=R where L.logIdentifier = R.logIdentifier [| search (index=myindex) earliest=&quot;$runBTimeInput.earliest$&quot; latest=&quot;$runBTimeInput.latest$&quot; environment=&quot;$runBEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier ] </code></pre> <p>The problem is that the query doesn't return any results although it should. The main query returns results:</p> <pre><code>(index=myindex) earliest=&quot;$runATimeInput.earliest$&quot; latest=&quot;$runATimeInput.latest$&quot; environment=&quot;$runAEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier | sort count desc </code></pre> <p>However the subsearch query doesn't return any results (although a separate search for the same period in a new tab returns results):</p> <pre><code>[| search (index=myindex) earliest=&quot;$runBTimeInput.earliest$&quot; latest=&quot;$runBTimeInput.latest$&quot; environment=&quot;$runBEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier ] </code></pre> <p>When I click on <code>Run Search</code> in Splunk panel in order to open the search in a new tab I see strange values for <code>earliest</code>/<code>latest</code> tokens. For the main query the values are: <code>earliest=&quot;1669500000&quot; latest=&quot;1669506493.677&quot;</code> where <code>1669500000</code> is the <code>Tue Jan 20 1970 09:45:00</code> and <code>1669506493.677</code> is <code>Sun Nov 27 2022 01:48:13</code> whereas the timeframe for period 1 was <code>Sun Nov 27 2022 00:00:00 - Sun Nov 27 2022 01:48:13</code>. That being said the main query works and it respects the original time frame.</p> <p>The values for the second query are <code>earliest=&quot;1669813200&quot; latest=&quot;1669816444.909&quot;</code> where <code>1669813200</code> is <code>Tue Jan 20 1970 09:45:00</code> and <code>1669816444.909</code> is <code>Wed Nov 30 2022 15:54:04</code> whereas the period 2 timeframe was <code>Wed Nov 30 2022 15:00:04 - </code>Wed Nov 30 2022 15:54:04`.</p> <p>Am I doing something wrong in the panel settings or the query? Or maybe there's another way to do this in Splunk?</p> <p>Below is the dashboard XML:</p> <pre class="lang-xml prettyprint-override"><code>&lt;form&gt; &lt;label&gt;My Dashboard&lt;/label&gt; &lt;description&gt;My Dashboard&lt;/description&gt; &lt;fieldset submitButton=&quot;false&quot; autoRun=&quot;true&quot;&gt; &lt;input type=&quot;time&quot; token=&quot;runATimeInput&quot; searchWhenChanged=&quot;true&quot;&gt; &lt;label&gt;Run A&lt;/label&gt; &lt;default&gt; &lt;earliest&gt;-24h@h&lt;/earliest&gt; &lt;latest&gt;now&lt;/latest&gt; &lt;/default&gt; &lt;/input&gt; &lt;input type=&quot;dropdown&quot; token=&quot;runAEnvironment&quot; searchWhenChanged=&quot;true&quot;&gt; &lt;label&gt;Run A Environment&lt;/label&gt; &lt;choice value=&quot;prod&quot;&gt;prod&lt;/choice&gt; &lt;default&gt;prod&lt;/default&gt; &lt;/input&gt; &lt;input type=&quot;time&quot; token=&quot;runBTimeInput&quot; searchWhenChanged=&quot;true&quot;&gt; &lt;label&gt;Run B&lt;/label&gt; &lt;default&gt; &lt;earliest&gt;-24h@h&lt;/earliest&gt; &lt;latest&gt;now&lt;/latest&gt; &lt;/default&gt; &lt;/input&gt; &lt;input type=&quot;dropdown&quot; token=&quot;runBEnvironment&quot; searchWhenChanged=&quot;true&quot;&gt; &lt;label&gt;Run B Environment&lt;/label&gt; &lt;choice value=&quot;prod&quot;&gt;prod&lt;/choice&gt; &lt;default&gt;prod&lt;/default&gt; &lt;/input&gt; &lt;/fieldset&gt; &lt;row&gt; &lt;panel&gt; &lt;title&gt;Top Exceptions&lt;/title&gt; &lt;table&gt; &lt;title&gt;Top Exceptions&lt;/title&gt; &lt;search&gt; &lt;query&gt;(index=distapps) earliest=&quot;$runATimeInput.earliest$&quot; latest=&quot;$runATimeInput.latest$&quot; environment=&quot;$runAEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier | sort count desc | join left=L right=R where L.logIdentifier = R.logIdentifier [| search (index=myindex) earliest=&quot;$runBTimeInput.earliest$&quot; latest=&quot;$runBTimeInput.latest$&quot; environment=&quot;$runBEnvironment$&quot; level=ERROR | spath input=message | stats count by logIdentifier ]&lt;/query&gt; &lt;earliest&gt;$runATimeInput.earliest$&lt;/earliest&gt; &lt;latest&gt;$runBTimeInput.latest$&lt;/latest&gt; &lt;/search&gt; &lt;option name=&quot;drilldown&quot;&gt;none&lt;/option&gt; &lt;option name=&quot;refresh.display&quot;&gt;progressbar&lt;/option&gt; &lt;/table&gt; &lt;/panel&gt; &lt;/row&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 74657737, "author": "upo", "author_id": 7497935, "author_profile": "https://Stackoverflow.com/users/7497935", "pm_score": 0, "selected": false, "text": "const magic = (str, ranges, before='<bold>', after='</bold>') => {\n // Create an array of characters from the input string\n const chars = str.split('');\n\n // Iterate over the ranges\n for (const [start, end] of ranges) {\n // Insert the before and after strings at the start and end indices\n chars.splice(end, 0, after);\n chars.splice(start, 0, before);\n }\n\n // Join the characters and return the resulting string\n return chars.join('');\n}\n\nconst ranges = [[2, 5], [11, 14]];\nconst str = 'brave new world';\nconst wrappedString = magic(str, ranges);\n\nconsole.log(wrappedString); // \"br<bold>ave</bold> new w<bold>orl</bold>d\"" }, { "answer_id": 74657883, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 1, "selected": false, "text": "before after const magic = (str, ranges, before='<bold>', after='</bold>') => {\n let result = \"\";\n let lastIndex = 0;\n \n for(const [start, end] of ranges) {\n result += str.slice(lastIndex, start);\n const wrap = str.slice(start, end);\n result += before + wrap + after;\n lastIndex = end;\n }\n \n result += str.slice(lastIndex);\n \n return result;\n}\n\nconst ranges = [[2,5], [11, 14]]\nconst str = 'brave new world'\nconsole.log(magic(str, ranges));" }, { "answer_id": 74658167, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 0, "selected": false, "text": ".reverse() // Wraps one range\nfunction wrap(str, [i, j]) {\n return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);\n}\n[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')\n function magic(str, ranges, b='<bold>', a='</bold>') {\n const wrap = (str, [i, j]) => str.substring(0, i) + b + \n str.substring(i, j) + a + str.substring(j);\n return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9914653/" ]
74,657,684
<p>I have an apache2 installation on my local linux server. It has a virtual host called <code>pcts.local</code> which has the root <code>/var/www/repos/pcts/</code>. Inside the root of pcts.local is a .htaccess file which attempts to rewrite urls to include .php if it isn't given like below:</p> <pre><code>http://pcts.local/ -&gt; http://pcts.local/index.php http://pcts.local/contact -&gt; http://pcts.local/contact.php </code></pre> <p>The problem is, <code>http://pcts.local/contact</code> gives an error 404 but <code>http://pcts.local/contact.php</code> gives 200.</p> <h3>Virtual Host Configuration:</h3> <pre><code>&lt;VirtualHost *:80&gt; ServerName pcts.local ServerAdmin webmaster@localhost DocumentRoot /var/www/repos/pcts ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre> <h3>.htaccess file in <code>/var/www/repos/pcts/</code></h3> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.+)$ $1.php [NC,L] </code></pre> <p>Thanks in advance of any help!</p>
[ { "answer_id": 74657737, "author": "upo", "author_id": 7497935, "author_profile": "https://Stackoverflow.com/users/7497935", "pm_score": 0, "selected": false, "text": "const magic = (str, ranges, before='<bold>', after='</bold>') => {\n // Create an array of characters from the input string\n const chars = str.split('');\n\n // Iterate over the ranges\n for (const [start, end] of ranges) {\n // Insert the before and after strings at the start and end indices\n chars.splice(end, 0, after);\n chars.splice(start, 0, before);\n }\n\n // Join the characters and return the resulting string\n return chars.join('');\n}\n\nconst ranges = [[2, 5], [11, 14]];\nconst str = 'brave new world';\nconst wrappedString = magic(str, ranges);\n\nconsole.log(wrappedString); // \"br<bold>ave</bold> new w<bold>orl</bold>d\"" }, { "answer_id": 74657883, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 1, "selected": false, "text": "before after const magic = (str, ranges, before='<bold>', after='</bold>') => {\n let result = \"\";\n let lastIndex = 0;\n \n for(const [start, end] of ranges) {\n result += str.slice(lastIndex, start);\n const wrap = str.slice(start, end);\n result += before + wrap + after;\n lastIndex = end;\n }\n \n result += str.slice(lastIndex);\n \n return result;\n}\n\nconst ranges = [[2,5], [11, 14]]\nconst str = 'brave new world'\nconsole.log(magic(str, ranges));" }, { "answer_id": 74658167, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 0, "selected": false, "text": ".reverse() // Wraps one range\nfunction wrap(str, [i, j]) {\n return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);\n}\n[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')\n function magic(str, ranges, b='<bold>', a='</bold>') {\n const wrap = (str, [i, j]) => str.substring(0, i) + b + \n str.substring(i, j) + a + str.substring(j);\n return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410287/" ]
74,657,691
<p>There's a macro defined as:</p> <pre><code>#define SET_ARRAY(field, type) \ foo.field = bar[#field].data&lt;type&gt;(); </code></pre> <p><code>foo</code> is a structure with members that are of type <code>int</code> or <code>float *</code>. <code>bar</code> is of type <code>cnpy::npz_t</code> (data loaded from .npz file). I understand that the macro is setting the structure member pointer so that it is pointing to the corresponding data in <code>bar</code> from the .npy file contained in the .npz file, but I'm wondering about the usage <code>bar[#field]</code>.</p> <p>When I ran the code through the preprocessor, I get:</p> <pre><code>foo.struct_member_name = bar[&quot;struct_member_name&quot;].data&lt;float&gt;(); </code></pre> <p>but I've never seen that type of usage either. It looks like the struct member variable name is somehow getting converted to an array index or memory offset that resolves to the data within the <code>cnpy::npz_t</code> structure. Can anyone explain how that is happening?</p>
[ { "answer_id": 74657737, "author": "upo", "author_id": 7497935, "author_profile": "https://Stackoverflow.com/users/7497935", "pm_score": 0, "selected": false, "text": "const magic = (str, ranges, before='<bold>', after='</bold>') => {\n // Create an array of characters from the input string\n const chars = str.split('');\n\n // Iterate over the ranges\n for (const [start, end] of ranges) {\n // Insert the before and after strings at the start and end indices\n chars.splice(end, 0, after);\n chars.splice(start, 0, before);\n }\n\n // Join the characters and return the resulting string\n return chars.join('');\n}\n\nconst ranges = [[2, 5], [11, 14]];\nconst str = 'brave new world';\nconst wrappedString = magic(str, ranges);\n\nconsole.log(wrappedString); // \"br<bold>ave</bold> new w<bold>orl</bold>d\"" }, { "answer_id": 74657883, "author": "VLAZ", "author_id": 3689450, "author_profile": "https://Stackoverflow.com/users/3689450", "pm_score": 1, "selected": false, "text": "before after const magic = (str, ranges, before='<bold>', after='</bold>') => {\n let result = \"\";\n let lastIndex = 0;\n \n for(const [start, end] of ranges) {\n result += str.slice(lastIndex, start);\n const wrap = str.slice(start, end);\n result += before + wrap + after;\n lastIndex = end;\n }\n \n result += str.slice(lastIndex);\n \n return result;\n}\n\nconst ranges = [[2,5], [11, 14]]\nconst str = 'brave new world'\nconsole.log(magic(str, ranges));" }, { "answer_id": 74658167, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 0, "selected": false, "text": ".reverse() // Wraps one range\nfunction wrap(str, [i, j]) {\n return str.substring(0, i) + '<b>' + str.substring(i, j) + '</b>' + str.substring(j);\n}\n[[2, 5], [11, 14]].reverse().reduce(wrap, 'brave new world')\n function magic(str, ranges, b='<bold>', a='</bold>') {\n const wrap = (str, [i, j]) => str.substring(0, i) + b + \n str.substring(i, j) + a + str.substring(j);\n return ranges.sort(([i], [j]) => j - i).reduce(wrap, str);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4409108/" ]
74,657,722
<p>I am trying to use a for loop with a nested ifelse statement to generate an indicator variable in a dataframe. I'm fairly new to using for-loops however. Other questions I've found seem to be more complex than my dataset, so the answers haven't been ideal for my situation.</p> <p>Essentially, I have survey recipients and names of their bosses, and I need to identify which recipients are also listed as bosses.</p> <p>I have a vector of the boss names in which I know these names are also survey recipients. For example (names have been changed):</p> <pre><code>bossrecip&lt;-c(&quot;Tamira Hughes&quot;, &quot;John Legend&quot;, &quot;Robert Collins&quot;) </code></pre> <p>Then the column that includes the recipients full name, which I cleaned to be formatted in the same way as the boss names, is column &quot;RecipientFullName&quot; in my SurveyData.</p> <pre><code>RecipientFullName&lt;-c(&quot;Gosha Jennings&quot;, &quot;Robert Stew&quot;, &quot;John Legend&quot;) both_recip_boss&lt;-0 SurveyData&lt;-data.frame(RecipientFullName, both_boss_recip) </code></pre> <p>&quot;both_recip_boss&quot; is where I would like to put a 1 for if the recipient is also a boss, and keep it as a 0 if they are just a recipient</p> <p>The for-loop I have tried that I think I am the closest with is</p> <pre><code>for (b in bossrecip) { ifelse(b==SurveyData$RecipientFullName | SurveyData$both_recip_boss==1, SurveyData$both_recip_boss&lt;-1, SurveyData$both_recip_boss&lt;-0) } </code></pre> <p>I included the OR statement because I don't want the following names in b to overwrite the previous loop work. However, this just gives me one row with a 1, when I know there should be at least 91 ones in my full dataset. I'm sure I'm messing up something with the logic of for-loops, but I'm uncertain what it is.</p> <p>I'd be very grateful for any advice and insight into what I am doing incorrectly. Thank you!</p>
[ { "answer_id": 74657781, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "%in% SurveyData$both_recip_boss <- +(SurveyData$RecipientFullName %in% bossrecip)\n\nSurveyData\n#> RecipientFullName both_recip_boss\n#> 1 Gosha Jennings 0\n#> 2 Robert Stew 0\n#> 3 John Legend 1\n" }, { "answer_id": 74658051, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "R bossrecip<-c(\"Tamira Hughes\", \"John Legend\", \"Robert Collins\") \n\nSurveyData<-data.frame(RecipientFullName=c(\"Gosha Jennings\", \"Robert Stew\", \"John Legend\"),\n both_boss_recip=0)\n\nfor (i in 1:nrow(SurveyData)){\n SurveyData$both_boss_recip[i]<-ifelse(SurveyData$RecipientFullName[i] %in% bossrecip, \n 1, \n 0)\n}\nSurveyData\n RecipientFullName both_boss_recip\n1 Gosha Jennings 0\n2 Robert Stew 0\n3 John Legend 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18012617/" ]
74,657,775
<p>I am writing a bazel rule, and one of the steps is acquiring an authentication token that will expire in some time. When I rebuild this target after that time, the step sees that nothing regarding getting that token has changed, so bazel uses a cached token.</p> <p>Is there a way to take the TTL of that token into account? Or at least force that step to be rebuilt every time the build is run?</p>
[ { "answer_id": 74657781, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "%in% SurveyData$both_recip_boss <- +(SurveyData$RecipientFullName %in% bossrecip)\n\nSurveyData\n#> RecipientFullName both_recip_boss\n#> 1 Gosha Jennings 0\n#> 2 Robert Stew 0\n#> 3 John Legend 1\n" }, { "answer_id": 74658051, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "R bossrecip<-c(\"Tamira Hughes\", \"John Legend\", \"Robert Collins\") \n\nSurveyData<-data.frame(RecipientFullName=c(\"Gosha Jennings\", \"Robert Stew\", \"John Legend\"),\n both_boss_recip=0)\n\nfor (i in 1:nrow(SurveyData)){\n SurveyData$both_boss_recip[i]<-ifelse(SurveyData$RecipientFullName[i] %in% bossrecip, \n 1, \n 0)\n}\nSurveyData\n RecipientFullName both_boss_recip\n1 Gosha Jennings 0\n2 Robert Stew 0\n3 John Legend 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241552/" ]
74,657,789
<p>I am getting <code>KeyError: &quot;['CashFinancial'] not in index&quot;</code> on the <code>df.to_csv</code> line because 'GOOG' doesn't have the <code>CashFinancial</code> column. How can I have it write in <code>null</code> for the <code>CashFinancial</code> value for 'GOOG'?</p> <pre><code>import pandas as pd from yahooquery import Ticker symbols = ['AAPL','GOOG','MSFT'] #This will be 75,000 symbols. header = [&quot;asOfDate&quot;,&quot;CashAndCashEquivalents&quot;,&quot;CashFinancial&quot;,&quot;CurrentAssets&quot;,&quot;TangibleBookValue&quot;,&quot;CurrentLiabilities&quot;,&quot;TotalLiabilitiesNetMinorityInterest&quot;] for tick in symbols: faang = Ticker(tick) faang.balance_sheet(frequency='q') df = faang.balance_sheet(frequency='q') df.to_csv('output.csv', mode='a', index=True, header=False, columns=header) </code></pre>
[ { "answer_id": 74657781, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "%in% SurveyData$both_recip_boss <- +(SurveyData$RecipientFullName %in% bossrecip)\n\nSurveyData\n#> RecipientFullName both_recip_boss\n#> 1 Gosha Jennings 0\n#> 2 Robert Stew 0\n#> 3 John Legend 1\n" }, { "answer_id": 74658051, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "R bossrecip<-c(\"Tamira Hughes\", \"John Legend\", \"Robert Collins\") \n\nSurveyData<-data.frame(RecipientFullName=c(\"Gosha Jennings\", \"Robert Stew\", \"John Legend\"),\n both_boss_recip=0)\n\nfor (i in 1:nrow(SurveyData)){\n SurveyData$both_boss_recip[i]<-ifelse(SurveyData$RecipientFullName[i] %in% bossrecip, \n 1, \n 0)\n}\nSurveyData\n RecipientFullName both_boss_recip\n1 Gosha Jennings 0\n2 Robert Stew 0\n3 John Legend 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6245473/" ]
74,657,805
<p>I'm trying to use Hibernate to map the following relationship:</p> <p>Each order contains 2 images. When I delete an order I want the images gone as well.</p> <p>I have two entities, OrderItems and Image and they look like this</p> <pre><code>public class OrderItems { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name=&quot;ID&quot;) private Long id; @Transient private String language; @OneToMany(fetch = FetchType.EAGER ,orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = &quot;order&quot;) private List&lt;Image&gt; images ; } </code></pre> <pre><code>public class Image implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name=&quot;ID&quot;) private Long id; @Column(name = &quot;IMAGE_NAME&quot;) private String name; @Column(name = &quot;IMAGE_BYTES&quot;, unique = false, nullable = true, length = 1000000) private byte[] image; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = &quot;order_id&quot; , nullable = false) private OrderItems order; } </code></pre> <p>Inserting new orders will also insert the coresponding images but when I try to delete an order I get an foreign key constraint error from the tables Image</p> <p>Am I missing something about Hibernate ? Shouldn't the attribute cascade = CascadeType.ALL do the trick ?</p> <p>Thanks for taking the time to provide any feedback. Cheers</p> <p>I already tried OneToMany and ManyToOne unidirectional and bidirectional but I get the same foreign key violation error or my images are not saved at all when I save a new order.</p>
[ { "answer_id": 74657781, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "%in% SurveyData$both_recip_boss <- +(SurveyData$RecipientFullName %in% bossrecip)\n\nSurveyData\n#> RecipientFullName both_recip_boss\n#> 1 Gosha Jennings 0\n#> 2 Robert Stew 0\n#> 3 John Legend 1\n" }, { "answer_id": 74658051, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "R bossrecip<-c(\"Tamira Hughes\", \"John Legend\", \"Robert Collins\") \n\nSurveyData<-data.frame(RecipientFullName=c(\"Gosha Jennings\", \"Robert Stew\", \"John Legend\"),\n both_boss_recip=0)\n\nfor (i in 1:nrow(SurveyData)){\n SurveyData$both_boss_recip[i]<-ifelse(SurveyData$RecipientFullName[i] %in% bossrecip, \n 1, \n 0)\n}\nSurveyData\n RecipientFullName both_boss_recip\n1 Gosha Jennings 0\n2 Robert Stew 0\n3 John Legend 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20005272/" ]
74,657,824
<p>I'm using Axios to fetch some data:</p> <pre><code>export const getProducts = async () =&gt; { try { const { data } = await axios.get(`/api/products`) return data } catch (err) { console.log(err) return err } } </code></pre> <p>Everything is fine, but I need to catch http errors inside try block. For example, when connection with the server is lost, Axios returns an AxiosError object:</p> <blockquote> <ol> <li>AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}</li> <li>code: &quot;ERR_BAD_REQUEST&quot;</li> <li>config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}</li> <li>message: &quot;Request failed with status code 404&quot;</li> <li>name: &quot;AxiosError&quot;</li> <li>request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}</li> <li>response: {data: '\n\n\n&lt;meta char…re&gt;Cannot GET /api/prducts\n\n\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}</li> <li>stack: &quot;AxiosError: Request failed with status code 404\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)&quot;</li> <li>[[Prototype]]: Error</li> </ol> </blockquote> <p>The problem is: I want to render a div saying &quot;There was an error fetching the data&quot; if there is an error. If not, render a table with products as usual.</p> <p>I call my function like this:</p> <pre><code>const productsArr = await getProducts() </code></pre> <p>How can I recognize if productsArr is a valid product array, or an AxiosError?</p>
[ { "answer_id": 74657781, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": true, "text": "%in% SurveyData$both_recip_boss <- +(SurveyData$RecipientFullName %in% bossrecip)\n\nSurveyData\n#> RecipientFullName both_recip_boss\n#> 1 Gosha Jennings 0\n#> 2 Robert Stew 0\n#> 3 John Legend 1\n" }, { "answer_id": 74658051, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "R bossrecip<-c(\"Tamira Hughes\", \"John Legend\", \"Robert Collins\") \n\nSurveyData<-data.frame(RecipientFullName=c(\"Gosha Jennings\", \"Robert Stew\", \"John Legend\"),\n both_boss_recip=0)\n\nfor (i in 1:nrow(SurveyData)){\n SurveyData$both_boss_recip[i]<-ifelse(SurveyData$RecipientFullName[i] %in% bossrecip, \n 1, \n 0)\n}\nSurveyData\n RecipientFullName both_boss_recip\n1 Gosha Jennings 0\n2 Robert Stew 0\n3 John Legend 1\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15797551/" ]
74,657,825
<p>Imagine a data frame...</p> <pre><code>df &lt;- rbind(&quot;A*YOU 1.000 0.780&quot;, &quot;A*YOUR 1.000 0.780&quot;, &quot;B*USE 0.800 0.678&quot;, &quot;B*USER 0.700 1.000&quot;) df &lt;- as.data.frame(df) df </code></pre> <p>... which prints...</p> <pre><code>&gt; df V1 1 A*YOU 1.000 0.780 2 A*YOUR 1.000 0.780 3 B*USE 0.800 0.678 4 B*USER 0.700 1.000 </code></pre> <p>... and of which I would like to remove any row that does not contain exactly any element of a list (called tenables here) <code>tenables &lt;- c(&quot;A*YOU&quot;, &quot;B*USE&quot;)</code>, so that the outcome becomes:</p> <pre><code>&gt; df V1 1 A*YOU 1.000 0.780 2 B*USE 0.800 0.678 </code></pre> <p>Any ideas on how to solve this? Many thanks in advance.</p>
[ { "answer_id": 74657931, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "> df[gsub(\"\\\\s*\\\\d+\\\\.*\", \"\", df$V1) %in% tenables, ,drop=FALSE]\n V1\n1 A*YOU 1.000 0.780\n3 B*USE 0.800 0.678\n" }, { "answer_id": 74657998, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 0, "selected": false, "text": "tenables * fixed=TRUE grep \\\\b YOU YOUR ## clean up tenables to be regex-friendly and precise\ngsub(\"([].*+(){}[])\", \"\\\\\\\\\\\\1\", tenables)\n# [1] \"A\\\\*YOU\" \"B\\\\*USE\"\n\n## combine into a single pattern for simple use in grep\npaste0(\"\\\\b(\", paste(gsub(\"([].*+(){}[])\", \"\\\\\\\\\\\\1\", tenables), collapse = \"|\"), \")\\\\b\")\n# [1] \"\\\\b(A\\\\*YOU|B\\\\*USE)\\\\b\"\n\n## subset your frame\nsubset(df, !grepl(paste0(\"\\\\b(\", paste(gsub(\"([].*+(){}[])\", \"\\\\\\\\\\\\1\", tenables), collapse = \"|\"), \")\\\\b\"), V1))\n# V1\n# 2 A*YOUR 1.000 0.780\n# 4 B*USER 0.700 1.000\n \\\\b(A\\\\*YOU|B\\\\*USE)\\\\b\n^^^ ^^^ \"word boundary\", meaning the previous/next chars\n are begin/end of string or from A-Z, a-z, 0-9, or _\n ^ ^ parens \"group\" the pattern so we can reference it\n in the replacement string\n ^^^^^^^ literal \"A\", \"*\", \"Y\", \"O\", \"U\" (same with other string)\n ^ the \"|\" means \"OR\", so either the \"A*\" or the \"B*\" strings\n" }, { "answer_id": 74658351, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "sapply strsplit A*YOU 1.000 0.780 df[sapply(strsplit(df$V1, \" \"), function(x) \n any(grepl(x[1], tenables))), , drop=F]\n V1\n2 A*YOU 1.000 0.780\n4 B*USE 0.800 0.678\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13574232/" ]
74,657,846
<p>`</p> <pre><code>export default async function handler(req, res) { if (req.method === 'POST') { try { const bodyItems = req.body.items; console.log(bodyItems) const renderCartItems = bodyItems?.map( singleProduct =&gt; { return { price_data: { currency: 'usd', product_data: { name: singleProduct.name }, unit_amount: singleProduct.price }, quantity: singleProduct.qty, } }) console.log(renderCartItems, &quot;mapped&quot;) // Create Checkout Sessions from body params. const session = await stripe.checkout.sessions.create({ line_items: renderCartItems, mode: 'payment', success_url: `http://localhost:3000/done`, cancel_url: `http://localhost:3000`, }); console.log(session.url) res.redirect(303, session.url); } catch (err) { res.status(err.statusCode || 500).json(err.message); } } else { res.setHeader('Allow', 'POST'); res.status(405).end('Method Not Allowed'); } } </code></pre> <p>`</p> <p>this is the error</p> <pre><code>&quot;The `line_items` parameter is required in payment mode.&quot; </code></pre> <p>and this is what got consoled out from my consonle.log statments</p> <pre><code>[ { name: 'sped', qty: 1, price: 5000, img: { _type: 'image', asset: [Object] }, ogprice: 5000 } ] [ { price_data: { currency: 'usd', product_data: [Object], unit_amount: 5000 }, quantity: 1 } ] mapped undefined undefined mapped </code></pre> <p>Anybody know how to fix this problem? It seems to get the right data on the first run, but on the second one it returns undefined. I tried using react strict mode but it still runs twice</p>
[ { "answer_id": 74657872, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 0, "selected": false, "text": "const renderCartItems = bodyItems ? bodyItems.map(singleProduct => {\n // Code to map the items goes here\n}) : [];\n const mappedBodyItems = bodyItems.map(singleProduct => {\n // Code to map the items goes here\n});\nconst renderCartItems = mappedBodyItems;\n" }, { "answer_id": 74658086, "author": "Nolan H", "author_id": 12474862, "author_profile": "https://Stackoverflow.com/users/12474862", "pm_score": 1, "selected": false, "text": "handler req.body.items handler" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17030379/" ]
74,657,884
<p>The issue I have is that after entering a value to be used by the variable <em>action</em>, the program immediately ends without doing any of the cases inside the switch. Will post the other functions if needed, but otherwise, I will refrain because it's too long and it will flood the page. Can anyone tell me why this is happening?</p> <p>Driver code and output are shown below:</p> <pre><code>int main() { // Creation of empty list struct Node* head = NULL; bool print = false; int action, placeNum, numIndex; while (print == false){ printf(&quot;LINKED LIST CREATOR \n&quot;); printf(&quot;1. Insert node at the beginning\n&quot;); printf(&quot;2. Insert node at the end\n&quot;); printf(&quot;3. Insert node at specified position\n&quot;); printf(&quot;4. Delete node at the beginning\n&quot;); printf(&quot;5. Delete node at the end\n&quot;); printf(&quot;6. Delete node at specified position\n&quot;); printf(&quot;7. Display the linked list\n&quot;); printf(&quot;Please enter the action you want to do: &quot;); scanf(&quot;%d&quot;, action); switch (action) { case 1: printf(&quot;Enter the number to be placed at the beginning: &quot;); scanf(&quot;%d&quot;, placeNum); insert_first(&amp;head, placeNum); break; case 2: printf(&quot;Enter the number to be placed at the end: &quot;); scanf(&quot;%d&quot;, placeNum); insert_last(&amp;head, placeNum); break; case 3: printf(&quot;Enter the index for the number to be placed: &quot;); scanf(&quot;%d&quot;, numIndex); printf(&quot;\nEnter the number to be placed at specified index: &quot;); scanf(&quot;%d&quot;, placeNum); insert_middle(numIndex, placeNum, &amp;head); break; case 4: delete_first(&amp;head); break; case 5: delete_last(head); break; case 6: printf(&quot;Enter the index of the number to be deleted: &quot;); scanf(&quot;%d&quot;, numIndex); delete_middle(&amp;head, numIndex); break; case 7: printf(&quot;\nThe Created Linked List is: &quot;); printList(head); print = true; break; } } return 0; } </code></pre> <pre><code> PS C:\Codes&gt; cd &quot;c:\Codes\C++\&quot; ; if ($?) { g++ singlelist.cpp -o singlelist } ; if ($?) { .\singlelist } LINKED LIST CREATOR 1. Insert node at the beginning 2. Insert node at the end 3. Insert node at specified position 4. Delete node at the beginning 5. Delete node at the end 6. Delete node at specified position 7. Display the linked list Please enter the action you want to do: 1 PS C:\Codes\C++&gt; </code></pre>
[ { "answer_id": 74657953, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 2, "selected": false, "text": "scanf scanf(\"%d\", action);\n %d int int * int scanf(\"%d\", &action);\n scanf %d" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20564942/" ]
74,657,888
<p>I am working with an Oracle DB 11g</p> <p>I have a database table with the primary key being a CHAR(4) - Though only numbers are used for this column.</p> <p>I noticed that there are some records that for example show '0018' or '0123'.</p> <p>So few things I noticed odd and needed some help on</p> <p>-Does a CHAR column &quot;automatically&quot; pad zeros to a value?</p> <p>-Also I noticed when writing a SQL that if I DONT use quotes in my where clause that it returns results, but if I do use quotes it does not? So for example</p> <p>DB CHAR(4) column has a key of '0018'</p> <p>I use this query</p> <pre><code>SELECT * FROM TABLE_A WHERE COLUMN_1=18; </code></pre> <p>I get the row as expected.</p> <p>But when I try the following</p> <pre><code>SELECT * FROM TABLE_A WHERE COLUMN_1='18'; </code></pre> <p>This does NOT work but this does work again</p> <pre><code>SELECT * FROM TABLE_A WHERE COLUMN_1='0018'; </code></pre> <p>So I am a bit confused how the first query can work as expected without quotes?</p>
[ { "answer_id": 74658312, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "18 '18 ' SELECT * FROM TABLE_A WHERE COLUMN_1=18;\n '0018' 18 '0018' '018 ' 18 18 '0018' 18 column_1 SELECT * FROM TABLE_A WHERE COLUMN_1='18';\n char '18 ' '18 ' '0018' ' 18 ' '0018' '18 ' '18' SELECT * FROM TABLE_A WHERE COLUMN_1='0018';\n '0018' '18 ' ' 18 ' '0018' '0018'" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3922588/" ]
74,657,914
<p>Is there a way to hover over data in a <code>plotly</code> graph and then be able to click on a choice of hyperlinks within the text?</p> <p>There are a number of questions (e.g., <a href="https://stackoverflow.com/questions/71819237/ggplotly-clickable-link-in-r-plot">here</a>, <a href="https://stackoverflow.com/questions/49711131/open-hyperlink-on-click-on-an-ggplot-plotly-chart">here</a>) that allow the user to click on a point and that brings you to the url associated with that point but in those solutions it is restricted to only one url. For example:</p> <pre><code>library(ggplot2) library(plotly) library(htmlwidgets) mydata &lt;- data.frame( xx = c(1, 2), yy = c(3, 4), website = c(&quot;https://www.google.com&quot;, &quot;https://www.r-project.org/&quot;), link = c( &quot;https://www.google.com&quot;, &quot;https://www.r-project.org/&quot;)) g &lt;- ggplot(mydata, aes(x = xx, y = yy, text = paste0(&quot;xx: &quot;, xx, &quot;\n&quot;, &quot;website link: &quot;, website), customdata = link)) + geom_point() g p &lt;- ggplotly(g, tooltip = c(&quot;text&quot;)) p onRender( p, &quot; function(el) { el.on('plotly_click', function(d) { var url = d.points[0].customdata; window.open(url); }); } &quot; ) </code></pre> <p>You can then click on the second point and it will bring you to <a href="https://www.r-project.org/" rel="nofollow noreferrer">https://www.r-project.org/</a> : <a href="https://i.stack.imgur.com/rD6ld.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rD6ld.png" alt="enter image description here" /></a></p> <p>What I want is to be able to choice between two or more links (i.e. click on a hyperlink within the textbox):</p> <pre><code>mydata &lt;- data.frame( xx = c(1, 2), yy = c(3, 4), website = c(&quot;https://www.google.com&quot;, &quot;https://www.r-project.org/), website2 = c(&quot; https://www.reddit.com/&quot;, &quot;http://stackoverflow.com/&quot;), link = c( &quot;https://www.google.com, https://www.reddit.com/&quot;, &quot;https://www.r-project.org/, http://stackoverflow.com/&quot;)) g &lt;- ggplot(mydata, aes(x = xx, y = yy, text = paste0(&quot;xx: &quot;, xx, &quot;\n&quot;, &quot;website link: &quot;, website, &quot;\n&quot;, &quot;Second website: &quot;, website2), customdata = link)) + geom_point() g p &lt;- ggplotly(g, tooltip = c(&quot;text&quot;)) p </code></pre> <p><a href="https://i.stack.imgur.com/TLDZu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TLDZu.png" alt="enter image description here" /></a></p> <p>I sense this cannot be achieved with <code>text</code> or <code>tooltip</code> from <code>plotly</code> but perhaps there is a different workaround using e.g. <code>javascript</code> (which I am not familiar with).</p> <p>Any ideas?</p> <p>Thanks</p>
[ { "answer_id": 74658312, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "18 '18 ' SELECT * FROM TABLE_A WHERE COLUMN_1=18;\n '0018' 18 '0018' '018 ' 18 18 '0018' 18 column_1 SELECT * FROM TABLE_A WHERE COLUMN_1='18';\n char '18 ' '18 ' '0018' ' 18 ' '0018' '18 ' '18' SELECT * FROM TABLE_A WHERE COLUMN_1='0018';\n '0018' '18 ' ' 18 ' '0018' '0018'" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4083743/" ]
74,657,952
<p>I made a code that select vowels and replace them with &quot;&quot;</p> <pre><code>function disemvowel(str) { str = str.replace(/[aeiouAEIOU]/g, &quot;&quot;); return str; } console.log(disemvowel(&quot;This website is for losers LOL!&quot;)); </code></pre> <p>But I am not quite sure how this part of the code works = <code>/[aeiouAEIOU]/g</code> why are the vowels inside [] and what the g does? as well as the //</p> <p>Another question, how could I select both lower and upper case letter at once instead of right [aeiouAEIOU]?</p>
[ { "answer_id": 74658079, "author": "jean.b", "author_id": 11282291, "author_profile": "https://Stackoverflow.com/users/11282291", "pm_score": 1, "selected": false, "text": "replace Regular Expression Regex" }, { "answer_id": 74658084, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 3, "selected": true, "text": "/[aeiouAEIOU]/g\n new RegExp( '[aeiouAEIOU]', 'g' )\n String.prototype.replace [aeiouAEIOU]\n a e i o u A E I O U g String.prototype.replace /[aeiou]/ig i" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74657952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20333201/" ]
74,658,056
<p>i'm using &quot;SubCategoryTiles&quot; widget all over the app. initially i was using same Group Icon but now i want to use different-different <strong>category_Icon</strong> wherever i use this widget. So i want to know how to do it. See the code and also the image with error i'm getting.</p> <pre><code>class SubCategoryTiles extends StatelessWidget { const SubCategoryTiles({ required this.titleText, required this.onTapHandler, required this.category_Icon, }); final Widget titleText; final VoidCallback onTapHandler; final IconData category_Icon; @override Widget build(BuildContext context) { return ListTile( leading: const CircleAvatar( backgroundColor: Colors.white, child: category_Icon, // Icon( // Icons.group, // color: Colors.deepOrange, // ), ), title: titleText, trailing: const Icon(Icons.arrow_right), onTap: onTapHandler, ); } } </code></pre> <p><a href="https://i.stack.imgur.com/WVkK3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WVkK3.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74658079, "author": "jean.b", "author_id": 11282291, "author_profile": "https://Stackoverflow.com/users/11282291", "pm_score": 1, "selected": false, "text": "replace Regular Expression Regex" }, { "answer_id": 74658084, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 3, "selected": true, "text": "/[aeiouAEIOU]/g\n new RegExp( '[aeiouAEIOU]', 'g' )\n String.prototype.replace [aeiouAEIOU]\n a e i o u A E I O U g String.prototype.replace /[aeiou]/ig i" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12722751/" ]
74,658,078
<p>I'm working with a couple volunteers on creating the first online dictionary for our language Tarifit (An Amazigh language spoken in Northern Morocco)</p> <p>I'm still a CS student learning about Python and C# currently but I also know HTML/CSS/JS and my question was what is the best way to store all the words in a database and how can the people I work with who don't know anything about programming edit the database and add more words etc...</p> <p>I'm already using JavaScript to work on the dictionary site but I could also use Python or any other programming language if it has a better solution for the Database.</p> <p>I have been looking at some SQL Databases and Redis but I don't have experience with them so idk if they will be useful to learn for this exact type of project.</p>
[ { "answer_id": 74658079, "author": "jean.b", "author_id": 11282291, "author_profile": "https://Stackoverflow.com/users/11282291", "pm_score": 1, "selected": false, "text": "replace Regular Expression Regex" }, { "answer_id": 74658084, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 3, "selected": true, "text": "/[aeiouAEIOU]/g\n new RegExp( '[aeiouAEIOU]', 'g' )\n String.prototype.replace [aeiouAEIOU]\n a e i o u A E I O U g String.prototype.replace /[aeiou]/ig i" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667783/" ]
74,658,107
<p>Have a table of employees (key emp id) with one column being the boss (same key format). I was able to build out the hierarchy by doing repeated joins (took 10 for my real organization), but now I need to add a column for:</p> <ul> <li>employee_count (count of rows with the boss_id = emp_id of current row)</li> <li>empire_count (count of rows with the hierarchy starting the same way)</li> </ul> <p>I'm most comfortable in the Tidyverse, here's some simplified fake data of what I have so far as example:</p> <pre><code>library(tidyverse) employees = tibble( emp_id = c(1,2,3,4,5,6,7), emp_name = c('BigBoss','MedBoss','MedBoss2','Emp1','Emp2','Emp3','Emp4'), boss_name = c('','BigBoss','BigBoss','MedBoss','MedBoss','MedBoss2','MedBoss2'), hierarchy = c('','BigBoss','BigBoss','BigBoss&gt;MedBoss','BigBoss&gt;MedBoss','BigBoss&gt;MedBoss2','BigBoss&gt;MedBoss2') ) </code></pre> <p>Which looks like this:</p> <pre><code># A tibble: 7 × 4 emp_id emp_name boss_name hierarchy &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; 1 1 BigBoss &quot;&quot; &quot;&quot; 2 2 MedBoss &quot;Bigboss&quot; &quot;BigBoss&quot; 3 3 MedBoss2 &quot;BigBoss&quot; &quot;BigBoss&quot; 4 4 Emp1 &quot;MedBoss&quot; &quot;BigBoss&gt;MedBoss&quot; 5 5 Emp2 &quot;MedBoss&quot; &quot;BigBoss&gt;MedBoss&quot; 6 6 Emp3 &quot;MedBoss2&quot; &quot;BigBoss&gt;MedBoss2&quot; 7 7 Emp4 &quot;MedBoss2&quot; &quot;BigBoss&gt;MedBoss2&quot; </code></pre> <p>As far as what I'm looking for, <code>employee_count</code> should be 2 for each of the MedBosses and BigBoss, and then the <code>empire_count</code> for BigBoss would be 6.</p> <p>For the <code>employee_count</code> piece, I could separately do a:</p> <pre><code>data %&gt;% group_by(boss_name) %&gt;% summarize(employee_count=n(emp_id)) </code></pre> <p>and then join it back, but then the hierarchy wouldn't work the same way... I think the answer is some map function from purrr or creating a function, and Vectorize()'ing it and calling within a mutate, but that hasn't worked for me.</p> <p>This is as close as I can get...</p> <pre><code># Function to get the count of employees for a boss_name get_employee_count = function(table,bossname) table %&gt;% filter(boss_name==bossname) %&gt;% nrow() # This call works (returns 2) get_employee_count(employees,'BigBoss') # Try to add the count in via a mutate (returns 7 for each) employees %&gt;% mutate(employee_count=get_employee_count(.,boss_name)) </code></pre> <p>If I can get that to work, I think I could figure out the harder piece as I could do it also as a function.</p>
[ { "answer_id": 74658079, "author": "jean.b", "author_id": 11282291, "author_profile": "https://Stackoverflow.com/users/11282291", "pm_score": 1, "selected": false, "text": "replace Regular Expression Regex" }, { "answer_id": 74658084, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 3, "selected": true, "text": "/[aeiouAEIOU]/g\n new RegExp( '[aeiouAEIOU]', 'g' )\n String.prototype.replace [aeiouAEIOU]\n a e i o u A E I O U g String.prototype.replace /[aeiou]/ig i" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4346891/" ]
74,658,113
<p>I got 8 bytes Hex values in a cell as below which is in little endian format 00 00 08 04 22 00 40 00</p> <p>With text split I could get individual hex values in an array. = TEXTSPLIT(A1, , &quot; &quot;)</p> <p>00 00 08 04 22 00 40 00</p> <p>Is there an excel formula that I can use to grab the values in reverse order from an array to do below?</p> <p>00 40 00 22 04 08 00 00</p> <p>I don't want to use LEFT or MID or RIGHT extractors as I want to create generic formula that works on all data types.</p>
[ { "answer_id": 74658304, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 4, "selected": true, "text": "=TRIM(CONCAT(MID(\" \"&A1,SEQUENCE(8,,22,-3),3))) A2 =TEXTJOIN(\" \",,SORTBY(TEXTSPLIT(A1,,\" \"),ROW(1:8),-1))\n =LET(r,TEXTSPLIT(A1,,\" \"),TEXTJOIN(\" \",,SORTBY(r,SEQUENCE(ROWS(r)),-1)))\n INDEX()" }, { "answer_id": 74658313, "author": "Spencer Barnes", "author_id": 12231984, "author_profile": "https://Stackoverflow.com/users/12231984", "pm_score": 2, "selected": false, "text": "=MID(SUBSTITUTE(A1, \" \", \"\"), SEQUENCE(1, LEN(SUBSTITUTE(A1, \" \", \"\"))/2, LEN(SUBSTITUTE(A1, \" \", \"\"))-1, -2), 2)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166368/" ]
74,658,130
<p>I am a beginner in writing React applications. Please help me where I have gone wrong in writing the code. This is the API- <a href="https://api.coindesk.com/v1/bpi/currentprice.json" rel="nofollow noreferrer">https://api.coindesk.com/v1/bpi/currentprice.json</a>. I am not able to iterate over the json format that I have received from fetch function. Below is the code.</p> <pre><code>//import logo from './logo.svg'; import './App.css'; import {useEffect, useState} from 'react'; function App() { const[bitData, setbitData]=useState([]); useEffect(()=&gt;{ fetch(&quot;https://api.coindesk.com/v1/bpi/currentprice.json&quot;,{ method:'GET' }).then(result=&gt;result.json()) .then(result=&gt;setbitData(result)) },[]) return ( &lt;div className=&quot;App&quot;&gt; { bitData &amp;&amp; &lt;table className=&quot;table&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;Code&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Symbol&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Rate&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Description&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Rate_float&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; { bitData.map(draw=&gt; &lt;tr&gt; &lt;th scope=&quot;row&quot;&gt;{draw.code}&lt;/th&gt; &lt;td&gt;{draw.symbol}&lt;/td&gt; &lt;td&gt;{draw.rate}&lt;/td&gt; &lt;td&gt;{draw.description}&lt;/td&gt; &lt;/tr&gt; )} &lt;/tbody&gt; &lt;/table&gt; } &lt;/div&gt; ); } export default App; </code></pre> <p>This is the error:</p> <pre><code>Uncaught TypeError: bitData.map is not a function at App (App.js:28:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at beginWork$1 (react-dom.development.js:27426:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1) at renderRootSync (react-dom.development.js:26434:1) at recoverFromConcurrentError (react-dom.development.js:25850:1) at performConcurrentWorkOnRoot (react-dom.development.js:25750:1) App @ App.js:28 renderWithHooks @ react-dom.development.js:16305 updateFunctionComponent @ react-dom.development.js:19588 beginWork @ react-dom.development.js:21601 beginWork$1 @ react-dom.development.js:27426 performUnitOfWork @ react-dom.development.js:26557 workLoopSync @ react-dom.development.js:26466 renderRootSync @ react-dom.development.js:26434 recoverFromConcurrentError @ react-dom.development.js:25850 performConcurrentWorkOnRoot @ react-dom.development.js:25750 workLoop @ scheduler.development.js:266 flushWork @ scheduler.development.js:239 performWorkUntilDeadline @ scheduler.development.js:533 </code></pre> <pre><code></code></pre>
[ { "answer_id": 74658304, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 4, "selected": true, "text": "=TRIM(CONCAT(MID(\" \"&A1,SEQUENCE(8,,22,-3),3))) A2 =TEXTJOIN(\" \",,SORTBY(TEXTSPLIT(A1,,\" \"),ROW(1:8),-1))\n =LET(r,TEXTSPLIT(A1,,\" \"),TEXTJOIN(\" \",,SORTBY(r,SEQUENCE(ROWS(r)),-1)))\n INDEX()" }, { "answer_id": 74658313, "author": "Spencer Barnes", "author_id": 12231984, "author_profile": "https://Stackoverflow.com/users/12231984", "pm_score": 2, "selected": false, "text": "=MID(SUBSTITUTE(A1, \" \", \"\"), SEQUENCE(1, LEN(SUBSTITUTE(A1, \" \", \"\"))/2, LEN(SUBSTITUTE(A1, \" \", \"\"))-1, -2), 2)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20491989/" ]
74,658,165
<p>after running this code I keep getting the same error:</p> <p>note:(the data is in excel file (Heights : 16 column) and (Wights:16 column)</p> <p>I tried to change the epochs_num and it keeps giving the same problem...</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np # Load the dataset data = pd.read_csv('heights_weights.csv') # Plot the data distribution plt.scatter(data['Height'], data['Weight'], color='b') plt.xlabel('Height') plt.ylabel('Weight') plt.title('Height vs. Weight') plt.show() # Define the linear regression model def linearRegression_model(X, weights): y_pred = np.dot(X, weights) return y_pred # Define the update weights function def linearRegression_update_weights(X, y, weights, learning_rate): y_pred = linearRegression_model(X, weights) weights_delta = np.dot(X.T, y_pred - y) m = len(y) weights -= (learning_rate/m) * weights_delta return weights # Define the train function def linearRegression_train(X, y, learning_rate, num_epochs): # Initialize weights and bias weights = np.zeros(X.shape[1]) for epoch in range(num_epochs): weights = linearRegression_update_weights(X, y, weights, learning_rate) if (epoch % 100 == 0): print('epoch: %s, weights: %s' % (epoch, weights)) return weights # Define the predict function def linearRegression_predict(X, weights): y_pred = linearRegression_model(X, weights) return y_pred # Define the mean squared error function def mean_squared_error(y_true, y_pred): mse = np.mean(np.power(y_true-y_pred, 2)) return mse # Prepare the data X = data['Height'].values.reshape(-1, 1) y = data['Weight'].values.reshape(-1, 1) # Train the model lr = 0.01 n_epochs = 1000 weights = linearRegression_train(X, y, lr, n_epochs) # Predict y_pred = linearRegression_predict(X, weights) # Evaluate the model mse = mean_squared_error(y, y_pred) print('Mean Squared Error: %s' % mse) # Plot the regression line plt.scatter(data['Height'], data['Weight'], color='b') plt.plot(X, y_pred, color='k') plt.xlabel('Height') plt.ylabel('Weight') plt.title('Height vs. Weight') plt.show() # Plot the predicted and actual values plt.scatter(data['Height'], y, color='b', label='Actual') plt.scatter(data['Height'], y_pred, color='r', label='Predicted') plt.xlabel('Height') plt.ylabel('Weight') plt.title('Actual vs. Predicted') plt.legend() plt.show() </code></pre> <p>i try the same code to run step by step in google colab and i also change the epochs to 62 and run it many times but still the same :</p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-23-98703406a0a3&gt; in &lt;module&gt; 2 learning_rate = 0.01 3 num_epochs = 62 ----&gt; 4 weights = linearRegression_train(X, y, learning_rate, num_epochs) 1 frames &lt;ipython-input-12-8f66dacdd5fc&gt; in linearRegression_update_weights(X, y, weights, learning_rate) 4 weights_delta = np.dot(X.T, y_pred - y) 5 m = len(y) ----&gt; 6 weights -= (learning_rate/m) * weights_delta 7 return weights ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15) </code></pre>
[ { "answer_id": 74658304, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 4, "selected": true, "text": "=TRIM(CONCAT(MID(\" \"&A1,SEQUENCE(8,,22,-3),3))) A2 =TEXTJOIN(\" \",,SORTBY(TEXTSPLIT(A1,,\" \"),ROW(1:8),-1))\n =LET(r,TEXTSPLIT(A1,,\" \"),TEXTJOIN(\" \",,SORTBY(r,SEQUENCE(ROWS(r)),-1)))\n INDEX()" }, { "answer_id": 74658313, "author": "Spencer Barnes", "author_id": 12231984, "author_profile": "https://Stackoverflow.com/users/12231984", "pm_score": 2, "selected": false, "text": "=MID(SUBSTITUTE(A1, \" \", \"\"), SEQUENCE(1, LEN(SUBSTITUTE(A1, \" \", \"\"))/2, LEN(SUBSTITUTE(A1, \" \", \"\"))-1, -2), 2)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15165506/" ]
74,658,183
<p>I have the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>1</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>6</td> <td>3</td> </tr> </tbody> </table> </div> <p>My goal is to find the max value per each row, and then find how many times it was repeated in the same row.</p> <p>The resulting table should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> <th>max_val</th> <th>repetition</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>1</td> <td>4</td> <td>4</td> <td>1</td> </tr> <tr> <td>5</td> <td>6</td> <td>6</td> <td>3</td> <td>6</td> <td>2</td> </tr> </tbody> </table> </div> <p>Now to achieve this, I am doing the following for Max:</p> <pre><code>df%&gt;% rowwise%&gt;% mutate(max=max(col1:col4)) </code></pre> <p>However, I am struggling to find the repetition. My idea is to use this pseudo code in mutate: sum( &quot;select current row entirely or only for some columns&quot;==max). But I don't know how to select entire row or only some columns of it and use its content to do the check, i.e.: is it equal to the max. How can we do this in dplyr?</p>
[ { "answer_id": 74658239, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 3, "selected": true, "text": "library(dplyr)\ndf %>% \n rowwise() %>% \n mutate(max_val = max(across(everything())),\n repetition = sum(across(col1:col4) == max_val))\n\n# A tibble: 2 × 6\n# Rowwise: \n col1 col2 col3 col4 max_val repetition\n <int> <int> <int> <int> <int> <int>\n1 1 2 1 4 4 1\n2 5 6 6 3 6 2\n df$max_val <- apply(df,1,max)\ndf$repetition <- rowSums(df[, 1:4] == df[, 5])\n" }, { "answer_id": 74658265, "author": "jpsmith", "author_id": 12109788, "author_profile": "https://Stackoverflow.com/users/12109788", "pm_score": 1, "selected": false, "text": "df$max_val <- apply(df, 1, max)\ndf$repetition <- apply(df, 1, function(x) sum(x[1:4] == x[5]))\n # col1 col2 col3 col4 max_val repetition\n# 1 1 2 1 4 4 1\n# 2 5 6 6 3 6 2\n" }, { "answer_id": 74658393, "author": "Curt F.", "author_id": 4480692, "author_profile": "https://Stackoverflow.com/users/4480692", "pm_score": 1, "selected": false, "text": "df %>%\n mutate(row = row_number()) %>%\n pivot_longer(cols = -row) %>%\n group_by(row) %>%\n mutate(max_val = max(value), repetitions = sum(value == max(value))) %>%\n pivot_wider(id_cols = c(row, max_val, repetitions)) %>%\n select(col1:col4, max_val, repetitions)\n select()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8758029/" ]
74,658,191
<p>This REGEX</p> <pre><code> [Required] [RegularExpression(&quot;^[VB]&quot;, ErrorMessage = &quot;The barcode must start with B or V&quot;)] public string Barcode { get; set; } </code></pre> <p>fails with the following:</p> <pre><code> &quot;Barcode&quot;: { &quot;rawValue&quot;: &quot;B6761126229752008155&quot;, &quot;attemptedValue&quot;: &quot;B6761126229752008155&quot;, &quot;errors&quot;: [ { &quot;exception&quot;: null, &quot;errorMessage&quot;: &quot;The barcode must start with B or V&quot; } ], &quot;validationState&quot;: 1, &quot;isContainerNode&quot;: false, &quot;children&quot;: null }, </code></pre> <p>even though the values are shown to be correct..... The regex passes in Regex101.com</p> <p><a href="https://i.stack.imgur.com/OyvIK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OyvIK.png" alt="enter image description here" /></a></p> <p>I'm not sure where to go with this. Any ideas? If I remove the validator the code runs through to my controller with the correct barcode value.</p>
[ { "answer_id": 74658239, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 3, "selected": true, "text": "library(dplyr)\ndf %>% \n rowwise() %>% \n mutate(max_val = max(across(everything())),\n repetition = sum(across(col1:col4) == max_val))\n\n# A tibble: 2 × 6\n# Rowwise: \n col1 col2 col3 col4 max_val repetition\n <int> <int> <int> <int> <int> <int>\n1 1 2 1 4 4 1\n2 5 6 6 3 6 2\n df$max_val <- apply(df,1,max)\ndf$repetition <- rowSums(df[, 1:4] == df[, 5])\n" }, { "answer_id": 74658265, "author": "jpsmith", "author_id": 12109788, "author_profile": "https://Stackoverflow.com/users/12109788", "pm_score": 1, "selected": false, "text": "df$max_val <- apply(df, 1, max)\ndf$repetition <- apply(df, 1, function(x) sum(x[1:4] == x[5]))\n # col1 col2 col3 col4 max_val repetition\n# 1 1 2 1 4 4 1\n# 2 5 6 6 3 6 2\n" }, { "answer_id": 74658393, "author": "Curt F.", "author_id": 4480692, "author_profile": "https://Stackoverflow.com/users/4480692", "pm_score": 1, "selected": false, "text": "df %>%\n mutate(row = row_number()) %>%\n pivot_longer(cols = -row) %>%\n group_by(row) %>%\n mutate(max_val = max(value), repetitions = sum(value == max(value))) %>%\n pivot_wider(id_cols = c(row, max_val, repetitions)) %>%\n select(col1:col4, max_val, repetitions)\n select()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307702/" ]
74,658,236
<p>Why does my button have a shadow around it?</p> <p>I am trying to create a blue button with the border being the same color as the button itself. When you hover over the button it moves up by 3px and when you click it moves back down.</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>button { background-color: var(--accent); border-radius: 10px; box-shadow: 0; border-color: var(--accent); color: var(--background); padding-top: 7px; padding-bottom: 7px; padding-left: 15px; padding-right: 15px; cursor: pointer; transition: transform 0.3s; } button:hover { transform: translateY(-3px); } button:active { transform: translateY(-0px); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button&gt;Button&lt;/button&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74658328, "author": "Leland", "author_id": 3072442, "author_profile": "https://Stackoverflow.com/users/3072442", "pm_score": 3, "selected": true, "text": "border-style: outset border-style: solid button {\n border-style: solid;\n border-radius: 10px;\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" }, { "answer_id": 74659411, "author": "Jonath B E", "author_id": 20614828, "author_profile": "https://Stackoverflow.com/users/20614828", "pm_score": 0, "selected": false, "text": "button {\n background-color: var(--accent);\n border-radius: 10px;\n box-shadow: 0; \n color: var(--background);\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\n\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20140332/" ]
74,658,273
<p>I have a MaterialApp in Flutter and want to scale up text throughout the entire app, base in user preferences.</p>
[ { "answer_id": 74658328, "author": "Leland", "author_id": 3072442, "author_profile": "https://Stackoverflow.com/users/3072442", "pm_score": 3, "selected": true, "text": "border-style: outset border-style: solid button {\n border-style: solid;\n border-radius: 10px;\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" }, { "answer_id": 74659411, "author": "Jonath B E", "author_id": 20614828, "author_profile": "https://Stackoverflow.com/users/20614828", "pm_score": 0, "selected": false, "text": "button {\n background-color: var(--accent);\n border-radius: 10px;\n box-shadow: 0; \n color: var(--background);\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\n\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190625/" ]
74,658,276
<p>I have this method in my <code>Cucumber</code> test:</p> <pre><code>public void validateError(String name, DataTable errorTable) { Map&lt;String, String&gt; error = errorTable.asMap(String.class, String.class); String result = then().extract().body().jsonPath().getString(&quot;&quot;); then().statusCode(Integer.parseInt(error.get(&quot;errorCode&quot;))); Assertions.assertThat(result).contains(error.get(&quot;errorMessage&quot;)); } </code></pre> <p>It fails on <code>then().extract().body().jsonPath().getString(&quot;&quot;)</code> with:</p> <blockquote> <p>Caused by: groovy.json.JsonException: Lexing failed on line: 1, column: 1, while reading 'B', no possible valid JSON value or punctuation could be recognized.</p> </blockquote> <p>I'm trying to understand what <code>then().extract().body().jsonPath().getString(&quot;&quot;)</code>. Is it trying to extract the result from <code>name</code>? That would make sense as name is Bob in this case. I was expecting the line to extract the result from a json string though.</p>
[ { "answer_id": 74658328, "author": "Leland", "author_id": 3072442, "author_profile": "https://Stackoverflow.com/users/3072442", "pm_score": 3, "selected": true, "text": "border-style: outset border-style: solid button {\n border-style: solid;\n border-radius: 10px;\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" }, { "answer_id": 74659411, "author": "Jonath B E", "author_id": 20614828, "author_profile": "https://Stackoverflow.com/users/20614828", "pm_score": 0, "selected": false, "text": "button {\n background-color: var(--accent);\n border-radius: 10px;\n box-shadow: 0; \n color: var(--background);\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\n\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7836976/" ]
74,658,279
<p>i wanted to ask how can connect dns sever with my apps . all trafic will go through that server .</p> <p>i wanted to ask how can connect dns sever with my apps . all trafic will go through that server .</p>
[ { "answer_id": 74658328, "author": "Leland", "author_id": 3072442, "author_profile": "https://Stackoverflow.com/users/3072442", "pm_score": 3, "selected": true, "text": "border-style: outset border-style: solid button {\n border-style: solid;\n border-radius: 10px;\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" }, { "answer_id": 74659411, "author": "Jonath B E", "author_id": 20614828, "author_profile": "https://Stackoverflow.com/users/20614828", "pm_score": 0, "selected": false, "text": "button {\n background-color: var(--accent);\n border-radius: 10px;\n box-shadow: 0; \n color: var(--background);\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\n\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17058635/" ]
74,658,298
<p><a href="https://i.stack.imgur.com/Bk6mJ.png" rel="nofollow noreferrer">The store function</a></p> <p><a href="https://i.stack.imgur.com/teqcw.png" rel="nofollow noreferrer">The Route</a></p> <p>I try to store a data to database and than i want to redirect the page with the created data ID. I use <code>return redirect()-&gt;route('test', $id)</code> but its not working.</p>
[ { "answer_id": 74658328, "author": "Leland", "author_id": 3072442, "author_profile": "https://Stackoverflow.com/users/3072442", "pm_score": 3, "selected": true, "text": "border-style: outset border-style: solid button {\n border-style: solid;\n border-radius: 10px;\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" }, { "answer_id": 74659411, "author": "Jonath B E", "author_id": 20614828, "author_profile": "https://Stackoverflow.com/users/20614828", "pm_score": 0, "selected": false, "text": "button {\n background-color: var(--accent);\n border-radius: 10px;\n box-shadow: 0; \n color: var(--background);\n padding-top: 7px;\n padding-bottom: 7px;\n padding-left: 15px;\n padding-right: 15px;\n cursor: pointer;\n transition: transform 0.3s;\n}\n\nbutton:hover {\n transform: translateY(-3px);\n}\n\nbutton:active {\n transform: translateY(-0px);\n} <button>Button</button>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18631739/" ]
74,658,306
<p>Any idea why does Django Rest Framework ignore default values?</p> <pre><code>class MyClass(models.Model): some_field = models.CharField(default='Yes') class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyCLass fields = ['some_field'] class MyClassListCreateAPIView(ListCreateAPIView): queryset = MyClass.objects.all() serializer_class = MyClassSerializer </code></pre> <p>When I send <code>{'some_field': None}</code> /null/something like this. I always get:</p> <pre><code>Bad Request: /myurl/ [02/Dec/2022 16:44:59] &quot;POST /myurl/ HTTP/1.1&quot; 400 114 </code></pre> <p>When changed to:</p> <pre><code>class MyClass(models.Model): some_field = models.CharField(default='Yes', blank=True, null=True) </code></pre> <p>it works but always sets the <code>NULL</code> value. Is this expected behaviour? Should I change the mechanics of my POST request to include changing value to default when user doesn't provide one?</p>
[ { "answer_id": 74658542, "author": "rob", "author_id": 6034955, "author_profile": "https://Stackoverflow.com/users/6034955", "pm_score": 2, "selected": false, "text": "{'some_field': None} MyClass some_field None None default some_field create()" }, { "answer_id": 74659068, "author": "Navio1729", "author_id": 20167612, "author_profile": "https://Stackoverflow.com/users/20167612", "pm_score": 1, "selected": false, "text": "max_length" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13650271/" ]
74,658,394
<p>I know its normally obvious where the conversion between double and int has gone wrong but im using recursion methods to add up the sum of a list to 1 decimal point but i cannot seem to find where the error is. There is no error when i use console.WriteLine but when i use return (which i would like) it comes up with the error.</p> <pre><code> double[] arr = { -1.103f, 2.2f, 3.1f, 10.0f, 15.0f, 23.1f, 22, 12f }; List&lt;double&gt; values = new List&lt;double&gt;(arr.Length); foreach (double i in arr) { values.Add(i); } static double sum(List&lt;double&gt; values, int position = 0) { if (values[position] == values[values.Count - 1]) { return values[values.Count - 1]; } return Math.Round(values[position], 2) + sum(values, position + 1); } return sum(values); //this is the return value that causes the error </code></pre> <p>Some insight onto why it works with console.WriteLine but not return would be great and how to fix it so it works with return would be great.</p>
[ { "answer_id": 74658619, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 2, "selected": false, "text": "return sum(values);\n double Console.WriteLine(values);\n Console.WriteLine return Main() int" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420084/" ]
74,658,401
<p><strong>CODE:</strong></p> <pre><code>import re inp=input() tup=tuple(map(str,inp.split(','))) i=0 while i&lt;len(tup): x=tup[i] a=re.search(&quot;[0-9a-zA-Z\$#@&quot;,x) if a!=&quot;None&quot;: break else: i=i+1 if a!=&quot;None&quot; and len(tup[i])&gt;=6 and len(tup[i])&lt;=12: print(tup[i]) else: print(&quot;invalid&quot;) </code></pre> <p><strong>INPUT:</strong> ABd1234@1,a F1#,2w3E*,2We3345</p> <p><strong>ERROR:</strong></p> <blockquote> <p>unterminated character set at position 0</p> </blockquote>
[ { "answer_id": 74658619, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 2, "selected": false, "text": "return sum(values);\n double Console.WriteLine(values);\n Console.WriteLine return Main() int" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732934/" ]
74,658,402
<p>Structure like this:</p> <pre><code>chart.yaml values.yaml templates/ |__deploymentconfig.yaml </code></pre> <p>Usage: <code>helm install demo --dry-run --debug -f values.yaml</code></p> <p>What i like to do is, to add an <code>environment variable</code> with the <code>--set</code> command on <code>helm install</code> after the template has filled the yaml.</p> <p>Dummy Command like this (not working):<br /> <code>helm install demo ... -f values.yaml --set ???env[0].name=MyEnvVar</code></p> <p>Resulting deployment config should look like this:</p> <pre class="lang-bash prettyprint-override"><code>kind: Deployment ... spec: template: spec: containers: env: - name: MyEnvVar value: Hello </code></pre> <p>What do i need to set on the <strong>???</strong> part of the install command to get the desired variable in the deployment part of the manifest?</p>
[ { "answer_id": 74661972, "author": "David Maze", "author_id": 10008173, "author_profile": "https://Stackoverflow.com/users/10008173", "pm_score": 2, "selected": true, "text": "--set helm install --set env:\n - name: SOME_VARIABLE\n value: {{ .Values.someValue | default \"foo\" }}\n helm install --set someValue=bar --set env:\n - name: ENVIRONMENT\n value: {{ Values.environment | default \"production\" }}\n helm install --set environment=development ...\n env:\n{{- with .Values.extraEnvironment }}\n{{ toYaml . | indent 2 }}\n{{- end }}\n helm install --set helm install -f" }, { "answer_id": 74669393, "author": "Akshay", "author_id": 3881787, "author_profile": "https://Stackoverflow.com/users/3881787", "pm_score": 0, "selected": false, "text": "helm install demo ... -f values.yaml --set spec.template.spec.containers[0].env[0].name=MyEnvVar\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5392813/" ]
74,658,417
<p>I need using JAVA, change colors of all textviews from LISTVIEW.</p> <p>MainActivity.java:</p> <pre><code>public class MainActivity extends AppCompatActivity { String[] programName = {&quot;ex1&quot;, &quot;ex2&quot;, &quot;ex3&quot;} protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvProgram = findViewById(R.id.listView); ProgramAdapter programAdapter = new ProgramAdapter(this, programName); lvProgram.setAdapter(programAdapter); }} </code></pre> <p>ProgramAdapter.java:</p> <pre><code>public class ProgramAdapter extends ArrayAdapter&lt;String&gt; { Context context; String[] programName; public ProgramAdapter(Context context, String[] programName) { super(context, R.layout.single_item2, R.id.titulo, programName); this.context = context; this.programName = programName; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View singleItem = convertView; ProgramViewHolder holder = null; if(singleItem == null){ LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false); holder = new ProgramViewHolder(singleItem); singleItem.setTag(holder); } else{ holder = (ProgramViewHolder) singleItem.getTag(); } holder.programTitle.setText(programName[position]); } } </code></pre> <p>MY ATTEMPT:</p> <pre><code>findViewById(R.id.TextView1).setBackgroundColor(Color.BLACK); </code></pre> <p>My attempt even worked, but it only changed the color of some textviews and at random times, it didn't change all the way I wanted.</p>
[ { "answer_id": 74659304, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 1, "selected": false, "text": "holder.programTitle.setTextColor(Color.RED)\n holder.programTitle.setBackgroundColor(Color.RED)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667940/" ]
74,658,458
<p>How can I sort this array of <code>boolean</code> primitive, by putting <code>false</code> first and <code>true</code> at the end?</p> <p>Suppose I have the following:</p> <pre><code>boolean[] arrayOfBoolean = // initializing the array </code></pre>
[ { "answer_id": 74659304, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 1, "selected": false, "text": "holder.programTitle.setTextColor(Color.RED)\n holder.programTitle.setBackgroundColor(Color.RED)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14481346/" ]
74,658,493
<p>So, how can I interchange two sets of adjacent elements In a string.</p> <p>Like lets take a string &quot;abcd&quot; I want to make it &quot;cdab&quot;,another example would be &quot;5089&quot; I want to change this to &quot;8950&quot;, The string is a large one and I want to apply the method throughout the string. Can you guys please suggest a way to do the same in python.</p> <p>I tried modifying an existing algorithm for interchanging adjacent characters but it didn't work.</p> <p>Thank You.</p>
[ { "answer_id": 74659304, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 1, "selected": false, "text": "holder.programTitle.setTextColor(Color.RED)\n holder.programTitle.setBackgroundColor(Color.RED)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20608200/" ]
74,658,528
<p>I am new to JSON in general. I have a JSON file and I want to extract data from it, but I can't seem to find a way on how to do it. I've searched online, but I could not find any answer or I was just looking at the wrong places.</p> <p>Here is my JSON data:</p> <pre><code>{&quot;data&quot;: {&quot;cars&quot;: {&quot;total&quot;:117, &quot;results&quot;:[ {&quot;id&quot;:&quot;779579&quot;}, {&quot;id&quot;:&quot;952209&quot;}, {&quot;id&quot;:&quot;1103285&quot;}, {&quot;id&quot;:&quot;1157321&quot;}, {&quot;id&quot;:&quot;1372321&quot;}, {&quot;id&quot;:&quot;1533192&quot;}, {&quot;id&quot;:&quot;1630240&quot;}, {&quot;id&quot;:&quot;2061824&quot;}, {&quot;id&quot;:&quot;2312383&quot;}, {&quot;id&quot;:&quot;2353755&quot;}, {&quot;id&quot;:&quot;2796716&quot;}, {&quot;id&quot;:&quot;2811260&quot;}, {&quot;id&quot;:&quot;2824839&quot;}, {&quot;id&quot;:&quot;2961828&quot;}, {&quot;id&quot;:&quot;3315226&quot;}, {&quot;id&quot;:&quot;3586555&quot;}, {&quot;id&quot;:&quot;3668182&quot;}, {&quot;id&quot;:&quot;3986886&quot;}, {&quot;id&quot;:&quot;3989623&quot;}, {&quot;id&quot;:&quot;3998581&quot;}, {&quot;id&quot;:&quot;4021057&quot;}, {&quot;id&quot;:&quot;4038880&quot;}, {&quot;id&quot;:&quot;4308809&quot;}, {&quot;id&quot;:&quot;4325718&quot;}, {&quot;id&quot;:&quot;4352725&quot;}, {&quot;id&quot;:&quot;4360349&quot;}, {&quot;id&quot;:&quot;4628661&quot;}, {&quot;id&quot;:&quot;4863093&quot;}, {&quot;id&quot;:&quot;4940146&quot;}, {&quot;id&quot;:&quot;4947395&quot;}, {&quot;id&quot;:&quot;5157781&quot;}, {&quot;id&quot;:&quot;5794466&quot;}, {&quot;id&quot;:&quot;6134469&quot;}, {&quot;id&quot;:&quot;6157337&quot;}, {&quot;id&quot;:&quot;6307352&quot;}, {&quot;id&quot;:&quot;6727975&quot;}, {&quot;id&quot;:&quot;6783794&quot;}, {&quot;id&quot;:&quot;6831800&quot;}, {&quot;id&quot;:&quot;6960771&quot;}, {&quot;id&quot;:&quot;7159286&quot;}, {&quot;id&quot;:&quot;7211880&quot;}, {&quot;id&quot;:&quot;7212277&quot;}, {&quot;id&quot;:&quot;7217410&quot;}, {&quot;id&quot;:&quot;7264660&quot;}, {&quot;id&quot;:&quot;7406984&quot;}, {&quot;id&quot;:&quot;7893798&quot;}, {&quot;id&quot;:&quot;7948268&quot;}, {&quot;id&quot;:&quot;8047751&quot;}, {&quot;id&quot;:&quot;8271106&quot;}, {&quot;id&quot;:&quot;8346001&quot;}, {&quot;id&quot;:&quot;8352176&quot;}, {&quot;id&quot;:&quot;8485193&quot;}, {&quot;id&quot;:&quot;8746468&quot;}, {&quot;id&quot;:&quot;8801718&quot;}, {&quot;id&quot;:&quot;9104008&quot;}, {&quot;id&quot;:&quot;9494179&quot;}, {&quot;id&quot;:&quot;9588599&quot;}, {&quot;id&quot;:&quot;9717878&quot;}, {&quot;id&quot;:&quot;9845048&quot;}, {&quot;id&quot;:&quot;9891941&quot;}, {&quot;id&quot;:&quot;9943516&quot;}, {&quot;id&quot;:&quot;10002374&quot;}, {&quot;id&quot;:&quot;10213949&quot;}, {&quot;id&quot;:&quot;10326370&quot;}, {&quot;id&quot;:&quot;10499431&quot;}, {&quot;id&quot;:&quot;10518069&quot;}, {&quot;id&quot;:&quot;10538037&quot;}, {&quot;id&quot;:&quot;10589618&quot;}, {&quot;id&quot;:&quot;10602337&quot;}, {&quot;id&quot;:&quot;10723171&quot;}, {&quot;id&quot;:&quot;10724725&quot;}, {&quot;id&quot;:&quot;10746729&quot;}, {&quot;id&quot;:&quot;10751575&quot;}, {&quot;id&quot;:&quot;10752559&quot;}, {&quot;id&quot;:&quot;10852235&quot;}, {&quot;id&quot;:&quot;10867573&quot;}, {&quot;id&quot;:&quot;10877115&quot;}, {&quot;id&quot;:&quot;10893349&quot;}, {&quot;id&quot;:&quot;10988880&quot;}, {&quot;id&quot;:&quot;10993485&quot;}, {&quot;id&quot;:&quot;11026957&quot;}, {&quot;id&quot;:&quot;11111205&quot;}, {&quot;id&quot;:&quot;11122085&quot;}, {&quot;id&quot;:&quot;11150052&quot;}, {&quot;id&quot;:&quot;11251748&quot;}, {&quot;id&quot;:&quot;11259887&quot;}, {&quot;id&quot;:&quot;11270391&quot;}, {&quot;id&quot;:&quot;11291731&quot;}, {&quot;id&quot;:&quot;11303142&quot;}, {&quot;id&quot;:&quot;11303143&quot;}, {&quot;id&quot;:&quot;11308615&quot;}, {&quot;id&quot;:&quot;11313379&quot;}, {&quot;id&quot;:&quot;11334337&quot;}, {&quot;id&quot;:&quot;11338119&quot;}, {&quot;id&quot;:&quot;11338290&quot;}, {&quot;id&quot;:&quot;11339650&quot;}, {&quot;id&quot;:&quot;11347202&quot;}, {&quot;id&quot;:&quot;11359983&quot;}, {&quot;id&quot;:&quot;11390048&quot;}, {&quot;id&quot;:&quot;11399541&quot;}]}}} </code></pre> <p>I want to extract all the id and put them in an array. I tried JToken, but it can only get 100 data (up to element [99]) only because anything beyond 99 would give me an error. I tried it using a for loop.</p> <p>This is the error I get if go beyond 99:</p> <blockquote> <p>ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. <br /> Parameter name: index</p> </blockquote>
[ { "answer_id": 74658854, "author": "dbc", "author_id": 3744182, "author_profile": "https://Stackoverflow.com/users/3744182", "pm_score": 2, "selected": true, "text": "data.cars.total data.cars.total SelectTokens() ToArray() var jtoken = JToken.Parse(jsonString); // Or load the JSON from a stream\nvar ids = jtoken.SelectTokens(\"data.cars.results[*].id\").Select(id => (int)id).ToArray(); // Remove the .Select(id => (int)id) if you want them as strings\n\nConsole.WriteLine(\"{0} ids found:\", ids.Length); // Prints 100\nConsole.WriteLine(string.Join(\",\", ids)); // Prints the deserialized ids\n [*] data.cars.total" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2052533/" ]
74,658,534
<p>I have this debounce function:</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-js lang-js prettyprint-override"><code>const selectElement = document.querySelector('input'); const debounce = (cb, time = 1000) =&gt; { let timer; return (...args) =&gt; { console.log('run inner function') if (timer) { clearTimeout(timer) } timer = setTimeout(() =&gt; cb(...args), time) } } const onChange = debounce((e) =&gt; { console.log('event', e.target.value) }) selectElement.addEventListener('input', onChange);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input input={onChange}/&gt;</code></pre> </div> </div> </p> <p>The code works ok, but I want to understand, how the returned function is triggered inside <code>debounce</code> function, because I know that if a function returns another function I need to call it like this: <code>debounce()()</code> to trigger the second one, but in our case we trigger the function only once <code>debounce()</code> in <code>addEventListener</code>, but how the second call happens?</p>
[ { "answer_id": 74658583, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 2, "selected": false, "text": "debounce()() onChange onChange selectElement input selectElement.addEventListener(('input', onChange()) onChange() onChange input" }, { "answer_id": 74658728, "author": "Wyck", "author_id": 1563833, "author_profile": "https://Stackoverflow.com/users/1563833", "pm_score": 3, "selected": true, "text": "debounce()();\n let onChange = debounce();\nonChange();\n onChange addEventListener selectElement.addEventListener('input', onChange);\n onChange onChange() input function addEventListener(type, listener) {} listener() debounce() debounce()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540500/" ]
74,658,555
<p>From the docs: &quot;Indicates not to recurse creating indexes on partitions, if the table is partitioned. The default is to recurse.&quot;.</p> <p>Am I understand correctly that index will not be created on existing partitons? What kind of index will be created then (on what)?</p>
[ { "answer_id": 74658583, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 2, "selected": false, "text": "debounce()() onChange onChange selectElement input selectElement.addEventListener(('input', onChange()) onChange() onChange input" }, { "answer_id": 74658728, "author": "Wyck", "author_id": 1563833, "author_profile": "https://Stackoverflow.com/users/1563833", "pm_score": 3, "selected": true, "text": "debounce()();\n let onChange = debounce();\nonChange();\n onChange addEventListener selectElement.addEventListener('input', onChange);\n onChange onChange() input function addEventListener(type, listener) {} listener() debounce() debounce()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7686473/" ]
74,658,562
<p>Okay so its been long i did react. my problem is very easy, i just dont know how to do it. Basically i am fetching data from an api and putting it inside a state. i basically want to display that data im fetching as raw data instead of mapping over it. this is what i mean.</p> <p>This is my component:</p> <pre><code> const App = () =&gt; { const [info, setInfo] = useState([]) const getData = async () =&gt; { const res = await fetch ('https://dummyjson.com/products/') const data = await res.json() setInfo(data.products) } console.log(info) return( &lt;div&gt; {info} &lt;button onClick={getData}&gt;click me&lt;/button&gt; &lt;/div&gt; ) } export default App; </code></pre> <p>Basically when i click the button, i want the info to be displayed like this on the browser:</p> <pre><code>{ &quot;id&quot;: 1, &quot;title&quot;: &quot;iPhone 9&quot;, &quot;description&quot;: &quot;An apple mobile which is nothing like apple&quot;, &quot;price&quot;: 549, &quot;discountPercentage&quot;: 12.96, &quot;rating&quot;: 4.69, &quot;stock&quot;: 94, &quot;brand&quot;: &quot;Apple&quot;, &quot;category&quot;: &quot;smartphones&quot;, &quot;thumbnail&quot;: &quot;https://i.dummyjson.com/data/products/1/thumbnail.jpg&quot;, &quot;images&quot;: [ &quot;https://i.dummyjson.com/data/products/1/1.jpg&quot;, &quot;https://i.dummyjson.com/data/products/1/2.jpg&quot;, &quot;https://i.dummyjson.com/data/products/1/3.jpg&quot;, &quot;https://i.dummyjson.com/data/products/1/4.jpg&quot;, &quot;https://i.dummyjson.com/data/products/1/thumbnail.jpg&quot; ] } </code></pre> <p>That is all. i just want to display the raw json data on the front end. but as my code is now, everytime i click the button i get this error:</p> <p>Objects are not valid as a React child (found: object with keys {id, title, description, price, discountPercentage, rating, stock, brand, category, thumbnail, images}). If you meant to render a collection of children, use an array instead</p>
[ { "answer_id": 74658654, "author": "David", "author_id": 13019276, "author_profile": "https://Stackoverflow.com/users/13019276", "pm_score": 2, "selected": false, "text": "<pre>{JSON.stringify(data)}</pre>" }, { "answer_id": 74658666, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 0, "selected": false, "text": "Objects are not valid as a React child (found: object with keys {id, title, description, price, discountPercentage, rating, stock, brand, category, thumbnail, images}). If you meant to render a collection of children, use an array instead\n info const App = () => {\n const [info, setInfo] = React.useState([]);\n\n const getData = () => {\n fetch(\"https://dummyjson.com/products/\")\n .then((res) => res.json())\n .then((data) => {\n setInfo(data.products);\n });\n };\n\n\n return (\n <div>\n {JSON.stringify(info)}\n <button onClick={getData}>click me</button>\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector('.react')); <script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\"></script>\n<div class='react'></div>" }, { "answer_id": 74658674, "author": "Shubham Waje", "author_id": 13483939, "author_profile": "https://Stackoverflow.com/users/13483939", "pm_score": 0, "selected": false, "text": "JSON.stringify pre const App = () => {\nconst [info, setInfo] = useState([])\n\nconst getData = async () => {\n const res = await fetch ('https://dummyjson.com/products/')\n const data = await res.json()\n setInfo(data.products)\n }\nconsole.log(info)\n \n\nreturn (\n <div>\n <pre>{JSON.stringify(info)}</pre>\n <button onClick={getData}>click me</button>\n </div>\n )\n}\n\nexport default App;\n\n\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15975299/" ]
74,658,593
<p>taking an intro CS class on python and was met by this lab on my textbook. It calls for binary search using recursive functions. I have the rest of the program, I simply need to define the Binary Search function. Any help on this would be greatly appreciated.</p> <p>Here is the problem:</p> <p>Binary search can be implemented as a recursive algorithm. Each call makes a recursive call on one-half of the list the call received as an argument.</p> <p>Complete the recursive function binary_search() with the following specifications:</p> <p>Parameters: a list of integers a target integer lower and upper bounds within which the recursive call will search Return value: if found, the index within the list where the target is located -1 if target is not found The algorithm begins by choosing an index midway between the lower and upper bounds.</p> <p>If target == nums[index] return index If lower == upper, return lower if target == nums[lower] else -1 to indicate not found Otherwise call the function recursively with half the list as an argument: If nums[index] &lt; target, search the list from index to upper If nums[index] &gt; target, search the list from lower to index The list must be ordered, but duplicates are allowed.</p> <p>Once the search algorithm works correctly, add the following to binary_search():</p> <p>Count the number of calls to binary_search(). Count the number of times when the target is compared to an element of the list. Note: lower == upper should not be counted. Hint: Use a global variable to count calls and comparisons.</p> <p>The input of the program consists of integers on one line followed by a target integer on the second.</p> <p>The template provides the main program and a helper function that reads a list from input.</p> <p><strong>Ex: If the input is:</strong> 1 2 3 4 5 6 7 8 9 2 <strong>the output is:</strong></p> <p>index: 1, recursions: 2, comparisons: 3</p> <p>Here is my code:</p> <hr /> <pre><code># TODO: Declare global variables here. recursions = 0 comparisons = 0 def binary_search(nums, target, lower, upper): global recursions global comparisons if target == nums[(lower+upper)/2]: if lower == upper: if target == nums[lower]: return lower else: target == -1 elif nums[(lower+upper)/2] &lt; target: recursions =+1 comparisons =+1 binary_search(upper) elif nums[(lower+upper)/2] &gt; target: recursions =+1 comparisons =+1 binary_search(lower) if __name__ == '__main__': # Input a list of nums from the first line of input nums = [int(n) for n in input().split()] # Input a target value target = int(input()) # Start off with default values: full range of list indices index = binary_search(nums, target, 0, len(nums) - 1) # Output the index where target was found in nums, and the # number of recursions and comparisons performed print(f'index: {index}, recursions: {recursions}, comparisons: {comparisons}') </code></pre> <h5></h5> <p>Error output:</p> <pre><code>Traceback (most recent call last): File &quot;main.py&quot;, line 34, in &lt;module&gt; index = binary_search(nums, target, 0, len(nums) - 1) File &quot;main.py&quot;, line 8, in binary_search if target == nums[(lower+upper)/2]: TypeError: list indices must be integers or slices, not float </code></pre>
[ { "answer_id": 74658632, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 1, "selected": false, "text": "lower + upper // if target == nums[(lower+upper)//2]:\n" }, { "answer_id": 74658911, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "recursions = 0\ncomparisons = 0\n\ndef binary_search(lst, t):\n def _binary_search(lst, lo, hi, t):\n global recursions, comparisons\n recursions += 1\n if hi >= lo:\n mid = (hi + lo) // 2\n comparisons += 1\n if lst[mid] == t:\n return mid\n\n comparisons += 1\n\n if lst[mid] > t:\n return _binary_search(lst, lo, mid - 1, t)\n else:\n return _binary_search(lst, mid + 1, hi, t)\n else:\n return -1\n return _binary_search(lst, 0, len(lst)-1, t)\n \nindex = binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9], 2)\n\nprint(f'{index=} {recursions=} {comparisons=}')\n index=1 recursions=2 comparisons=3\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667987/" ]
74,658,634
<p>I'm using Node v16.17 on MacBook Pro M1. I want to use microsecond timestamps, so I tried <code>process.hrtime()</code>. But this is very strange, as the first array element (which should be seconds when multiplied by 1000) is like some date in 2017:</p> <pre><code>&gt; new Date().getTime(); 1669997280728 &gt; process.hrtime(); [ 1486038, 90680583 ] </code></pre> <p>So, if I take 1486038000 --&gt; it is Thu, 02 Feb 2017 12:20:00 GMT If I take out the milliseconds from new Date().getTime() -&gt; it is correctly Fri, 02 Dec 2022 16:08:00 GMT</p> <p>What it the issue here? I thought process.hrtime() will be the high resolution time, but why is this so <em>off</em>?</p> <p>Thanks Fritz</p>
[ { "answer_id": 74658632, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 1, "selected": false, "text": "lower + upper // if target == nums[(lower+upper)//2]:\n" }, { "answer_id": 74658911, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "recursions = 0\ncomparisons = 0\n\ndef binary_search(lst, t):\n def _binary_search(lst, lo, hi, t):\n global recursions, comparisons\n recursions += 1\n if hi >= lo:\n mid = (hi + lo) // 2\n comparisons += 1\n if lst[mid] == t:\n return mid\n\n comparisons += 1\n\n if lst[mid] > t:\n return _binary_search(lst, lo, mid - 1, t)\n else:\n return _binary_search(lst, mid + 1, hi, t)\n else:\n return -1\n return _binary_search(lst, 0, len(lst)-1, t)\n \nindex = binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9], 2)\n\nprint(f'{index=} {recursions=} {comparisons=}')\n index=1 recursions=2 comparisons=3\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2240829/" ]
74,658,655
<p>I have an issue with React when I try to retrieve the value of return.</p> <p>The code:</p> <pre><code>export const RuoloOnline = (jwt) =&gt; { axios.get(&quot;http://localhost:1337/api/users/me&quot;, { headers: { &quot;Authorization&quot;: `Bearer ${jwt}` } } ).then((res) =&gt; { return (res.data.ruolo) }).catch(() =&gt; {return 0}) </code></pre> <p>if I put a console.log the value is correctly viewed. If I try to call this function outside the file, it generates an undefined return.</p>
[ { "answer_id": 74658632, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 1, "selected": false, "text": "lower + upper // if target == nums[(lower+upper)//2]:\n" }, { "answer_id": 74658911, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "recursions = 0\ncomparisons = 0\n\ndef binary_search(lst, t):\n def _binary_search(lst, lo, hi, t):\n global recursions, comparisons\n recursions += 1\n if hi >= lo:\n mid = (hi + lo) // 2\n comparisons += 1\n if lst[mid] == t:\n return mid\n\n comparisons += 1\n\n if lst[mid] > t:\n return _binary_search(lst, lo, mid - 1, t)\n else:\n return _binary_search(lst, mid + 1, hi, t)\n else:\n return -1\n return _binary_search(lst, 0, len(lst)-1, t)\n \nindex = binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9], 2)\n\nprint(f'{index=} {recursions=} {comparisons=}')\n index=1 recursions=2 comparisons=3\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14603504/" ]
74,658,670
<p>How to rebuilt this using rxjs if it is advisable:</p> <pre><code>constructor(private customerInfoService: CustomerInfoService) { customerInfoService.getCustomerIPById(this.a).subscribe(x =&gt; { customerInfoService.getIPActivityDates(x).subscribe(y =&gt; { this.latestActivityDate = y.latestDate; }) }) } </code></pre>
[ { "answer_id": 74658784, "author": "Paul Thorsen", "author_id": 11790081, "author_profile": "https://Stackoverflow.com/users/11790081", "pm_score": 2, "selected": false, "text": "customerInfoService.getCustomerIPById(this.a).pipe(\n switchMap(x => customerInfoService.getIPActivityDates(x))\n}).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n})\n" }, { "answer_id": 74660722, "author": "Prashant Singh", "author_id": 11170656, "author_profile": "https://Stackoverflow.com/users/11170656", "pm_score": 0, "selected": false, "text": " constructor(private customerInfoService: CustomerInfoService) {\n this.customerInfoService.getCustomerIPById(this.a)\n .pipe(\n concatMap(x => this.customerInfoService.getIPActivityDates(x))\n ).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n });\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10733113/" ]
74,658,685
<p>I want to have a Bool property, that represents that option key is pressed <code>@Publised var isOptionPressed = false</code>. <em>I would use it for changing SwiftUI View.</em></p> <p>For that, I think, that I should use Combine to observe for key pressure.</p> <p>I tried to find an NSNotification for that event, but it seems to me that there are no any NSNotification, that could be useful to me.</p>
[ { "answer_id": 74658784, "author": "Paul Thorsen", "author_id": 11790081, "author_profile": "https://Stackoverflow.com/users/11790081", "pm_score": 2, "selected": false, "text": "customerInfoService.getCustomerIPById(this.a).pipe(\n switchMap(x => customerInfoService.getIPActivityDates(x))\n}).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n})\n" }, { "answer_id": 74660722, "author": "Prashant Singh", "author_id": 11170656, "author_profile": "https://Stackoverflow.com/users/11170656", "pm_score": 0, "selected": false, "text": " constructor(private customerInfoService: CustomerInfoService) {\n this.customerInfoService.getCustomerIPById(this.a)\n .pipe(\n concatMap(x => this.customerInfoService.getIPActivityDates(x))\n ).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n });\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18199114/" ]
74,658,707
<p>Say one has a div which is vertically resizable like a textarea as below. When the user resizes the div, I would like to run a javascript function, <code>resizeHandler</code> below.</p> <p>It seems like the <code>resize</code> event is only for the document/window. And resize observer fires for all events, like say when the document is loading, it will fire resize observer events. So then I set a timeout to apply the resize observer after the page load, but the resize observer seems to remember historic resizes, and fires the previous resizes events.</p> <p>Is there a clean way to run <code>resizeHandler()</code> when the user resizes the div, and not for pageloading layout shifts?</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-js lang-js prettyprint-override"><code>function resizeHandler() { console.log('the div was resized') }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { resize: vertical; height: 64px; overflow-y: auto; background-color:gray; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="DIV" style="max-height:180px"&gt;This is a resizable div&lt;/div&gt;</code></pre> </div> </div> </p> <p>Note: I can't remove the style attribute of the div which sets the <code>max-height</code>.</p>
[ { "answer_id": 74658784, "author": "Paul Thorsen", "author_id": 11790081, "author_profile": "https://Stackoverflow.com/users/11790081", "pm_score": 2, "selected": false, "text": "customerInfoService.getCustomerIPById(this.a).pipe(\n switchMap(x => customerInfoService.getIPActivityDates(x))\n}).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n})\n" }, { "answer_id": 74660722, "author": "Prashant Singh", "author_id": 11170656, "author_profile": "https://Stackoverflow.com/users/11170656", "pm_score": 0, "selected": false, "text": " constructor(private customerInfoService: CustomerInfoService) {\n this.customerInfoService.getCustomerIPById(this.a)\n .pipe(\n concatMap(x => this.customerInfoService.getIPActivityDates(x))\n ).subscribe(y => {\n this.latestActivityDate = y.latestDate;\n });\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5506400/" ]
74,658,727
<p>I am trying to run an Nonlinear Least Squares regression to estimate three parameters while controlling for categorical variables. I am currently using the nlsLM function from the minpack.lm package for this.</p> <p>I have the following data set:</p> <pre><code>df &lt;- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003), Color=c(&quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;red&quot;, &quot;white&quot;, &quot;brown&quot;), Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6, 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9, 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7, 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5), Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4, 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1, 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8, 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5, 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9, 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2, 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5, 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8), Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7, 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9, 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6, 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2, 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3, 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5, 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3, 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6)) </code></pre> <p>In the following function, I am estimating parameters z, k and g. Variables &quot;Y&quot;, &quot;Value&quot; and &quot;Amount&quot; is given by my dataset. The following code works for me:</p> <pre><code>library(minpack.lm) ### I set the following starting values for z, k and g: z &lt;- 10 k &lt;- 0.1 g &lt;- 1 ### This is my nls function and formula: nlsfit &lt;- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z), data = df, control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), start = list(z = z, k = k, g = g)) </code></pre> <p>However, I know that variables &quot;color&quot; and &quot;Year&quot; may have an impact on my regression and results, and thus I want to control for these. In a regular lm regression, I am able to add these categorical variables, but in the nlsLM function, I get an error. When adding Color as a control variable, I get:</p> <pre><code>&gt; nlsfit &lt;- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + Color, + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in (k/z) * log(Value^z + g * Amount^z) + Color : non-numeric argument to binary operato </code></pre> <p>And when adding factor(Year) as a control variable, I get:</p> <pre><code>&gt; nlsfit &lt;- nlsLM(formula = log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + factor(Year), + data = df, + control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280), + start = list(z = z, k = k, g = g)) Error in numericDeriv(form[[3L]], names(ind), env) : Missing value or an infinity produced when evaluating the model </code></pre> <p>I want to add both Color and Year in the (same) nls-function as categorical control variables.</p> <p>I know NLS might have some problems with categorical variables. I am appreciative for any help or suggestions for other types of solutions or work-arounds.</p>
[ { "answer_id": 74658993, "author": "DaveArmstrong", "author_id": 8206434, "author_profile": "https://Stackoverflow.com/users/8206434", "pm_score": 0, "selected": false, "text": " df <- data.frame(Year=c(1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1991, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1992, 1993, 1993, 1993, 1993,\n 1993, 1993, 1993, 1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996,\n 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000,\n 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003),\n Color=c(\"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \n \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \n \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\",\n \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\",\n \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\",\n \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \n \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\", \"blue\", \n \"green\", \"yellow\", \"orange\", \"purple\", \"red\", \"white\", \"brown\"),\n Y=c(6.9, 53.6, 3.9, 7.6, 17.3, 29.9, 35.1, 6.2, 6.9, 53.6, 3.6, 8.8, 10.6, 29.9, 23.2, 8.8, 5.8, 51.0, 5.8, 3.9, 9.9, 21.0, 35.8, 6.9, 3.9, 69.5, 5.4, 3.6,\n 13.2, 32.8, 27.3, 8.0, 6.2, 66.2, 3.2, 3.9, 10.6, 27.6, 23.9, 11.7, 8.8, 49.5, 4.3, 4.7, 7.3, 33.2, 18.8, 18.4, 8.8, 49.9, 2.5, 27.6, 11.4, 56.9, 16.9, 9.9,\n 3.6, 59.9, 0.6, 19.9, 16.2, 38.4, 19.9, 12.8, 7.3, 49.5, 2.5, 11.4, 11.4, 32.5, 25.8, 31.4, 4.7, 60.6, 5.4, 14.3, 16.5, 51.4, 26.5, 21.4, 6.5, 61.4, 5.1, 14.7,\n 12.1, 53.6, 22.1, 15.8, 6.5, 61.0, 3.9, 14.3, 12.1, 69.1, 28.4, 18.8, 6.5, 76.9, 1.7, 8.0, 9.1, 43.9, 21.0, 17.3, 3.6, 63.6, 2.8, 9.9, 5.1, 35.1, 20.6, 16.5),\n Value=c(45048.7, 218638.3, 39069.9, 10740.1, 62575.7, 76967.4, 226646.2, 36693.8, 40915.0, 247665.1, 43910.4, 11429.4, 60295.5, 76426.6, 244191.4,\n 36749.2, 35005.8, 228515.1, 42248.2, 10285.1, 60681.4, 72030.6, 229893.0, 36404.7, 43749.9, 268866.1, 38835.1, 11899.6, 58424.4, 82731.1,\n 255466.1, 31277.1, 55047.2, 305402.5, 39084.3, 13398.4, 65122.4, 79750.5, 281509.4, 35542.1, 47780.8, 327010.6, 44074.8, 14565.8, 70142.8,\n 104683.1, 315443.8, 46939.5, 41387.0, 327226.5, 44330.9, 16046.2, 67922.8, 122232.1, 323685.2, 44895.5, 36323.1, 346799.2, 43400.6, 16547.5,\n 77243.2, 111932.1, 331698.8, 47992.3, 34636.8, 357551.3, 41798.8, 17346.3, 87586.4, 99095.4, 366299.7, 53745.3, 39918.4, 357564.7, 43367.9,\n 17921.5, 96130.4, 101582.7, 399612.1, 40792.3, 45870.7, 360308.6, 46312.0, 20444.3, 101972.7, 96745.6, 439824.2, 49499.2, 48152.0, 346522.2,\n 54800.0, 20503.6, 98936.7, 105203.3, 436226.9, 40983.5, 53812.9, 351838.8, 55071.2, 20865.7, 99782.6, 112538.4, 474671.2, 43175.7, 53994.5,\n 333412.4, 54407.9, 19528.1, 95297.1, 101047.5, 470599.2, 33293.8),\n Amount=c(22357.1, 45323.2, 7060.7, 0.2, 103671.4, 100515.1, 122229.3, 1254.9, 78600.7, 48483.2, 6291.6, 1059.7, 28861.1, 179036.4, 40044.7,\n 12921.4, 19601.9, 6095.1, 4667.4, 2194.7, 22358.8, 161020.1, 40368.1, 4000.5, 139611.6, 45724.9, 1262.3, 86.4, 88898.4, 85844.9,\n 262167.2, 19233.5, 21174.3, 16797.2, 246.0, 4284.0, 124309.9, 109092.7, 80172.1, 5315.0, 17300.8, 58570.1, 4240.7, 29715.0, 67126.6,\n 42928.3, 132263.8, 12182.9, 77751.4, 117453.7, 443.9, 21868.6, 63683.6, 212790.1, 28990.6, 0.2, 39413.4, 134290.1, 4665.5, 0.2,\n 135307.1, 114914.2, 258602.7, 0.2, 3391.7, 74113.6, 3070.4, 17796.6, 6223.9, 188960.2, 260430.1, 0.2, 16379.0, 37389.8, 2587.3,\n 1149.9, 54814.3, 183559.8, 55877.1, 0.2, 5835.3, 39010.5, 8263.9, 13463.9, 40232.7, 152270.9, 314975.1, 119611.4, 5811.2, 102397.5,\n 6479.1, 890.6, 24356.6, 68414.0, 85800.6, 16564.8, 9218.9, 170079.5, 5181.0, 3378.0, 37603.9, 98078.2, 533192.3, 5753.8, 41286.3,\n 43227.9, 2494.7, 9025.1, 20819.6, 45227.4, 563984.9, 7129.6))\n library(minpack.lm)\n### I set the following starting values for z, k and g:\nz <- 10\nk <- 0.1\ng <- 1\n\n\ndf$Year <- as.factor(df$Year)\ndf$Color <- as.factor(df$Color)\nX <- model.matrix(~Color + Year, data=df)[,-1]\ndf <- cbind(df, X)\n\nform <- paste0(\"log(Y) ~ (k/z)*log(Value^z + g*Amount^z) + \", paste(paste0(\"b\", 1:ncol(X)), \"*\", colnames(X), collapse=\" + \"))\n\nnlsfit <- nlsLM(formula = form ,\n data = df,\n control = nls.lm.control(ftol = 1e-10, ptol = 1e-10, maxiter = 280),\n start = list(z = z, k = k, g = g, b1=0, \n b2=0, b3=0, b4=0, b5=0, b6=0, \n b7=0, b8=0, b9=0, b10=0, \n b11=0, b12=0, b13=0, b14=0, \n b15=0, b16=0, b17=0, b18=0, \n b19=0, b20=0))\npars <- nlsfit$m$getPars()\npars\n#> z k g b1 b2 \n#> -2.176726e+00 1.697185e-01 -1.520116e-12 7.285176e-01 1.961322e+00 \n#> b3 b4 b5 b6 b7 \n#> 6.062530e-01 5.360258e-01 1.722828e+00 1.062541e+00 -6.178919e-01 \n#> b8 b9 b10 b11 b12 \n#> -6.618152e-02 -1.544231e-01 -1.186151e-01 -1.567786e-01 -1.044543e-01 \n#> b13 b14 b15 b16 b17 \n#> 6.997504e-02 -1.969730e-01 -4.729006e-02 2.103823e-01 1.488066e-01 \n#> b18 b19 b20 \n#> 1.950499e-01 -1.005054e-01 -2.060658e-01\nb <- pars[4:23]\nxb <- X %*% b\nfit <- (pars[2]/pars[1])*log(df$Value^pars[1] + pars[3]*df$Amount^pars[1]) + xb\nplot(fit, log(df$Y))\n NaN NaN" }, { "answer_id": 74667830, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "nls plinear k Color Year g g g fm Color k Year fm2 g_seq <- seq(-1, 1, .01)\nmColor <- model.matrix(~ Color, df)[, -1]\nmYear <- model.matrix(~ Year, transform(df, Year = factor(Year)))[, -1]\nrss <- sapply(g_seq, function(g) try(deviance(\n nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor),\n df, start = list(z = 1), algorithm = \"plinear\"))))\nrss <- as.numeric(rss)\ng <- g_seq[which.min(rss)]\ng\n## [1] 0.19\n\n# fit with best g obtained above\nfm <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mYear, mColor), df,\n start = list(z = 1), algorithm = \"plinear\")\n\n# fit without mYear\nfm2 <- nls(log(Y) ~ cbind(k = (1/z) * log(Value^z + g*Amount^z), mColor), df,\n start = list(z = 1), algorithm = \"plinear\")\n\nsummary(fm2)\n Formula: log(Y) ~ cbind(k = (1/z) * log(Value^z + g * Amount^z), mColor)\n\nParameters:\n Estimate Std. Error t value Pr(>|t|) \nz 0.97166 5.47654 0.177 0.859525 \n.lin.k 0.16467 0.01472 11.185 < 2e-16 ***\n.lin.Colorbrown 0.81941 0.15972 5.130 1.37e-06 ***\n.lin.Colorgreen 1.98067 0.17444 11.354 < 2e-16 ***\n.lin.Colororange 0.60442 0.14776 4.091 8.55e-05 ***\n.lin.Colorpurple 0.53150 0.15857 3.352 0.001124 ** \n.lin.Colorred 1.70567 0.16161 10.554 < 2e-16 ***\n.lin.Colorwhite 1.07264 0.16924 6.338 6.24e-09 ***\n.lin.Coloryellow -0.60455 0.16543 -3.654 0.000408 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 0.4083 on 103 degrees of freedom\n\nNumber of iterations to convergence: 7 \nAchieved convergence tolerance: 9.09e-06\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667228/" ]
74,658,732
<p>Having this dataframe:</p> <pre><code>df_grafico2 = pd.DataFrame(data = { &quot;Usos&quot; : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'], &quot;Periodo&quot; : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*'], &quot;Dolares&quot; : [5247,869,2227,393,991,606,104,57,6074,996,2334,601,1231,676,202,33] }) </code></pre> <p>I've tryied this plot:</p> <pre><code>plot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != &quot;Total&quot;], x = &quot;Usos&quot;, y = &quot;Dolares&quot;,color=&quot;Periodo&quot;, barmode=&quot;group&quot;, template=&quot;none&quot;, hover_data =[&quot;Periodo&quot;, &quot;Dolares&quot;], ) plot_impo_usos.update_yaxes(tickformat = &quot;,&quot;,title_text='En millones de USD') plot_impo_usos.update_layout(separators=&quot;,.&quot;,font_family='georgia', title_text = &quot;Importación por usos económicos. Octubre de 2022 y octubre de 2021&quot;, legend=dict( yanchor=&quot;top&quot;, orientation = &quot;h&quot;, y=1.07, xanchor=&quot;left&quot;, x=0.3)) </code></pre> <p>But the hover changes automaticaly into &quot;sum of Dolares&quot;, and it won't be possible to get the &quot;Dolares&quot; name back, even if I try this:</p> <pre><code>labels={&quot;Usos&quot;:&quot;Uso&quot;,&quot;sum of Dólares&quot;: &quot;Dólares&quot;} </code></pre> <p><a href="https://i.stack.imgur.com/SjW2E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SjW2E.png" alt="hover sum of dol" /></a></p> <p>The best outcome would be a hover template with: &quot;Periodo&quot;, &quot;Uso&quot; and &quot;Dolares&quot; (with $ before). I've tried this, but it won't work neither:</p> <pre><code>plot_impo_usos.update_traces(hovertemplate='Periodo: %{color} &lt;br&gt;Uso: %{x} &lt;br&gt;Dolares: $%{y}') </code></pre> <p><a href="https://i.stack.imgur.com/99UtK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/99UtK.png" alt="enter image description here" /></a></p> <p>Help is much appreciated!</p>
[ { "answer_id": 74663702, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 1, "selected": false, "text": "import plotly.express as px\n\nplot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != \"Total\"],\n x = \"Usos\",\n y = \"Dolares\",\n color=\"Periodo\",\n barmode=\"group\",\n template=\"none\",\n hover_data =[\"Periodo\", \"Dolares\"],\n )\n\nplot_impo_usos.data[0].hovertemplate = 'Periodo: Octubre 2021*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\nplot_impo_usos.data[1].hovertemplate = 'Periodo: Octubre 2022*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\n\nplot_impo_usos.update_yaxes(tickformat = \",\",\n title_text='En millones de USD')\nplot_impo_usos.update_layout(separators=\",.\",\n font_family='georgia',\n title_text = \"Importación por usos económicos. Octubre de 2022 y octubre de 2021\",\n legend=dict(\n yanchor=\"top\",\n orientation = \"h\",\n y=1.07,\n xanchor=\"left\",\n x=0.3\n )\n )\n\nplot_impo_usos.show()\n" }, { "answer_id": 74667573, "author": "EricLavault", "author_id": 2529954, "author_profile": "https://Stackoverflow.com/users/2529954", "pm_score": 0, "selected": false, "text": "hovertemplate %{fullData.name} %{color} plot_impo_usos.update_traces(\n hovertemplate='Periodo: %{fullData.name}<br>Uso: %{x}<br>Dolares: %{y:$,.2f}<extra></extra>'\n)\n hovertemplate <extra> <extra></extra> fullData.name px.histogram() color" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15204101/" ]
74,658,809
<p>Tring to move a PDF file from <code>Resources\Raw</code> to <code>appData</code> directory for App. File becomes corrupted on copy. Obviously I'm missing something.</p> <p>using the following:</p> <pre><code> using var stream = await FileSystem.OpenAppPackageFileAsync(&quot;CBA2015.pdf&quot;); using var reader = new StreamReader(stream); if (stream != null) { var contents = reader.ReadToEnd(); string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, &quot;CBA2015.pdf&quot;); using FileStream outputStream = System.IO.File.OpenWrite(targetFile); using StreamWriter streamWriter = new StreamWriter(outputStream); await streamWriter.WriteAsync(contents); } </code></pre> <pre><code></code></pre>
[ { "answer_id": 74663702, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 1, "selected": false, "text": "import plotly.express as px\n\nplot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != \"Total\"],\n x = \"Usos\",\n y = \"Dolares\",\n color=\"Periodo\",\n barmode=\"group\",\n template=\"none\",\n hover_data =[\"Periodo\", \"Dolares\"],\n )\n\nplot_impo_usos.data[0].hovertemplate = 'Periodo: Octubre 2021*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\nplot_impo_usos.data[1].hovertemplate = 'Periodo: Octubre 2022*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\n\nplot_impo_usos.update_yaxes(tickformat = \",\",\n title_text='En millones de USD')\nplot_impo_usos.update_layout(separators=\",.\",\n font_family='georgia',\n title_text = \"Importación por usos económicos. Octubre de 2022 y octubre de 2021\",\n legend=dict(\n yanchor=\"top\",\n orientation = \"h\",\n y=1.07,\n xanchor=\"left\",\n x=0.3\n )\n )\n\nplot_impo_usos.show()\n" }, { "answer_id": 74667573, "author": "EricLavault", "author_id": 2529954, "author_profile": "https://Stackoverflow.com/users/2529954", "pm_score": 0, "selected": false, "text": "hovertemplate %{fullData.name} %{color} plot_impo_usos.update_traces(\n hovertemplate='Periodo: %{fullData.name}<br>Uso: %{x}<br>Dolares: %{y:$,.2f}<extra></extra>'\n)\n hovertemplate <extra> <extra></extra> fullData.name px.histogram() color" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668345/" ]
74,658,813
<p>How to extract current branch name from git log</p> <p>How to extract current branch name from git log</p> <p>when I use the **</p> <pre><code>log -n 1 --pretty=%d HEAD </code></pre> <p>** then the following output is showing (HEAD -&gt; branch1, origin/branch1 , orign/branch3 , origin/branch4 etc....)</p> <p>But I want to extract only the current branch name from the git log, Can someone please help ?</p> <p><strong>Limitation:</strong> I want to achive this only by using **git log ** command.</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17005621/" ]
74,658,816
<p>I'm using js-interop to use the File System Access API with Dart in a web environment. I would like to store a <code>FileSystemDirectoryHandle</code> in IndexedDB to reuse it later.</p> <p>When storing an instance of <code>FileSystemDirectoryHandle</code> in IndexedDB, the data is a Dart object (Symbol when exploring the value in DevTools). When I read back, value is not a <code>FileSystemDirectoryHandle</code> and all informations of the object is lost and useless.</p> <p>I did not find a way to store a handle into IndexedDB and read it back as a <code>FileSystemDirectoryHandle</code>.</p> <p>Below is parts of the code I declare with js-interop:</p> <pre class="lang-dart prettyprint-override"><code>// Only to keep track of API's types definitions. typedef Promise&lt;T&gt; = dynamic; // FileSystemHandle and *Options are declared in the same way. @JS() class FileSystemDirectoryHandle extends FileSystemHandle { external Promise&lt;FileSystemFileHandle&gt; getFileHandle(String name, [FileSystemGetFileOptions? options]); external Promise&lt;FileSystemDirectoryHandle&gt; getDirectoryHandle(String name, [FileSystemGetDirectoryOptions? options]); external Promise&lt;void&gt; removeEntry(String name, [FileSystemRemoveOptions? options]); external Promise&lt;List&lt;String&gt;?&gt; resolve(FileSystemHandle possibleDescendant); } </code></pre> <p>Here is what I'm trying to achieve:</p> <pre class="lang-dart prettyprint-override"><code>final handle = await js.promiseToFuture(window.showDirectoryPicker()); // Storage use dart:indexed_db in a homebrew implementation (tested and works fine with // primitive types). await storage.set(&quot;dir&quot;, handle); // Reload page... // Dynamic only final directory = await storage.get(&quot;dir&quot;); print(directory.name); // Typed FileSystemDirectoryHandle dirHandle = directory as FileSystemDirectoryHandle; print(dirHandle.name); </code></pre> <p>Calling dynamic <code>directory.name</code> throws a <code>NoSuchMethodError</code>:</p> <blockquote> <p>Uncaught (in promise) Error: NoSuchMethodError: 'name'</p> <p>method not found</p> <p>Receiver: Instance of 'LinkedMap&lt;dynamic, dynamic&gt;'</p> </blockquote> <p>Calling typed <code>dirHandle.name</code> throws an <code>Error</code>:</p> <blockquote> <p>Error: Expected a value of type 'FileSystemDirectoryHandle', but got one of type 'LinkedMap&lt;dynamic, dynamic&gt;'</p> </blockquote> <p><a href="https://i.stack.imgur.com/AFtka.png" rel="nofollow noreferrer">Screenshot of IndexedDB in DevTools, when storing from Dart, and storing from JavaScript</a></p> <p>My understanding of js-interop is that it translates JavaScript object into a Dart proxy. As I'm sending a Dart object, it does not serialize the JavaScript object, but the Dart proxy object. Therefore the JavaScript object is lost in the process.</p> <p>Is there a way to pass the JavaScript object to IndexedDB from Dart? Or at least serialize the native JavaScript object from Dart proxy and then send it into IndexedDB?</p> <p>Any guidance would be much appreciated.</p> <p>Issue on dart-lang/sdk repository <a href="https://github.com/dart-lang/sdk/issues/50621" rel="nofollow noreferrer">#50621</a></p> <p>More on this <a href="https://github.com/poirierlouis/file_system_access_api" rel="nofollow noreferrer">repository</a>, usage in <a href="https://github.com/poirierlouis/file_system_access_api/blob/master/example/tree_viewer_tab.dart#L20" rel="nofollow noreferrer">example here</a>, and <a href="https://github.com/poirierlouis/file_system_access_api/blob/master/lib/src/wrapper/file_system_handle.dart" rel="nofollow noreferrer">js-interop here</a>.</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600235/" ]
74,658,820
<p><strong>Return Error when Im tried to make a class.</strong></p> <p>When I tried as here <a href="https://www.stackoverflow.com/">https://github.com/google/mediapipe/blob/master/docs/solutions/face_mesh.md#python-solution-api</a>. everething is perfect</p> <p>There are some problem with self. method. But I could not undestand where exactly</p> <pre class="lang-py prettyprint-override"><code>import cv2 import mediapipe as mp import time class FaceMeshDetector: def __init__(self, static_mode=False, maxFaces=2, minDetectionCon=0.5, minTrackCon=0.5): self.static_mode = static_mode self.maxFaces = maxFaces self.minDetectionCon = minDetectionCon self.minTrackCon = minTrackCon self.mpDraw = mp.solutions.drawing_utils self.mpFaceMesh = mp.solutions.face_mesh self.faceMesh = self.mpFaceMesh.FaceMesh(self.static_mode, self.maxFaces, self.minDetectionCon, self.minTrackCon) self.drawSpec = self.mpDraw.DrawingSpec(thickness=1, circle_radius=1) def findFaceMesh(self, img, draw=True): self.imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.results = self.faceMesh.process(self.imgRGB) faces = [] if self.results.multi_face_landmarks: for faceLms in self.results.multi_face_landmarks: if draw: self.mpDraw.draw_landmarks(img, faceLms, self.mpFaceMesh.FACEMESH_CONTOURS, self.drawSpec, self.drawSpec) face = [] for id, lm in enumerate(faceLms.landmark): # print(lm) ih, iw, ic = img.shape x, y = int(lm.x * iw), int(lm.y * ih) # cv2.putText(img, str(id), (x, y), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 255, 0), 1) # print(id, x, y) face.append([x, y]) faces.append(face) return img, faces def main(): cap = cv2.VideoCapture(0) pTime = 0 detector = FaceMeshDetector() while True: success, img = cap.read() img, faces = detector.findFaceMesh(img) if len(faces) != 0: print(faces[0]) cTime = time.time() fps = 1 / (cTime - pTime) pTime = cTime cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 3) cv2.imshow(&quot;Image&quot;, img) cv2.waitKey(1) if __name__ == '__main__': main() </code></pre> <p><strong>Full traceback</strong></p> <p>Traceback (most recent call last): File &quot;C:\Users\Roman\PycharmProjects\pythonProject\FaceMeshModule.py&quot;, line 59, in main() File &quot;C:\Users\Roman\PycharmProjects\pythonProject\FaceMeshModule.py&quot;, line 44, in main detector = FaceMeshDetector() File &quot;C:\Users\Roman\PycharmProjects\pythonProject\FaceMeshModule.py&quot;, line 16, in <strong>init</strong> self.minTrackCon) File &quot;C:\Users\Roman\PycharmProjects\pythonProject\venv\lib\site-packages\mediapipe\python\solutions\face_mesh.py&quot;, line 107, in <strong>init</strong> outputs=['multi_face_landmarks']) File &quot;C:\Users\Roman\PycharmProjects\pythonProject\venv\lib\site-packages\mediapipe\python\solution_base.py&quot;, line 291, in <strong>init</strong> for name, data in (side_inputs or {}).items() File &quot;C:\Users\Roman\PycharmProjects\pythonProject\venv\lib\site-packages\mediapipe\python\solution_base.py&quot;, line 291, in for name, data in (side_inputs or {}).items() File &quot;C:\Users\Roman\PycharmProjects\pythonProject\venv\lib\site-packages\mediapipe\python\solution_base.py&quot;, line 592, in <em>make_packet return getattr(packet_creator, 'create</em>' + packet_data_type.value)(data) TypeError: create_bool(): incompatible function arguments. The following argument types are supported: 1. (arg0: bool) -&gt; mediapipe.python._framework_bindings.packet.Packet</p> <p>Invoked with: 0.5</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668220/" ]
74,658,862
<p>My goal is to write an algorithm that checks if an unsorted array of positive integers contains a value x and x^2 and return their indices if so. I've solved this by proposing that first you sort the array using merge sort, then perform binary search for x, then perform binary search for x^2. I then wrote that &quot;since binary search has worst-case runtime of O(log n) and merge sort has worst-case runtime of O(n log n), we conclude that the worst-case runtime of this algorithm is O(n log n).&quot; Am I correct in my understanding that when analyzing the overall efficiency of an algorithm that involves steps with different runtimes, we just take the one with the longest runtime? Or is it more involved than this? Thanks in advance!</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16689751/" ]
74,658,900
<p>I have 2 models named AdminContent, AdminCategory. I have content_category_id in my admin_contents table. I have category_id and category_name in my admin_categories table. I linked category_id with content_category_id foreign. I am using the hasOne() function in my Admin Content model. But I get the error Using $this when not in object context! My main goal is to get content_category_id value from admin_categories table name column</p> <p><strong>Migrations</strong></p> <pre><code>// Admin Categories Migration Schema::create( 'admin_categories', function(Blueprint $table) { $table-&gt;bigIncrements('ctgry_id')-&gt;unique(); $table-&gt;string('category_name', 50)-&gt;unique(); $table-&gt;timestamps(); }); </code></pre> <pre><code>// Admin Contents Migration Schema::create('admin_contents', function (Blueprint $table) { $table-&gt;bigIncrements('cntnt_id')-&gt;unique(); $table-&gt;string('content_title'); $table-&gt;text('content_content'); $table-&gt;string('content_slug'); $table-&gt;bigInteger('content_category_id'); $table-&gt;foreign('content_category_id')-&gt;references('ctgry_id')-&gt;on('admin_categories'); $table-&gt;string('content_status'); $table-&gt;string('create_user'); $table-&gt;string('content_tags'); $table-&gt;string('content_excerpt'); $table-&gt;dateTime('posted_at'); $table-&gt;timestamps(); }); </code></pre> <p><strong>Models</strong></p> <pre><code>// AdminContent Model protected $table = &quot;admin_contents&quot;; protected $fillable = [ 'content_title', 'content_content', 'content_category_id', 'content_status', 'create_user','content_tags', 'content_excerpt', 'created_at', 'updated_at' ]; protected $guards = [ 'cntnt_id', ]; public function setCategoryName() { return $this-&gt;hasOne(AdminCategory::class); } </code></pre> <p>When I want to access with $this-&gt;hasOne(AdminCategory::class) I get this error!</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668283/" ]
74,658,907
<p>I use toString and I print out the output like below. I want to align it like a timetable using toString, but I can't.</p> <p>what I print</p> <p>NAME: Poon</p> <p>IC NO: 000912</p> <p>TAXABLE INCOME 85000.0</p> <p>STATUS :S</p> <p>TAX AMOUNT: 17000.0</p> <p>what I use public String toString(){ return person+&quot;\nTAXABLE INCOME&quot; + taxableIncome +&quot;\nSTATUS :&quot;+status+ &quot;\nTAX AMOUNT: &quot; + taxAmount ; }</p> <p>Required output:</p> <pre class="lang-none prettyprint-override"><code>name iCNO taxableincome taxableAmount Poon 00654 6546546 465 </code></pre> <p>the required output is somekind like this format I want to print</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654455/" ]
74,658,909
<pre><code>&lt;FormWrap&gt; &lt;FormImg img src='./img/CB.png' alt=&quot;CB&quot; /&gt; &lt;FormContent&gt; &lt;Form onSubmit={handleSubmit}&gt; {errorMessage &amp;&amp; (&lt;p className=&quot;errorM&quot;&gt; {errorMessage} &lt;/p&gt;)} &lt;FormH1&gt;Log in to your account&lt;/FormH1&gt; &lt;FormLabel htmlFor='for'&gt;Email&lt;/FormLabel&gt; &lt;FormInput type='text' value={email} required onChange={e =&gt; setemail(e.target.value)}/&gt; &lt;FormLabel htmlFor='for'&gt;Password&lt;/FormLabel&gt; &lt;FormInput type='password' value={password} required onChange={e =&gt; setpassword(e.target.value)}/&gt; &lt;FormButton type='submit'&gt;Sign in&lt;/FormButton&gt; &lt;Navtext&gt; &lt;NavtextLink to=&quot;/Register&quot;&gt;Register&lt;/NavtextLink&gt; &lt;/Navtext&gt; &lt;/Form&gt; &lt;/FormContent&gt; &lt;/FormWrap&gt; </code></pre> <pre><code>export const errorM = styled.p` width:1000px; height:692px; background:black; color:white; display:grid; grid-template-columns: 1fr 6fr; position:relative; border-radius:10px; ` export const FormWrap = styled.div` width:800px; height:692px; background:white; color:yellow; display:grid; grid-template-columns: 1fr 6fr; position:relative; border-radius:10px; @media screen and (max-width: 980px){ height:95%; padding:50px; } @media screen and (max-width: 720px){ height:90%; padding-left:95px; } ` </code></pre> <p>The thing is that errorM is taking the style from FormWrap even through the one is <p> and the other is &lt;div.I tried to make inline style but then only that I managed to change was the cooler of the texts tried to change the fond but nothing happened.</p>
[ { "answer_id": 74659013, "author": "Romain Valeri", "author_id": 1057485, "author_profile": "https://Stackoverflow.com/users/1057485", "pm_score": 0, "selected": false, "text": "sed git log -1 --pretty=%d | sed -E 's/^.*HEAD -> ([^\\,]*)\\,.*$/\\1/'\n HEAD" }, { "answer_id": 74659115, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 0, "selected": false, "text": "git rev-parse --abbrev-ref HEAD\n" }, { "answer_id": 74659355, "author": "jthill", "author_id": 1290731, "author_profile": "https://Stackoverflow.com/users/1290731", "pm_score": 1, "selected": false, "text": "HEAD git for-each-ref --format='%(refname:short)' --points-at HEAD\n git log --no-walk --decorate-refs=refs/ --pretty=%D\n refs/heads --decorate-refs=refs/heads" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16640780/" ]
74,658,926
<pre><code>enhancerlist=[[5,8],[10,11]] TFlist=[[6,7],[24,56]] </code></pre> <p>I have two lists of lists. I am trying to isolate the sublists in my 'TFlist' that don't fit in the range of ANY of the sublists of enhancerlist (by range: TFlist sublist range fits inside of enhancerlist sublist range). SO for example, TFlist[1] will not occur in the range of any sublists in enhancerlist (whereas TFlist [6,7] fits inside the range of [5,8]) , so I want this as output:</p> <p>TF_notinrange=[24,56]</p> <p>the problem with a nested for loop like this:</p> <pre><code>while TFlist: TF=TFlist.pop() for j in enhancerlist: if ((TF[0]&gt;= j[0]) and (TF[1]&lt;= j[1])): continue else: TF_notinrange.append(TF) </code></pre> <p>is that I get this as output: [[24, 56], [3, 4]]</p> <p>the if statement is checking one sublist in enhancerlist at a time and so will append TF even if, later on, there is a sublist it is in the range of.</p> <p>Could I somehow do a while loop with the condition? although it seems like I still have the issue of a nested loop appending things incorrectly ?</p>
[ { "answer_id": 74659114, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 1, "selected": false, "text": "TF_notinrange = [tf for tf in TFlist \n if not any(istart <= tf[0] <= tf[1] <= iend \n for istart, iend in enhancerlist)]\nprint(TF_notinrange)\n>>> TF_notinrange\n" }, { "answer_id": 74659184, "author": "ddejohn", "author_id": 6298712, "author_profile": "https://Stackoverflow.com/users/6298712", "pm_score": 0, "selected": false, "text": "for-else else for non_overlapping = []\n\nfor tf_a, tf_b in TFlist:\n for enhancer_a, enhancer_b in enhancerlist:\n if enhancer_a <= tf_a < tf_b <= enhancer_b:\n break\n else:\n non_overlapping.append([tf_a, tf_b])\n (2, 2)" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20257102/" ]
74,658,982
<p>I've encountered a problem in Excel that I don't know how to approach solving.</p> <p><a href="https://i.stack.imgur.com/213Ye.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/213Ye.png" alt="enter image description here" /></a></p> <p>There are two tables in the image above.</p> <p>Table 1 is a list of gifts exchanged between individuals, with the giver and the receiver identified. (I'm using &quot;gifts&quot; and &quot;people&quot; to make it easier to discuss here. In reality these are pieces of equipment exchanging control signals. This table can be hundreds of rows long.)</p> <p>Table 2, columns E and F, is a list of unique person-pairs (irrespective of giver and receiver). I have already written formulas to search columns A and B and return only unique pairs in E and F. Now, for each unique pair, I need to return all of the gifts exchanged between the two individuals in column G (I have manually entered what column G <em>should</em> contain with a working formula.</p> <p>I'm not even sure where to begin with this problem. Column G3's formula should have something like the following in it:</p> <pre><code>=and(or(B3=$E$3,C3=$E$3),or(B3=$F$3,C3=$F$3)),A3,&quot;&quot;) </code></pre> <p>But then, the cell needs to search the entire range B:B and C:C and TEXTJOIN every A:A in which the conditions are met.</p> <p>I am fine using VBA for a solution (even then, I'm not sure where to begin), but would prefer not; the data will be imported into another piece of software and that software can't execute VBA code.</p> <p>Can anyone point me in the right direction?</p> <p>Thanks for your help.</p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74658982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668151/" ]
74,659,010
<p>I'm creating a table that I'd like to search by he first column (number + % sign). I've got it set up so I can search for the number, but need it to return the exact number without necessitating the % to be included.</p> <p>I've found a <a href="https://stackoverflow.com/questions/54700692/filter-search-table-for-exact-match">close solution here</a>, but it doesn't account for excluding the % in the search.</p> <p>Here's an portion of the table along with the search script:</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-js lang-js prettyprint-override"><code>function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i &lt; tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) &gt; -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search ABV" title="Type in ABV"&gt; &lt;table id="myTable"&gt; &lt;tr class="header"&gt; &lt;th style="width:100%;"&gt;ABV&lt;/th&gt; &lt;th&gt;&lt;strong&gt;1 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;2 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;3 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;4 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;5 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;6 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;7 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;8 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;9 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;10 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;11 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;12 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;13 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;14 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;15 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;16 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;17 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;18 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;19 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;20 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;21 oz.&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&lt;strong&gt;22 oz.&lt;/strong&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;3%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;15&lt;/td&gt; &lt;td&gt;23&lt;/td&gt; &lt;td&gt;30&lt;/td&gt; &lt;td&gt;38&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;53&lt;/td&gt; &lt;td&gt;60&lt;/td&gt; &lt;td&gt;68&lt;/td&gt; &lt;td&gt;75&lt;/td&gt; &lt;td&gt;83&lt;/td&gt; &lt;td&gt;90&lt;/td&gt; &lt;td&gt;98&lt;/td&gt; &lt;td&gt;105&lt;/td&gt; &lt;td&gt;113&lt;/td&gt; &lt;td&gt;120&lt;/td&gt; &lt;td&gt;128&lt;/td&gt; &lt;td&gt;135&lt;/td&gt; &lt;td&gt;143&lt;/td&gt; &lt;td&gt;150&lt;/td&gt; &lt;td&gt;158&lt;/td&gt; &lt;td&gt;165&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;3.5%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;9&lt;/td&gt; &lt;td&gt;18&lt;/td&gt; &lt;td&gt;27&lt;/td&gt; &lt;td&gt;35&lt;/td&gt; &lt;td&gt;44&lt;/td&gt; &lt;td&gt;53&lt;/td&gt; &lt;td&gt;62&lt;/td&gt; &lt;td&gt;70&lt;/td&gt; &lt;td&gt;79&lt;/td&gt; &lt;td&gt;88&lt;/td&gt; &lt;td&gt;97&lt;/td&gt; &lt;td&gt;105&lt;/td&gt; &lt;td&gt;114&lt;/td&gt; &lt;td&gt;123&lt;/td&gt; &lt;td&gt;132&lt;/td&gt; &lt;td&gt;140&lt;/td&gt; &lt;td&gt;149&lt;/td&gt; &lt;td&gt;158&lt;/td&gt; &lt;td&gt;167&lt;/td&gt; &lt;td&gt;175&lt;/td&gt; &lt;td&gt;184&lt;/td&gt; &lt;td&gt;193&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;10&lt;/td&gt; &lt;td&gt;20&lt;/td&gt; &lt;td&gt;30&lt;/td&gt; &lt;td&gt;40&lt;/td&gt; &lt;td&gt;50&lt;/td&gt; &lt;td&gt;60&lt;/td&gt; &lt;td&gt;70&lt;/td&gt; &lt;td&gt;80&lt;/td&gt; &lt;td&gt;90&lt;/td&gt; &lt;td&gt;100&lt;/td&gt; &lt;td&gt;110&lt;/td&gt; &lt;td&gt;120&lt;/td&gt; &lt;td&gt;130&lt;/td&gt; &lt;td&gt;140&lt;/td&gt; &lt;td&gt;150&lt;/td&gt; &lt;td&gt;160&lt;/td&gt; &lt;td&gt;170&lt;/td&gt; &lt;td&gt;180&lt;/td&gt; &lt;td&gt;190&lt;/td&gt; &lt;td&gt;200&lt;/td&gt; &lt;td&gt;210&lt;/td&gt; &lt;td&gt;220&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4.5%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;12&lt;/td&gt; &lt;td&gt;23&lt;/td&gt; &lt;td&gt;34&lt;/td&gt; &lt;td&gt;45&lt;/td&gt; &lt;td&gt;57&lt;/td&gt; &lt;td&gt;68&lt;/td&gt; &lt;td&gt;79&lt;/td&gt; &lt;td&gt;90&lt;/td&gt; &lt;td&gt;101&lt;/td&gt; &lt;td&gt;113&lt;/td&gt; &lt;td&gt;124&lt;/td&gt; &lt;td&gt;135&lt;/td&gt; &lt;td&gt;147&lt;/td&gt; &lt;td&gt;158&lt;/td&gt; &lt;td&gt;169&lt;/td&gt; &lt;td&gt;180&lt;/td&gt; &lt;td&gt;192&lt;/td&gt; &lt;td&gt;203&lt;/td&gt; &lt;td&gt;214&lt;/td&gt; &lt;td&gt;225&lt;/td&gt; &lt;td&gt;237&lt;/td&gt; &lt;td&gt;248&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4.6%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;12&lt;/td&gt; &lt;td&gt;23&lt;/td&gt; &lt;td&gt;35&lt;/td&gt; &lt;td&gt;46&lt;/td&gt; &lt;td&gt;58&lt;/td&gt; &lt;td&gt;69&lt;/td&gt; &lt;td&gt;81&lt;/td&gt; &lt;td&gt;92&lt;/td&gt; &lt;td&gt;104&lt;/td&gt; &lt;td&gt;115&lt;/td&gt; &lt;td&gt;127&lt;/td&gt; &lt;td&gt;138&lt;/td&gt; &lt;td&gt;150&lt;/td&gt; &lt;td&gt;161&lt;/td&gt; &lt;td&gt;173&lt;/td&gt; &lt;td&gt;184&lt;/td&gt; &lt;td&gt;196&lt;/td&gt; &lt;td&gt;207&lt;/td&gt; &lt;td&gt;219&lt;/td&gt; &lt;td&gt;230&lt;/td&gt; &lt;td&gt;242&lt;/td&gt; &lt;td&gt;253&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4.7%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;12&lt;/td&gt; &lt;td&gt;24&lt;/td&gt; &lt;td&gt;36&lt;/td&gt; &lt;td&gt;47&lt;/td&gt; &lt;td&gt;59&lt;/td&gt; &lt;td&gt;71&lt;/td&gt; &lt;td&gt;83&lt;/td&gt; &lt;td&gt;94&lt;/td&gt; &lt;td&gt;106&lt;/td&gt; &lt;td&gt;118&lt;/td&gt; &lt;td&gt;130&lt;/td&gt; &lt;td&gt;141&lt;/td&gt; &lt;td&gt;153&lt;/td&gt; &lt;td&gt;165&lt;/td&gt; &lt;td&gt;177&lt;/td&gt; &lt;td&gt;188&lt;/td&gt; &lt;td&gt;200&lt;/td&gt; &lt;td&gt;212&lt;/td&gt; &lt;td&gt;224&lt;/td&gt; &lt;td&gt;235&lt;/td&gt; &lt;td&gt;247&lt;/td&gt; &lt;td&gt;259&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4.8%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;12&lt;/td&gt; &lt;td&gt;24&lt;/td&gt; &lt;td&gt;36&lt;/td&gt; &lt;td&gt;48&lt;/td&gt; &lt;td&gt;60&lt;/td&gt; &lt;td&gt;72&lt;/td&gt; &lt;td&gt;84&lt;/td&gt; &lt;td&gt;96&lt;/td&gt; &lt;td&gt;108&lt;/td&gt; &lt;td&gt;120&lt;/td&gt; &lt;td&gt;132&lt;/td&gt; &lt;td&gt;144&lt;/td&gt; &lt;td&gt;156&lt;/td&gt; &lt;td&gt;168&lt;/td&gt; &lt;td&gt;180&lt;/td&gt; &lt;td&gt;192&lt;/td&gt; &lt;td&gt;204&lt;/td&gt; &lt;td&gt;216&lt;/td&gt; &lt;td&gt;228&lt;/td&gt; &lt;td&gt;240&lt;/td&gt; &lt;td&gt;252&lt;/td&gt; &lt;td&gt;264&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;4.9%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;13&lt;/td&gt; &lt;td&gt;25&lt;/td&gt; &lt;td&gt;37&lt;/td&gt; &lt;td&gt;49&lt;/td&gt; &lt;td&gt;62&lt;/td&gt; &lt;td&gt;74&lt;/td&gt; &lt;td&gt;86&lt;/td&gt; &lt;td&gt;98&lt;/td&gt; &lt;td&gt;110&lt;/td&gt; &lt;td&gt;123&lt;/td&gt; &lt;td&gt;135&lt;/td&gt; &lt;td&gt;147&lt;/td&gt; &lt;td&gt;160&lt;/td&gt; &lt;td&gt;172&lt;/td&gt; &lt;td&gt;184&lt;/td&gt; &lt;td&gt;196&lt;/td&gt; &lt;td&gt;209&lt;/td&gt; &lt;td&gt;221&lt;/td&gt; &lt;td&gt;233&lt;/td&gt; &lt;td&gt;245&lt;/td&gt; &lt;td&gt;258&lt;/td&gt; &lt;td&gt;270&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;5%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;13&lt;/td&gt; &lt;td&gt;25&lt;/td&gt; &lt;td&gt;38&lt;/td&gt; &lt;td&gt;50&lt;/td&gt; &lt;td&gt;63&lt;/td&gt; &lt;td&gt;75&lt;/td&gt; &lt;td&gt;88&lt;/td&gt; &lt;td&gt;100&lt;/td&gt; &lt;td&gt;113&lt;/td&gt; &lt;td&gt;125&lt;/td&gt; &lt;td&gt;138&lt;/td&gt; &lt;td&gt;150&lt;/td&gt; &lt;td&gt;163&lt;/td&gt; &lt;td&gt;175&lt;/td&gt; &lt;td&gt;188&lt;/td&gt; &lt;td&gt;200&lt;/td&gt; &lt;td&gt;213&lt;/td&gt; &lt;td&gt;225&lt;/td&gt; &lt;td&gt;238&lt;/td&gt; &lt;td&gt;250&lt;/td&gt; &lt;td&gt;263&lt;/td&gt; &lt;td&gt;275&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;5.1%&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;13&lt;/td&gt; &lt;td&gt;26&lt;/td&gt; &lt;td&gt;39&lt;/td&gt; &lt;td&gt;51&lt;/td&gt; &lt;td&gt;64&lt;/td&gt; &lt;td&gt;77&lt;/td&gt; &lt;td&gt;90&lt;/td&gt; &lt;td&gt;102&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668437/" ]
74,659,026
<p>I have a Blazor web project, and am getting errors on one rather large page file when I build. There are no errors if I close and relaunch VS 2022, until I build. Then, it says there are 2 errors (&quot;} expected&quot; and &quot;; expected&quot;), but it shows them in the .g file, and when I double-click on the error line in the Error window, nothing happens.</p> <p>How do I trace to where in the source code the bad lines are? There are 1300 lines of code in this page...</p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706983/" ]
74,659,035
<p>I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.</p> <p>Here's the function:</p> <pre class="lang-py prettyprint-override"><code>async def check(message): if type == &quot;netflix&quot;: c.execute(&quot;SELECT price FROM netflix&quot;) neprice = c.fetchall() netprice= neprice[0][0] netfprice = netprice*amount nettax = await tax(args=netfprice) try: return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content except IndexError: return False </code></pre> <p>Here's where I call the function:</p> <pre class="lang-py prettyprint-override"><code> await bot.wait_for('message', check=check, timeout=60) </code></pre> <p>Here's the full command:</p> <pre><code>@bot.slash_command() @discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user) async def buy(message, type: str, amount:Optional[int]): if amount == None: amount = 1 if amount &lt; 0: await message.respond(&quot;You cannot buy negative amount of accounts&quot;) member = message.author con = sqlite3.connect(&quot;db.sqlite&quot;) c = con.cursor() async def check(message): if type == &quot;netflix&quot;: c.execute(&quot;SELECT price FROM netflix&quot;) neprice = c.fetchall() netprice= neprice[0][0] netfprice = netprice*amount nettax = await tax(args=netfprice) try: return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content except IndexError: return False elif type == &quot;spotify&quot; or &quot;crunchyroll&quot;: c.execute(&quot;SELECT price FROM spotify&quot;) spotiprice = c.fetchall() spotprice = spotiprice[0][0] newspot = spotprice*amount spotytax = await tax(args=newspot) print(spotiprice[0][0]) try: return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content except IndexError: return False if type == &quot;netflix&quot;: c.execute('SELECT *, COUNT(*) AS &quot;count&quot; FROM netflix GROUP BY price') netamount= c.fetchall() print(netamount[1]) if netamount[0][3] &lt; amount: await message.respond(f&quot;We do not have this amount of accounts in the stock&quot;) else: c.execute(&quot;SELECT price FROM netflix &quot;) netfprice = c.fetchall() netprice = netfprice[0][0] newnet = netprice*amount withtax = await tax(args=newnet) embed = discord.Embed(title=&quot;transfer&quot;,description=f&quot;Please transfer :{newnet + withtax}&quot;) embed.add_field(name=f&quot;c &lt;@994347081294684240&gt; {newnet + withtax}&quot;,value=&quot;**Copy paste the message for no error**&quot;) embed.set_footer(text=f&quot;Sidtho Host. | Requested by - {message.author}&quot;) print(&quot;Sent embed, Waiting for receiving the credits&quot;) await message.respond(embed=embed) await bot.wait_for('message', check=check, timeout=60) c.execute(&quot;SELECT email, password FROM netflix&quot;) netres = c.fetchmany(size=amount) # print(netres) embed = discord.Embed(title=f&quot;حساب {type}&quot;, description=&quot;&quot;) embed.add_field(name=&quot;Sidtho Host.&quot;,value=&quot; &quot;,inline=False) for thisamount in netres: try: email = thisamount[0] password= thisamount[1] embed.add_field(name=f&quot;Email: {email}&quot;, value=f&quot;Password: {password}&quot;, inline=False) # print(f&quot;The email is {email} \n The password is {password} except TypeError as err: print(f&quot;Gave A TypeError. Where {err} &quot;) await member.send(embed=embed) c.execute(&quot;DELETE FROM netflix WHERE email=? AND password=?&quot;,(email, password)) </code></pre> <p>There is no traceback So no error.</p> <p>Please note that the check function is a Function, not a command. and the await bot.wait_for is on a command.</p> <p>Please note too that <code>type</code> is a value that the user will give to the bot, and its not the python built.</p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400934/" ]
74,659,038
<p>I am having the following dataframe</p> <pre><code>data = [ [1000, 1, 1], [1000, 1, 1], [1000, 1, 1], [1000, 1, 2], [1000, 1, 2], [1000, 1, 2], [2000, 0, 1], [2000, 0, 1], [2000, 1, 2], [2000, 0, 2], [2000, 1, 2]] df = pd.DataFrame(data, columns=['route_id', 'direction_id', 'trip_id']) </code></pre> <p>Then, I group my <code>df</code> based on the columns <code>route_id</code>, <code>direction_id</code> by using:</p> <pre><code>t_groups = df.groupby(['route_id','direction_id']) </code></pre> <p>I would like to store the value of the <code>trip_id</code> column based on the <strong>first most popular</strong> <code>trip_id</code> of each unique <code>route_id</code>, <code>direction_id</code> combination.</p> <p>Ι have tried to apply a function <code>value_counts()</code> but I cannot get the first popular <code>trip_id</code> value.</p> <p>I would like my expected output to be like:</p> <pre><code> route_id direction_id trip_id 0 1000 1 1 1 2000 0 1 2 2000 1 2 </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668333/" ]
74,659,044
<p>I have the following table:</p> <pre><code>product price date banana 90 2022-01-01 banana 90 2022-01-02 banana 90 2022-01-03 banana 95 2022-01-04 banana 90 2022-01-05 banana 90 2022-01-06 </code></pre> <p>I need to add a non-unique ID column to the table. Every time the price changes, I want the ID to change. This would result in the following table.</p> <pre><code>id product price date A banana 90 2022-01-01 A banana 90 2022-01-02 A banana 90 2022-01-03 B banana 95 2022-01-04 C banana 90 2022-01-05 C banana 90 2022-01-06 </code></pre> <p>By searching for answers in SO and Google, I was able to create a column (my_seq) that contains a sequence that resets every time (see sql fiddle for my query) the price changes. But I still don't know how to create an ID column that resets every time the my_seq starts over.</p> <pre><code>my_seq rn1 rn2 product price date 1 1 1 banana 90 2022-01-01 2 2 2 banana 90 2022-01-02 3 3 3 banana 90 2022-01-03 1 1 4 banana 95 2022-01-04 1 4 5 banana 90 2022-01-05 2 5 6 banana 90 2022-01-06 </code></pre> <p><a href="http://sqlfiddle.com/#!17/51ded/2" rel="nofollow noreferrer">sql-fiddle</a> with DDL and my query</p> <p>thanks</p>
[ { "answer_id": 74659176, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": true, "text": "=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n" }, { "answer_id": 74671773, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E1 = LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n LET [Giver, Receivers] g r ux g r UNIQUE(TOCOL(B2:C9,,TRUE))\n Sam\nSally\nHenry\nMike\n TOCOL rMatch gMatch ux gMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n gMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n sorted BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n [by_col] TRUE SORT idx XMATCH(UNIQUE(sorted), sorted)\n ux gMatch rMatch #N/A FILTER(idx, ISNUMBER(idx)) idExcl idExcl pa pb pa pb g r gifts MAP VSTACK HSTACK" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935369/" ]
74,659,046
<p>I'm new to the Entity Framework and I'm having problems with properly defining relationships.</p> <p>I have a <code>Student</code> class, and a <code>Course</code> class and it's supposed to me a many to many relationship. A student can do one or more courses and a course can be done by one or more students. But when I try to run the command <code>dotnet ef migrations add InitialCreate</code> to create the initial migration, I get the error: <code>The entity type 'List&lt;int&gt;' requires a primary key to be defined</code>. Here is the <code>Student</code> class</p> <pre><code>using System; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; namespace Advisment.Models { public class Student { public int Id { get; set; } public string Name { get; set; } public int MajorId { get; set; } public int AdvisorId { get; set; } public List &lt;int&gt; CompletedCourses { get; set; }//List of courses done by student public ICollection &lt;Course&gt; Courses { get; set; }//Reference the Course class public Advisor Advisor { get; set; } public Major Major { get; set; } } } </code></pre> <p>And here is the the <code>Course</code> class:</p> <pre><code>using System; using System.ComponentModel.DataAnnotations; namespace Advisment.Models { public class Course { [Key] public int CourseId { get; set; } public string CourseName { get; set; } public int MajorId { get; set; } public ICollection &lt;Student&gt; Students { get; set; }//Store student objects public Major Major { get; set; } } } </code></pre> <p>From my understanding the ICollection(s) is used to reference the classes, but I'm not sure if I'm using it correctly.</p>
[ { "answer_id": 74666171, "author": "Fitri Halim", "author_id": 13218799, "author_profile": "https://Stackoverflow.com/users/13218799", "pm_score": 1, "selected": false, "text": "public class Enrollment\n{\n public int CourseId { get; set; }\n public int StudentId { get; set; }\n public Student Student { get; set; }\n public Course { get; set; }\n public char Grade {get; set; }\n}\n public class Student\n{\n public int Id { get; set; }\n public string Name { get; set; }\n\n public int MajorId { get; set; }\n\n public int AdvisorId { get; set; }\n\n public ICollection <Enrollment> Enrollments { get; set; }//Reference the Enrollment class\n\n public Advisor Advisor { get; set; }\n\n public Major Major { get; set; }\n \n}\n Course public class Course\n{\n [Key]\n public int CourseId { get; set; }\n public string CourseName { get; set; }\n\n public int MajorId { get; set; }\n \n public ICollection <Enrollment> Enrollments{ get; set; }//Store student objects\n\n public Major Major { get; set; }\n}\n modelBuilder.Entity<Enrollment>()\n .HasKey(c => new { c.CourseId, c.StudentId});\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Student)\n .WithMany(s => s.Enrollments)\n .HasForeignKey(h => h.StudentId)\n .IsRequired();\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Course)\n .WithMany(j => j.Courses)\n .HasForeignKey(h => h.CourseId)\n .IsRequired();\n\n context.Students.Include(s => s.Enrollments).ThenInclude(e => e.Course).ToList();\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19462819/" ]
74,659,050
<p>I thought * should be escaped in bash when it is to be used in a meaning other than the universal character, for example I am trying to use * to multiply two numbers. But when I am trying to use * with an escape character I am getting an error.</p> <pre><code>echo &quot;scale=2; 10 \* 3&quot; | bc EOF encountered in a comment. (standard_in) 1: syntax error </code></pre> <p>but when I am not using the escape character it works.</p> <pre><code>echo &quot;scale=2; 10 * 3&quot; | bc 30 </code></pre> <p>why is this? Can someone explain?</p>
[ { "answer_id": 74666171, "author": "Fitri Halim", "author_id": 13218799, "author_profile": "https://Stackoverflow.com/users/13218799", "pm_score": 1, "selected": false, "text": "public class Enrollment\n{\n public int CourseId { get; set; }\n public int StudentId { get; set; }\n public Student Student { get; set; }\n public Course { get; set; }\n public char Grade {get; set; }\n}\n public class Student\n{\n public int Id { get; set; }\n public string Name { get; set; }\n\n public int MajorId { get; set; }\n\n public int AdvisorId { get; set; }\n\n public ICollection <Enrollment> Enrollments { get; set; }//Reference the Enrollment class\n\n public Advisor Advisor { get; set; }\n\n public Major Major { get; set; }\n \n}\n Course public class Course\n{\n [Key]\n public int CourseId { get; set; }\n public string CourseName { get; set; }\n\n public int MajorId { get; set; }\n \n public ICollection <Enrollment> Enrollments{ get; set; }//Store student objects\n\n public Major Major { get; set; }\n}\n modelBuilder.Entity<Enrollment>()\n .HasKey(c => new { c.CourseId, c.StudentId});\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Student)\n .WithMany(s => s.Enrollments)\n .HasForeignKey(h => h.StudentId)\n .IsRequired();\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Course)\n .WithMany(j => j.Courses)\n .HasForeignKey(h => h.CourseId)\n .IsRequired();\n\n context.Students.Include(s => s.Enrollments).ThenInclude(e => e.Course).ToList();\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10164891/" ]
74,659,075
<p>I have created a project in ASP.NET Core and wanted the language to be detected based on the url: https://localhost:7090/en</p> <p>If controllers and actions are used in the url, everything works as planned. However, when the registration or login page is called, it does not work (default asp.net identity registration page).</p> <p>Works: https://localhost:7090/en/Home/Index</p> <p>Does not work: https://localhost:7090/en/Identity/Account/Register</p> <p>In the startup, I configured the following for MVC routing:</p> <pre><code>builder.Services .AddLocalization() .AddMvc(options =&gt; options.EnableEndpointRouting = false); builder.Services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt; { var supportedCultures = CultureHelper.GetSupportedCultures(); options.DefaultRequestCulture = new RequestCulturne(&quot;en&quot;); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; var provider = new RouteDataRequestCultureProvider { RouteDataStringKey = &quot;culture&quot;, UIRouteDataStringKey = &quot;culture&quot;, Options = options }; options.RequestCultureProviders = new[] { provider }; }); builder.Services.Configure&lt;RouteOptions&gt;(options =&gt; { options.ConstraintMap.Add(&quot;culture&quot;, typeof(LanguageRouteConstraint)); }); var options = app.Services.GetService&lt;IOptions&lt;RequestLocalizationOptions&gt;&gt;(); app.UseRequestLocalization(options.Value); app.UseMvc(routes =&gt; { app.MapRazorPages(); routes.MapRoute( name: &quot;LocalizedDefault&quot;, template: &quot;{culture:culture}/{controller=Home}/{action=Index}/{id?}&quot; ); }); </code></pre> <p>The language constraint is then used to set the CurrentCulture and CurrentUICulture.</p> <p>Here is a code snippet for calling the login/register pages:</p> <pre><code>&lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Register&quot;&gt; @Language.register &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Login&quot;&gt; @Language.login &lt;/a&gt; &lt;/li&gt; </code></pre> <p>I've tried pretty much everything I've found on Google, but nothing seems to work....</p> <p>I just think knowing that it does not work because of the pages</p> <p><strong>[UPDATE]</strong> I was able to get the url to be valid with the following code:</p> <pre><code>builder.Services .AddLocalization(options =&gt; options.ResourcesPath = &quot;Resources&quot;) .AddMvc(options =&gt; options.EnableEndpointRouting = false) .AddRazorPagesOptions(options =&gt; { options.Conventions.Add(new LanguageRouteModelConversion()); }); </code></pre> <hr /> <pre><code>public class LanguageRouteModelConversion : IPageRouteModelConvention { public void Apply(PageRouteModel pageRouteModel) { var selectorModels = new List&lt;SelectorModel&gt;(); foreach (var selector in pageRouteModel.Selectors.ToList()) { var template = selector.AttributeRouteModel?.Template; selectorModels.Add(new SelectorModel() { AttributeRouteModel = new AttributeRouteModel { Template = &quot;/{culture}/&quot; + template } }); } foreach (var model in selectorModels) pageRouteModel.Selectors.Add(model); } } </code></pre> <p>But i still don't know how to call the page properly</p>
[ { "answer_id": 74666171, "author": "Fitri Halim", "author_id": 13218799, "author_profile": "https://Stackoverflow.com/users/13218799", "pm_score": 1, "selected": false, "text": "public class Enrollment\n{\n public int CourseId { get; set; }\n public int StudentId { get; set; }\n public Student Student { get; set; }\n public Course { get; set; }\n public char Grade {get; set; }\n}\n public class Student\n{\n public int Id { get; set; }\n public string Name { get; set; }\n\n public int MajorId { get; set; }\n\n public int AdvisorId { get; set; }\n\n public ICollection <Enrollment> Enrollments { get; set; }//Reference the Enrollment class\n\n public Advisor Advisor { get; set; }\n\n public Major Major { get; set; }\n \n}\n Course public class Course\n{\n [Key]\n public int CourseId { get; set; }\n public string CourseName { get; set; }\n\n public int MajorId { get; set; }\n \n public ICollection <Enrollment> Enrollments{ get; set; }//Store student objects\n\n public Major Major { get; set; }\n}\n modelBuilder.Entity<Enrollment>()\n .HasKey(c => new { c.CourseId, c.StudentId});\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Student)\n .WithMany(s => s.Enrollments)\n .HasForeignKey(h => h.StudentId)\n .IsRequired();\n\n modelBuilder.Entity<Enrollment>()\n .HasOne(c => c.Course)\n .WithMany(j => j.Courses)\n .HasForeignKey(h => h.CourseId)\n .IsRequired();\n\n context.Students.Include(s => s.Enrollments).ThenInclude(e => e.Course).ToList();\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11919058/" ]
74,659,078
<p>How can I use the <code>style</code> input of <code>p-checkbox</code> to change the border and background color of a checkbox? I already tried <code>[style]=&quot;{'background': '#ff0000'}&quot;</code>. But this only applies the style to the div which holds the actual checkbox. So its useless. Instead I need to change the <code>border-color</code> and <code>background</code> of the div which has the classes <code>p-checkbox-box</code> and <code>p-highlight</code>. Note: I cant use CSS here because the colors are dynamic and dependant on the content.</p>
[ { "answer_id": 74674802, "author": "Mouayad_Al", "author_id": 19101349, "author_profile": "https://Stackoverflow.com/users/19101349", "pm_score": 1, "selected": false, "text": "document.getElementsByClassName('p-checkbox-box') renderer2.setStyle() ngAfterViewInit() let chkboxes = document.getElementsByClassName('p-checkbox-box')\n for (let index = 0; index < chkboxes.length; index++) {\n const element = chkboxes[index];\n this._renderer2.setStyle(element,'background-color','#bf2222');\n this._renderer2.setStyle(element,'border-color','#bf2222');\n }\n" }, { "answer_id": 74674925, "author": "odnualam", "author_id": 10875688, "author_profile": "https://Stackoverflow.com/users/10875688", "pm_score": 0, "selected": false, "text": "<p-checkbox [ngStyle]=\"{'border-color': '#ff0000', 'background-color': '#ff0000'}\"></p-checkbox>\n <p-checkbox [ngStyle]=\"{'border-color': myBorderColor, 'background-color': myBackgroundColor}\"></p-checkbox>\n <p-checkbox [ngStyle]=\"{'.p-checkbox-box': {'border-color': '#ff0000'}, '.p-highlight': {'background-color': '#ff0000'}}\"></p-checkbox>\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74659078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9570195/" ]