qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,324,600
<pre><code>import datetime from datetime import date today = date.today() user_name = input('What is your name? ') user_age = int(input('How old are you? ')) print('Hello ' + user_name + '! You were born in', today.year - user_age, '.') </code></pre> <p>What is your name? Tyler How old are you? 31 Hello Tyler! You were born in 1991 .</p> <p>Process finished with exit code 0</p> <p>how do i get rid of the space between the period at the end?</p> <p>I tried using + but it wont work because its an integer</p>
[ { "answer_id": 74324622, "author": "Phillips Olagunju", "author_id": 19143237, "author_profile": "https://Stackoverflow.com/users/19143237", "pm_score": 0, "selected": false, "text": "str()" }, { "answer_id": 74324635, "author": "Virt", "author_id": 20408215, "author_profile": "https://Stackoverflow.com/users/20408215", "pm_score": 0, "selected": false, "text": "print()" }, { "answer_id": 74324639, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "print(f\"Hello {user_name}! You were born in {today.year - user_age}.\")\n" }, { "answer_id": 74324655, "author": "iiSpidey", "author_id": 20420076, "author_profile": "https://Stackoverflow.com/users/20420076", "pm_score": 2, "selected": false, "text": "import datetime\nfrom datetime import date\ntoday = date.today()\nuser_name = input('What is your name? ')\nuser_age = int(input('How old are you? '))\nprint(f\"Hello {user_name}! You were born in {today.year - user_age}.\")\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335099/" ]
74,324,626
<p>I have this error, and I don't know what to do</p> <p>This is my code</p> <p>js:</p> <pre><code>var uploadField = document.getElementById(&quot;file&quot;); console.log(uploadField); uploadField.onchange = function() { console.log(&quot;new&quot;) if(this.files[0].size &gt; 2200000){ alert(&quot;File is too big!&quot;); this.value = &quot;&quot;; }; }; </code></pre> <p>html:</p> <pre><code>&lt;input id =&quot;post-input&quot; id type=&quot;file&quot; placeholder=&quot;Foto do Cartaz&quot; name=&quot;image&quot; accept=&quot;.png,.jpeg,.jpg,.gif&quot; class=&quot;file-input&quot; style=&quot;color: black;&quot;/&gt; </code></pre> <p>What's the best solution, I've searched and none of the solutions that help everybody, helped me.</p>
[ { "answer_id": 74324622, "author": "Phillips Olagunju", "author_id": 19143237, "author_profile": "https://Stackoverflow.com/users/19143237", "pm_score": 0, "selected": false, "text": "str()" }, { "answer_id": 74324635, "author": "Virt", "author_id": 20408215, "author_profile": "https://Stackoverflow.com/users/20408215", "pm_score": 0, "selected": false, "text": "print()" }, { "answer_id": 74324639, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 0, "selected": false, "text": "print(f\"Hello {user_name}! You were born in {today.year - user_age}.\")\n" }, { "answer_id": 74324655, "author": "iiSpidey", "author_id": 20420076, "author_profile": "https://Stackoverflow.com/users/20420076", "pm_score": 2, "selected": false, "text": "import datetime\nfrom datetime import date\ntoday = date.today()\nuser_name = input('What is your name? ')\nuser_age = int(input('How old are you? '))\nprint(f\"Hello {user_name}! You were born in {today.year - user_age}.\")\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16827183/" ]
74,324,633
<p><strong>TL;DR: I try to generate large amounts of random numbers from a set of <code>[-1, 1]</code> I found out that <code>np.random.Generator.choice</code> is the worst method while the best one is to use <code>np.random.Generator.random</code> and move from boolean and to integer. Is there a better way to generate such random numbers in large amounts?</strong></p> <p>I want to simulate the motion of <code>m</code> particles in a closed container with reflective surfaces in d-D in a mesh for <code>n</code> iterations. There is also a hitting condition that I check after every iteration. Without loss of generality, let's assume <code>d=2</code>.</p> <p>Since I use a mesh, the movement part boils down to generating -1s and +1s. At this point, I treat each particle individually in a loop so after generating these -1s and +1s, I access them in a loop and as the number of particles still in the system decreases, I generate less numbers. This part can be improved and I am open to comments but it is not what I am asking.</p> <p>My question is <strong>what the fastest way is to generate many random numbers from the set <code>[-1,1]</code>.</strong> I thought of five approaches, four with np and with random.</p> <p>I firstly thought that the obvious choice was <code>np.random.Generator.choice([-1,1],size=(m,2))</code>. It took 595.6 seconds.</p> <pre class="lang-py prettyprint-override"><code>n=int(5e6) m=1000 rng=np.random.default_rng() tic=time.time() for i in range(n): a=rng.choice([-1,1], size=(m,2)) for j in range(m): #This useless loop is here to demonstrate that I am accessing each line one by one b=a[j] print(&quot;choice&quot;,time.time()-tic) </code></pre> <p>I tried to move from uniform~[0,1) to integers -1 and +1 with code below, which took 527.6 s. Note that the +0 part converts <code>True</code> to <code>1</code> and <code>False</code> to <code>0</code>.</p> <pre class="lang-py prettyprint-override"><code>n=int(5e6) m=1000 rng=np.random.default_rng() tic=time.time() for i in range(n): a=(rng.random(size=(m,2))&gt;0.5+0)*2-1 for j in range(m): b=a[j] print(&quot;operate&quot;,time.time()-tic) </code></pre> <p>I tried something very similar with <code>np.sign</code>, which took 543.5 s.</p> <pre class="lang-py prettyprint-override"><code>n=int(5e6) m=1000 rng=np.random.default_rng() tic=time.time() for i in range(n): a=np.sign(rng.random(size=(m,2))-0.5) for j in range(m): b=a[j] print(&quot;sign&quot;,time.time()-tic) </code></pre> <p>Finally, I tried <code>np.random.Generator.integers</code> with a few extra manipulations. It took 553.8 s.</p> <pre class="lang-py prettyprint-override"><code>n=int(5e6) m=1000 rng=np.random.default_rng() tic=time.time() for i in range(n): a=(rng.integers(2,size=(m,2))*2)-1 for j in range(m): b=a[j] print(&quot;integer&quot;,time.time()-tic </code></pre> <p>Since I access them one by one, I could also use the <code>random.random()</code> on the spot. It takes far too long (~750 s).</p> <p>What baffles me most is that <code>rng.choice()</code> is by far the worst choice. I knew that it didn't work well for small set size, but since <code>m</code> is large, I thought it can redeem itself. I am also surprised that boolean to integer transition offers the fastest solution.</p> <p>So, my question is, what is the fastest way to generate <code>m*d</code> random integers belonging to the set <code>[-1,1]</code>? Is it one of those that I tried or am I missing something? Or am I not even on the right track?</p>
[ { "answer_id": 74325773, "author": "craigb", "author_id": 20236884, "author_profile": "https://Stackoverflow.com/users/20236884", "pm_score": 3, "selected": true, "text": "rng" }, { "answer_id": 74326305, "author": "Suthiro", "author_id": 12497820, "author_profile": "https://Stackoverflow.com/users/12497820", "pm_score": 1, "selected": false, "text": "import numpy as np\nimport time\nfrom numba import njit, prange\n\nn=int(5e6)\nm=1000\nrng=np.random.default_rng()\ntic=time.time()\nfor i in range(n):\n a=(rng.random(size=(m,2))>0.5+0)*2-1\nprint(\"operate\",time.time()-tic)\n\n@njit(parallel=True)\ndef getRandomNumbers(n):\n a = np.zeros(n)\n for i in prange(n):\n a[i] = (np.random.rand()>0.5+0)*2-1\n return a\n\ntic=time.time()\nfor i in range(n):\n a = getRandomNumbers(2*m).reshape((m,2))\nprint(\"numba\",time.time()-tic)\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6361763/" ]
74,324,645
<p>I have a dataset where I will be using the FILTER formula to extract specific values relative to an individual. For each individual, I only want to be extracting the last 2 scores. The data is in descending chronological order so effectively I just need the first 2 entries that exist.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Year</th> <th>Name</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>2022</td> <td>A</td> <td>50</td> </tr> <tr> <td>2022</td> <td>B</td> <td>40</td> </tr> <tr> <td>2022</td> <td>C</td> <td>60</td> </tr> <tr> <td>2021</td> <td>A</td> <td>10</td> </tr> <tr> <td>2021</td> <td>B</td> <td>5</td> </tr> <tr> <td>2020</td> <td>A</td> <td>90</td> </tr> <tr> <td>2020</td> <td>B</td> <td>76</td> </tr> <tr> <td>2019</td> <td>A</td> <td>45</td> </tr> <tr> <td>2019</td> <td>C</td> <td>12</td> </tr> <tr> <td>2018</td> <td>A</td> <td>14</td> </tr> <tr> <td>2017</td> <td>A</td> <td>13</td> </tr> </tbody> </table> </div> <p>Using a dataset similar to the one attached, if I wasn't interested in only the last 2 scores, I would use something like</p> <p><code>=FILTER(A:C,B:B=B1)</code> <code>B1</code> for <code>A</code>, <code>B2</code> for <code>B</code> etc.</p> <p>But doing that would give me <code>6</code> rows for <code>A</code>, <code>3</code> for <code>B</code> and <code>2</code> for <code>C</code>. To standardize this, I only want to consider, at max, <code>2</code> results per individual. How do I change the FILTER formula to achieve this?</p>
[ { "answer_id": 74325636, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "FILTER" }, { "answer_id": 74326770, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 2, "selected": false, "text": "=LET(data,A2:C12,\n names,INDEX(data,,2),\nDROP( \n REDUCE(0,UNIQUE(names),LAMBDA(a,b, \n VSTACK(a,TAKE(FILTER(data,names=b),2)))),\n 1))\n" }, { "answer_id": 74327759, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "FILTER" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278392/" ]
74,324,646
<p>I am trying to make my <code>&lt;li&gt;</code> inside of the <code>&lt;nav&gt;</code> to be positioned at the right side.</p> <p>I am using <code>display:inline-block;</code> property and I have tried to position elements to the right by using following property: <code>text-align:right;</code>.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;./style.css&quot;&gt; &lt;title&gt; Practice &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;header class=&quot;main&quot;&gt; &lt;div&gt; Gokul &lt;/div&gt; &lt;nav class=&quot;main-nav&quot; &gt; &lt;ul class=&quot;item&quot;&gt; &lt;li class=&quot;items&quot;&gt; &lt;a href=&quot;/&quot; class=&quot;brand&quot;&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;items&quot;&gt; &lt;a href=&quot;/&quot; class=&quot;brand&quot;&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the full code on CodePen: <a href="https://codepen.io/gauntletww/pen/VwdjNBz" rel="nofollow noreferrer">CodePen Link</a></p> <p>I want to align the <code>home</code> and <code>contact</code>.</p> <p>I would be glad if someone could address what the problem and give a short answer for solving it.</p>
[ { "answer_id": 74325636, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 3, "selected": true, "text": "FILTER" }, { "answer_id": 74326770, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 2, "selected": false, "text": "=LET(data,A2:C12,\n names,INDEX(data,,2),\nDROP( \n REDUCE(0,UNIQUE(names),LAMBDA(a,b, \n VSTACK(a,TAKE(FILTER(data,names=b),2)))),\n 1))\n" }, { "answer_id": 74327759, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "FILTER" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18805171/" ]
74,324,660
<p>I thought I understood this, but clearly I don't.</p> <p>I have a context manager that wraps suites of code inside some metadata handling. The details of that don't matter, suffice to say the code needs to be between a push_job() and pop_job(). That all works, so I can say:</p> <pre><code>with JobManager(*config) as job: &lt;Processing Goes Here&gt; &lt;Follow up processing, not connected to the job&gt; </code></pre> <p>I thought it would be neat if, instead of inserting the <code>with</code> statement when an entire function needed to be in its own job context, I could just use the same class as a decorator, and say:</p> <pre><code>@JobManager def process_job(job, *other_args, *other_kwargs): </code></pre> <p>But it's not working as a decorator, and I can't see why. I get confusion of arguments between the decorator and the wrapped function.</p> <p>Here's the code:</p> <pre><code>class JobManager(ContextDecorator, AbstractContextManager): &quot;&quot;&quot;Convenience class that provides both a context manager to surround code suites needing a new job frame (using push_job()/pop_job()), and a decorator to wrap functions in the current frame automagically &quot;&quot;&quot; def __init__(self, *args, **kwargs): self._func, self._args = ( (args[0], args[1:] if len(args) &gt; 1 else []) if args and callable(args[0]) else (None, args) ) self._kwargs = kwargs def __call__(self, func): &quot;&quot;&quot;Called when using JobManager as a decorator. Returns a new frame.&quot;&quot;&quot; @wraps(func) def inner(*args, **kwargs): with self._recreate_cm() as job_: return func(job_, *args, **kwargs) return inner def __enter__(self): &quot;&quot;&quot;Called when using JobManager as a context manager. Pushes a new frame or creates the initial frame from the arguments. &quot;&quot;&quot; return ( push_job(*(self._args), **(self._kwargs)) if not _jobs else push_job() ) def __exit__(self, exc_type, exc_value, traceback): &quot;&quot;&quot;Called when using JobManager as a context manager.&quot;&quot;&quot; pop_job() return super().__exit__(exc_type, exc_value, traceback) </code></pre>
[ { "answer_id": 74324732, "author": "Marco Bonelli", "author_id": 3889449, "author_profile": "https://Stackoverflow.com/users/3889449", "pm_score": 2, "selected": false, "text": "@some_decorator\ndef func(...):\n ...\n" }, { "answer_id": 74324859, "author": "Mandera", "author_id": 3936044, "author_profile": "https://Stackoverflow.com/users/3936044", "pm_score": 0, "selected": false, "text": "pip install generallibrary" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2438389/" ]
74,324,665
<p>I have a program to update vehicle inventory. I call the updateVehicle()...it should loop through the arrayList of vehicles to look for a match based on what the user input. In the if statement, if a match is found, update the vehicle in the arrayList with what the user input, display the updated details, display a successfully updated message. If a match was not found, just display not found message. The code works and will update the vehicle with the correct message if there is only one vehicle in the arrayList. However, if there is more than one vehicle in the arrayList, it will update it, but still prints both messages.</p> <pre><code>public void updateVehicle(String makeCurrent, String modelCurrent, String colorCurrent, int yearCurrent, int mileageCurrent, String makeUpdated, String modelUpdated, String colorUpdated, int yearUpdated, int mileageUpdated) { for (int i = 0; i &lt; listOfVehicles.size(); i++) { AutoInv vehicle = listOfVehicles.get(i); if (vehicle.getMake().equalsIgnoreCase(makeCurrent) &amp;&amp; vehicle.getModel().equalsIgnoreCase(modelCurrent) &amp;&amp; vehicle.getColor().equalsIgnoreCase(colorCurrent) &amp;&amp; vehicle.getYear() == yearCurrent &amp;&amp; vehicle.getMileage() == mileageCurrent) { vehicle.setMake(makeUpdated); vehicle.setModel(modelUpdated); vehicle.setColor(colorUpdated); vehicle.setYear(yearUpdated); vehicle.setMileage(mileageUpdated); System.out.println(&quot;\nVehicle updated successfully!\n&quot;); displayCurrentVehicleEntry(); // break; } else { System.out.println(&quot;\nVehicle not found in inventory!&quot;); } } } </code></pre>
[ { "answer_id": 74324725, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 3, "selected": true, "text": "boolean" }, { "answer_id": 74325269, "author": "Karl", "author_id": 10687061, "author_profile": "https://Stackoverflow.com/users/10687061", "pm_score": 0, "selected": false, "text": "updateVehicle" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422475/" ]
74,324,690
<p>Animated background not working. I have sat here for weeks trying to make this code work and it just wont. Open up the link and u realise there are alot of problems but what i just want rn is that the div containing the arabic cat extends all the way down. (use inspect since this website is blocking me from posting code)</p> <p>link: delightful-cuchufli-33d7e2.netlify.app</p> <p>I want the background to extend all the way down to the bottom of the page. As i said before there are alot of other issues but it just wont. Do remember that this is the only issue i want fixed.</p>
[ { "answer_id": 74324725, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 3, "selected": true, "text": "boolean" }, { "answer_id": 74325269, "author": "Karl", "author_id": 10687061, "author_profile": "https://Stackoverflow.com/users/10687061", "pm_score": 0, "selected": false, "text": "updateVehicle" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422404/" ]
74,324,724
<p>I have a table <code>Cards(card_id,status,cid)</code></p> <p>With the columns:</p> <ul> <li><code>cid</code> - customer id</li> <li><code>status</code> - <code>exp</code>/<code>vld</code></li> <li><code>card_id</code> - card id's</li> </ul> <p>How to find the <code>cid</code> with the most expired cards?</p>
[ { "answer_id": 74325169, "author": "sankar", "author_id": 4017098, "author_profile": "https://Stackoverflow.com/users/4017098", "pm_score": 0, "selected": false, "text": "WITH t AS(\nSELECT cid, count(1) customer_exp_cards_count\nFROM Cards where status = 'exp'\ngroup by cid)\nSELECT cid FROM t t1 \nWHERE t1.customer_exp_cards_count IN (SELECT MAX(t2.customer_exp_cards_count) \n FROM t t2)\n" }, { "answer_id": 74325982, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "Select CUST_ID, EXPIRED_CARDS\nFrom (Select CUST_ID, Count(CARD_ID) \"EXPIRED_CARDS\" From cards Where CARD_STATUS = 'EXPIRED' Group By CUST_ID)\nWhere EXPIRED_CARDS = (Select Max(EXPIRED_CARDS) From (Select Count(CARD_ID) \"EXPIRED_CARDS\" From cards Where CARD_STATUS = 'EXPIRED' Group By CUST_ID) )\n-- \n-- R e s u l t\n-- CUST_ID EXPIRED_CARDS\n-- ---------- -------------\n-- 102 3\n" }, { "answer_id": 74326131, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "SELECT cid,\n COUNT(*) AS num_exp\nFROM cards\nWHERE status = 'exp'\nGROUP BY cid\nORDER BY num_exp DESC\nFETCH FIRST ROW WITH TIES;\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17495827/" ]
74,324,731
<p>I've got a table containing results of chess matches:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>player_white</th> <th>player_black</th> <th>result</th> <th>session_start</th> <th>session_end</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Jonathan1</td> <td>TrentX</td> <td>0</td> <td>2020-01-01 13:10:10</td> <td>2020-01-01 13:15:23</td> </tr> <tr> <td>2</td> <td>TrentX</td> <td>Jonathan1</td> <td>1</td> <td>2020-01-01 13:18:32</td> <td>2020-01-01 13:23:13</td> </tr> <tr> <td>3</td> <td>Ezekiel2001</td> <td>Jonathan1</td> <td>1</td> <td>2020-01-01 13:30:12</td> <td>2020-01-01 13:37:01</td> </tr> <tr> <td>4</td> <td>Ezekiel2001</td> <td>TrentX</td> <td>3</td> <td>2020-01-01 13:40:08</td> <td>2020-01-01 13:44:02</td> </tr> <tr> <td>5</td> <td>Jonathan1</td> <td>Ezekiel2001</td> <td>4</td> <td>2020-01-01 13:48:32</td> <td>2020-01-01 13:53:56</td> </tr> <tr> <td>6</td> <td>TrentX</td> <td>Ezekiel2001</td> <td>1</td> <td>2020-01-01 13:56:30</td> <td>2020-01-01 13:59:02</td> </tr> </tbody> </table> </div> <p><code>result</code> is an enum where:</p> <ul> <li>0 = white victory</li> <li>1 = black victory</li> <li>2 = draw by agreement</li> <li>3 = draw by stalemate</li> <li>4 = draw by repetition</li> <li>5 = draw by fifty move rule</li> <li>6 = aborted</li> </ul> <p>I would like to sort players by maximum number of victories and draws to display a leader board. Is there any straightforward way to get this leader board view or are any changes required in the way the data is organized?</p>
[ { "answer_id": 74324988, "author": "sankar", "author_id": 4017098, "author_profile": "https://Stackoverflow.com/users/4017098", "pm_score": 3, "selected": true, "text": "SELECT player, count(1) number_of_victories_and_draws\nFROM(\nSELECT player_white player, result from plays pw_victory_draw_table where result IN( 0, 2, 3, 4, 5)\nUNION ALL\nSELECT player_black player, result from plays pb_victory_draw_table where result IN (1, 2, 3, 4, 5)\n) playes_union_table\nGROUP BY player\nORDER BY 1;\n" }, { "answer_id": 74325162, "author": "user4157124", "author_id": 4157124, "author_profile": "https://Stackoverflow.com/users/4157124", "pm_score": 1, "selected": false, "text": "SELECT\n player_name,\n sum(player_wins) AS player_wins,\n sum(player_loss) AS player_loss,\n sum(player_draw) AS player_draw\nFROM (\n\n SELECT\n player_white AS player_name,\n count(*) AS player_wins,\n 0 AS player_loss,\n 0 AS player_draw\n FROM\n tablename\n WHERE\n result = 0\n\n UNION ALL\n\n SELECT\n player_black AS player_name,\n count(*) AS player_wins,\n 0 AS player_loss,\n 0 AS player_draw\n FROM\n tablename\n WHERE\n result = 1\n\n UNION ALL\n\n SELECT\n player_white AS player_name,\n 0 AS player_wins,\n count(*) AS player_loss,\n 0 AS player_draw\n FROM\n tablename\n WHERE\n result = 1\n\n UNION ALL\n\n SELECT\n player_black AS player_name,\n 0 AS player_wins,\n count(*) AS player_loss,\n 0 AS player_draw\n FROM\n tablename\n WHERE\n result = 0\n\n UNION ALL\n\n SELECT\n player_white AS player_name,\n 0 AS player_wins,\n 0 AS player_loss,\n count(*) AS player_draw\n FROM\n table_name\n WHERE\n result BETWEEN 2 AND 5\n\n UNION ALL\n\n SELECT\n player_black AS player_name,\n 0 AS player_wins,\n 0 AS player_loss,\n count(*) AS player_draw\n FROM\n table_name\n WHERE\n result BETWEEN 2 AND 5\n\n)\nGROUP BY\n player_name\nORDER BY\n player_wins DESC,\n player_loss ASC,\n player_draw DESC,\n player_name ASC\n;\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335534/" ]
74,324,763
<p>I'm starting to learn how to use git and I'm very doubful with some questions about security.</p> <p>I need to manage my codes (in the same GitHub account) between my personal computer and my computer from work, so I've installed git on both. When I clone my repository (personal or private), make changes to it, and push it back, it accepts the pushing without any verification of who is pushing it.</p> <p>So my question is: How does git know who is pushing to my GitHub repository? If anyone uses &quot;git clone <a href="https://github.com/username/myrepo.git%22" rel="nofollow noreferrer">https://github.com/username/myrepo.git&quot;</a>, will them be able to push to it? How can I avoid that?</p> <p>I read in other posts that is not possible, but I still don't understand in what step git verifies who is pushing.</p>
[ { "answer_id": 74327650, "author": "torek", "author_id": 1256452, "author_profile": "https://Stackoverflow.com/users/1256452", "pm_score": 2, "selected": true, "text": "user.name" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16402932/" ]
74,324,785
<p>I have two datasets, one has old data and one has updated data. I'd like to create a new dataset by updating values based on if the area, date and column values match.</p> <p><strong>Data</strong></p> <p>df1</p> <pre><code>area date aa bb cc japan 10/1/2027 1 0 0 us 1/1/2022 5 5 5 fiji 11/2/2026 1 1 1 </code></pre> <p>df2</p> <pre><code>area date aa bb cc stat japan 10/1/2027 0 5 5 yes fiji 11/2/2026 0 0 10 no </code></pre> <p>I have two datasets. I wish to <strong>replace the values in [aa], [bb], and [cc] columns of df2 with the updated values from df1 if we have the same date and area values</strong>. The aa, bb, and cc column are replaced with the updated values.</p> <p><strong>Desired</strong></p> <pre><code>area date aa bb cc stat japan 10/1/2027 1 0 0 yes fiji 11/2/2026 1 1 1 no </code></pre> <p><strong>Doing</strong></p> <pre><code>df['date'] = df.date.apply(lambda x: np.nan if x == ' ' else x) </code></pre> <p>I am not exactly sure how to set this up, however, I have an idea. Any suggestion is appreciated</p>
[ { "answer_id": 74324856, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df1[\"date\"] = pd.to_datetime(df1[\"date\"])\ndf2[\"date\"] = pd.to_datetime(df2[\"date\"])\n\ndf3 = pd.merge(left=df1, right=df2, on=[\"area\", \"date\"], how=\"right\").filter(regex=r\".*(?<!_y)$\")\ndf3.columns = df3.columns.str.split(\"_\").str[0]\nprint(df3)\n\n area date aa bb cc stat\n0 japan 2027-10-01 1 0 0 yes\n1 fiji 2026-11-02 1 1 1 no\n" }, { "answer_id": 74324894, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "output = df1[df1['area'].isin(df2['area']) & df1['date'].isin(df2['date'])]\n" }, { "answer_id": 74325257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "merge" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
74,324,787
<p>Import.php</p> <pre><code>... return new Statement([ 'account_number' =&gt; $row['accountno'], 'account_name' =&gt; $row['name'], 'reading_date' =&gt; \Carbon\Carbon::createFromFormat('m/d/Y', $row['billdate']), 'due_date' =&gt; \Carbon\Carbon::createFromFormat('m/d/Y', $row['duedate']), ]); ... </code></pre> <p>Error:</p> <pre><code>Illuminate\Database\QueryException PHP 8.1.6 9.37.0 SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '10/18/2022' for column `mubsdb`.`statements`.`due_date` at row 1 INSERT INTO `statements` (`due_date`, `reading_date`) VALUES ( 10 / 18 / 2022, 10 / 03 / 2022), ( 10 / 18 / 2022, 10 / 03 / 2022 ), ( 10 / 18 / 2022, 10 / 03 / 2022), ( 10 / 18 / 2022, 10 / 03 / 2022), (10/18/2022, 10/03/2022), (10/18/2022, 10/03/2022), (10/18/2022, 10/03/2022), </code></pre> <p>DB Structure:</p> <pre><code>Name Type Null Default reading_date date Yes NULL due_date date Yes NULL </code></pre> <p>I'm trying to import and save csv rows to my DB but I get error with dates. I tried <code> \Carbon\Carbon::createFromFormat('m/d/Y', $row['billdate'])</code> and <code>\Carbon\Carbon::parse($row['billdate'])-&gt;format('Y-m-d')</code> but neither seems to work</p>
[ { "answer_id": 74324856, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df1[\"date\"] = pd.to_datetime(df1[\"date\"])\ndf2[\"date\"] = pd.to_datetime(df2[\"date\"])\n\ndf3 = pd.merge(left=df1, right=df2, on=[\"area\", \"date\"], how=\"right\").filter(regex=r\".*(?<!_y)$\")\ndf3.columns = df3.columns.str.split(\"_\").str[0]\nprint(df3)\n\n area date aa bb cc stat\n0 japan 2027-10-01 1 0 0 yes\n1 fiji 2026-11-02 1 1 1 no\n" }, { "answer_id": 74324894, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "output = df1[df1['area'].isin(df2['area']) & df1['date'].isin(df2['date'])]\n" }, { "answer_id": 74325257, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "merge" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9426624/" ]
74,324,790
<p>Our server need to use AWS S3 to store users images, our server is springboot ,we will connect S3 to upload image, sometimes it raise exception :java.net.ConnectException: Connection refused, once the exception was raised, it will alway rasie utils we restart springboot service . It can work fine in some days (1 ~2) and then raise Connection refused</p> <pre><code> String fileExt = fileName.substring(fileName.lastIndexOf(&quot;.&quot;) + 1); String contentType = WUtils.getContentType(fileExt); AwsBasicCredentials awsCreds = AwsBasicCredentials.create( aws_access_key_id, aws_secret_key); Region region = Region.AP_EAST_1; presigner = S3Presigner.builder() .region(region) .credentialsProvider(StaticCredentialsProvider.create(awsCreds)) .build(); PutObjectRequest objectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(bucketFolderName + &quot;/&quot; + fileName) .contentType(contentType) .build(); PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder() .signatureDuration(Duration.ofMinutes(10)) .putObjectRequest(objectRequest) .build(); PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest); // Upload content to the Amazon S3 bucket by using this URL. URL url = presignedRequest.url(); // Create the connection and use it to upload the new object by using the presigned URL. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty(&quot;Content-Type&quot;, contentType); connection.setRequestMethod(&quot;PUT&quot;); connection.getOutputStream().write(pic); int responseCode = connection.getResponseCode(); if (responseCode == 200) { imagePath = url.toString().replace(&quot;?&quot; + url.getQuery(), &quot;&quot;); log.info(&quot;======Upload Image Url:&quot; + imagePath); } else { log.error(&quot;======Upload Image fail, responseCode:&quot; + responseCode); } } catch (Exception e) { log.error(String.format(&quot;Module:%s,Method:%s,Info:%s&quot;, &quot;File Upload&quot;, &quot;generatePresignedUrlUploadImage&quot;, e.getMessage())); } finally { if (presigner != null) { presigner.close(); } return imagePath; } java.net.ConnectException: Connection refused at java.base/sun.nio.ch.Net.connect0(Native Method) at java.base/sun.nio.ch.Net.connect(Net.java:579) at java.base/sun.nio.ch.Net.connect(Net.java:568) at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588) at java.base/java.net.Socket.connect(Socket.java:633) at java.base/java.net.Socket.connect(Socket.java:583) at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:498) at java.base/sun.net.www.http.HttpClient$1.run(HttpClient.java:557) at java.base/sun.net.www.http.HttpClient$1.run(HttpClient.java:555) at java.base/java.security.AccessController.doPrivileged(AccessController.java:569) at java.base/sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:554) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:598) at java.base/sun.net.www.protocol.https.HttpsClient.&lt;init&gt;(HttpsClient.java:266) at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:380) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:198) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1263) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1128) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:175) at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1430) at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1401) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:220) at com.wealth.api.service.AmazonService.generatePresignedUrlUploadImage(AmazonService.java:357) at com.wealth.api.service.AmazonService$$FastClassBySpringCGLIB$$23d39f70.invoke(&lt;generated&gt;) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) at com.wealth.api.service.AmazonService$$EnhancerBySpringCGLIB$$58fed417.generatePresignedUrlUploadImage(&lt;generated&gt;) at com.wealth.api.controller.CommControl.uploadFile(CommControl.java:294) at jdk.internal.reflect.GeneratedMethodAccessor943.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:833) </code></pre> <p>AWS support can not resolve this issue ,it suggests retry... but once the exception was raised, retry will be useless util we restart springboot.</p> <p>=========================================================== AWS support had captured the network packets, no issues were found.</p>
[ { "answer_id": 74514869, "author": "wang michael", "author_id": 7998760, "author_profile": "https://Stackoverflow.com/users/7998760", "pm_score": 0, "selected": false, "text": "String imagePath = \"\";\n S3TransferManager transferManager = null;\n String fileExt = fileName.substring(fileName.lastIndexOf(\".\") + 1);\n String contentType = WUtils.getContentType(fileExt);\n\n AwsBasicCredentials awsCreds = AwsBasicCredentials.create(\n aws_access_key_id_for_upload_image,\n aws_secret_key_for_upload_image);\n Region region = Region.AP_EAST_1;\n transferManager = S3TransferManager.builder()\n .s3ClientConfiguration(cfg ->cfg.region(region) .credentialsProvider(StaticCredentialsProvider.create(awsCreds))\n .targetThroughputInGbps(20.0)\n .minimumPartSizeInBytes(10 * 1024L))\n .build();\n\n File file = new File(fileName);\n FileUtils.copyInputStreamToFile(w_file.getInputStream(), file);\n\n log.info(\"======upload image begin,{}\", fileName);\n FileUpload upload =\n transferManager.uploadFile(u -> u.source(file)\n .putObjectRequest(p -> p.bucket(bucketName).key(bucketFolderName + \"/\" + fileName)));\n \n // upload...\n upload.completionFuture().join();//<---Hold ....\n \n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7998760/" ]
74,324,797
<p>I have several thousand lines of code that all ultimately results in a few strings being printed using <code>print()</code> calls. Is there a way to, at the bottom of my code, export everything that has been printed to a text file?</p>
[ { "answer_id": 74324813, "author": "LEGION GREEN", "author_id": 17495765, "author_profile": "https://Stackoverflow.com/users/17495765", "pm_score": 1, "selected": false, "text": "python main.py > output.txt\n" }, { "answer_id": 74324815, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "sys.stdout" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16507322/" ]
74,324,808
<p>After being helped by other users’ questions uncountable times, I finally have to ask my first question.</p> <p><strong>What I’m trying to do:</strong><br> Running a CodeIgniter project (ver. 4.2.8) on a live server.</p> <p><strong>Problem:</strong><br> The URL routing is not working (400 Bad Request error). It’s a fresh installation, so there are no pages other than the default CodeIgniter homepage (the one that says “Welcome to CodeIgniter”).</p> <p>The welcome page displays correctly when I access it like this:</p> <p><a href="http://www.example.com" rel="nofollow noreferrer">www.example.com</a><br> <a href="http://www.example.com/index.php" rel="nofollow noreferrer">www.example.com/index.php</a></p> <p>I get the Bad Request error when I try:</p> <p><a href="http://www.example.com/home" rel="nofollow noreferrer">www.example.com/home</a></p> <p><strong>Here's what I've done:</strong></p> <p>Folder structure on server:<br></p> <pre><code>root | + | dir public_html | | + | dir www.example.com //web root, this is where I put the files that were in the CI public folder + | dir exampleCI4 //here I put all the other CI files and folders app, vendor, writable... </code></pre> <p>I have adjusted following files:</p> <ul> <li>exampleCI4/app/Config/App.php</li> </ul> <pre><code>public $baseURL = 'http://www.example.com' </code></pre> <ul> <li><a href="http://www.example.com/index.php" rel="nofollow noreferrer">www.example.com/index.php</a></li> </ul> <pre><code>// Load our paths config file // This is the line that might need to be changed, depending on your folder structure. require FCPATH . '../exampleCI4/app/Config/Paths.php'; // ^^^ Change this line if you move your application folder </code></pre> <p>At first I always got a 500 Internal Server error. After hours of searching for solutions I came across this post:</p> <p><a href="https://stackoverflow.com/questions/65849139/codeigniter4-htaccess-file-wont-work-with-options-all-indexes">CodeIgniter4 htaccess won't work with Options All -Indexes</a></p> <p>That indeed did solve the 500 Internal Server error, and the welcome page is displaying. I also confirmed with my hosting provider and it turns out that they don't allow Options All and FollowSymlinks.</p> <p>I'm pretty sure there is something in the htaccess file that needs to be adjusted but I don't know what.</p> <p>Here's the complete htaccess file:</p> <ul> <li>public_html/www.example.com/.htaccess</li> </ul> <pre><code>#Disable directory browsing Options -Indexes # ---------------------------------------------------------------------- # Rewrite engine # ---------------------------------------------------------------------- # Turning on the rewrite engine is necessary for the following rules and features. # FollowSymLinks must be enabled for this to work. &lt;IfModule mod_rewrite.c&gt; # Options +FollowSymlinks Options +SymLinksIfOwnerMatch RewriteEngine On # If you installed CodeIgniter in a subfolder, you will need to # change the following line to match the subfolder you need. # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase # RewriteBase / # Redirect Trailing Slashes... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Rewrite &quot;www.example.com -&gt; example.com&quot; RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] # Checks to see if the user is attempting to access a valid file, # such as an image or css document, if this isn't true it sends the # request to the front controller, index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([\s\S]*)$ ../index.php/$1 [L,NC,QSA] # Ensure Authorization header is passed along RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] &lt;/IfModule&gt; &lt;IfModule !mod_rewrite.c&gt; # If we don't have mod_rewrite installed, all 404's # can be sent to index.php, and everything works as normal. ErrorDocument 404 index.php &lt;/IfModule&gt; # Disable server signature start ServerSignature Off # Disable server signature end </code></pre> <p>If somebody could tell me what needs to be changed in order for it to work, that would be awesome.</p>
[ { "answer_id": 74329866, "author": "Nilesh Karanjkar", "author_id": 13028263, "author_profile": "https://Stackoverflow.com/users/13028263", "pm_score": 0, "selected": false, "text": "$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == \"on\") ? \"https\" : \"http\");\n$base_url .= \"://\". @$_SERVER['HTTP_HOST'];\n$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),\"\",$_SERVER['SCRIPT_NAME']);\n$config['base_url'] = $base_url;\n" }, { "answer_id": 74595761, "author": "Ronin-0822", "author_id": 10639537, "author_profile": "https://Stackoverflow.com/users/10639537", "pm_score": 2, "selected": true, "text": " /*\n *---------------------------------------------------------------\n * BOOTSTRAP THE APPLICATION\n *---------------------------------------------------------------\n * This process sets up the path constants, loads and registers\n * our autoloader, along with Composer's, loads our constants\n * and fires up an environment-specific bootstrapping.\n */\n\n// Load our paths config file\n// This is the line that might need to be changed, depending on your folder structure.\nrequire FCPATH . 'app/Config/Paths.php';\n// ^^^ Change this line if you move your application folder\n\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10639537/" ]
74,324,812
<p>I have an angular application that uses two libraries locally, however, when trying to build everything ending up with an error of modules not found, but I thought it was some problems of undeclared dependencies, or imported, but everything is fine.</p> <p>For better understanding, I have: Two local libraries that are used by a test application, where this application consumes both libs, but in the compilation it presents the error of modules not found:</p> <p>`Error: Module not found: Error: Can't resolve '@ngx-formly/example-kendo' in 'C:\SamuelPierre\Example\Repositório\NgBibliotecas\NgBibliotecas\projects\framework-example\src\app\shared'</p> <p>Error: projects/framework-example/src/app/app.component.ts:1:34 - error TS2307: Cannot find module '@example-library/identity' or its corresponding type declarations.</p> <p>1 import { UserTokenService } from '@example-library/identity'; ~~~~~~~~~~~~~~~~~~~~~~~`</p> <p>This error appears for all dependencies, but my main file has all the necessary imports and declarations.</p> <p>Also, &quot;npm install&quot; to install the libraries doesn't help as they are accessed locally. I've already cleaned the node modules, reinstalled npm, everything is ok, but the problem persists.</p>
[ { "answer_id": 74329866, "author": "Nilesh Karanjkar", "author_id": 13028263, "author_profile": "https://Stackoverflow.com/users/13028263", "pm_score": 0, "selected": false, "text": "$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == \"on\") ? \"https\" : \"http\");\n$base_url .= \"://\". @$_SERVER['HTTP_HOST'];\n$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),\"\",$_SERVER['SCRIPT_NAME']);\n$config['base_url'] = $base_url;\n" }, { "answer_id": 74595761, "author": "Ronin-0822", "author_id": 10639537, "author_profile": "https://Stackoverflow.com/users/10639537", "pm_score": 2, "selected": true, "text": " /*\n *---------------------------------------------------------------\n * BOOTSTRAP THE APPLICATION\n *---------------------------------------------------------------\n * This process sets up the path constants, loads and registers\n * our autoloader, along with Composer's, loads our constants\n * and fires up an environment-specific bootstrapping.\n */\n\n// Load our paths config file\n// This is the line that might need to be changed, depending on your folder structure.\nrequire FCPATH . 'app/Config/Paths.php';\n// ^^^ Change this line if you move your application folder\n\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20124684/" ]
74,324,822
<p>I have a problem with my code. my article and aside boxes are overlapping my footer section, any ideas? I also have a problem with making them the same height.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: 'Times New Roman', Serif; } .header { background-color: lightskyblue; border: 3px solid red; height: 200px; } .main { background-color: lightskyblue; border: 3px solid red; height: 200px; padding: 10px; width: 50%; } .article { background-color: lightskyblue; border: 3px solid red; height: 200px; width: 200px; float: right; margin: 5px; padding: 10px; } .aside { background-color: lightskyblue; border: 3px solid red; height: 200px; width: 200px; float: right; margin: 5px; padding: 10px; } .footer { background-color: lightskyblue; border: 3px solid red; height: 200px; padding: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header"&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="main"&gt; &lt;main&gt; &lt;h1&gt;Main&lt;/h1&gt; &lt;/main&gt; &lt;/div&gt; &lt;div class="article"&gt; &lt;article&gt; &lt;h1&gt;Article&lt;/h1&gt; &lt;/article&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="aside"&gt; &lt;aside&gt; &lt;h1&gt;Aside&lt;/h1&gt; &lt;/aside&gt; &lt;/div&gt; &lt;div class="footer"&gt; &lt;footer&gt; &lt;h1&gt;Footer&lt;/h1&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I have tried to set the position of the two (aside and article) to relative and absolute and fixed but i'm still getting the same problem. None of them have positioned them correctly as they should appear :<a href="https://i.stack.imgur.com/0LEGN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0LEGN.png" alt="overlapping problem" /></a> Thats what im getting.</p>
[ { "answer_id": 74324873, "author": "Damzaky", "author_id": 7552340, "author_profile": "https://Stackoverflow.com/users/7552340", "pm_score": 1, "selected": false, "text": "float" }, { "answer_id": 74324912, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": " html {\n margin: 0px;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n }\n\n .header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n }\n \n .content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n }\n \n .main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n }\n \n .article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n }" }, { "answer_id": 74324929, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "html {\n margin: 0px;\n width: 100vw;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n}\n\n.header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n}\n\n.content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n}\n\n.sub-content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-end;\n width: 50%;\n}\n\n.main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n}\n\n.article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20324241/" ]
74,324,829
<p><a href="https://i.stack.imgur.com/JBscR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBscR.png" alt="enter image description here" /></a> I am having this error, I am having trouble understanding if I am importing correctly my styles as well and using components in the right way, can someone steer me on the right path `</p> <pre><code>Cloning github.com/branexists/nextjs (Branch: main, Commit: 30c148b) Cloning completed: 1.626s Build cache restored Running &quot;vercel build&quot; Vercel CLI 28.4.14 Installing dependencies... up to date in 498ms 80 packages are looking for funding run `npm fund` for details Detected Next.js version: 13.0.2 Detected `package-lock.json` generated by npm 7+... Running &quot;npm run build&quot; &gt; nextjs@0.1.0 build &gt; next build info - Linting and checking validity of types... info - Creating an optimized production build... (node:318) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API (Use `node --trace-deprecation ...` to show where the warning was created) Failed to compile. ./styles/hero.css Global CSS cannot be imported from files other than your Custom &lt;App&gt;. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules). Read more: https://nextjs.org/docs/messages/css-global Location: comps/Hero.js Import trace for requested module: ./styles/hero.css ./comps/Hero.js ./styles/hero.css Module build failed: Error: Final loader (./node_modules/next/dist/build/webpack/loaders/error-loader.js) didn't return a Buffer or String at processResult (/vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:28:395049) at /vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:28:396519 at /vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:283578 at iterateNormalLoaders (/vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:280385) at iterateNormalLoaders (/vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:280470) at /vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:280699 at runSyncOrAsync (/vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:279045) at iterateNormalLoaders (/vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:280602) at /vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:1:280244 at /vercel/path0/node_modules/next/dist/compiled/webpack/bundle5.js:28:395994 Import trace for requested module: ./styles/hero.css ./comps/Hero.js &gt; Build failed because of webpack errors Error: Command &quot;npm run build&quot; exited with 1 </code></pre> <p>`</p> <p>I tried changing syntax on my imports from import styles to just import because in my previous question I was told I cannot have more than one styles import</p>
[ { "answer_id": 74324873, "author": "Damzaky", "author_id": 7552340, "author_profile": "https://Stackoverflow.com/users/7552340", "pm_score": 1, "selected": false, "text": "float" }, { "answer_id": 74324912, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": " html {\n margin: 0px;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n }\n\n .header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n }\n \n .content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n }\n \n .main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n }\n \n .article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n }" }, { "answer_id": 74324929, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "html {\n margin: 0px;\n width: 100vw;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n}\n\n.header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n}\n\n.content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n}\n\n.sub-content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-end;\n width: 50%;\n}\n\n.main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n}\n\n.article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17325416/" ]
74,324,853
<p>This is what I see in an official tool, and I need to calculate the same end value:</p> <p><a href="https://i.stack.imgur.com/MOOF0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MOOF0.png" alt="enter image description here" /></a></p> <p>For clarification:</p> <p>I am given the numbers 95, 3, 5, 19 and 17.15.</p> <p>I am trying to replicate a math formula in VB.NET in order to achieve the same sum as a government financial tool that I must stay conform with.</p> <p>The official tool's result and mine differ by 0.1 €, and I don't see what I need to do to achieve the same result.</p> <p>The official tool states:</p> <pre><code>A product costs 95.00 € net. Somebody buys 3 pieces of it. He gets a discount of 5 % (=4.75 €) 19% VAT is added: 17.15 € The net price is then 90.25 € The price is now 270.75 € The resulting end price is now 322.19 €. </code></pre> <p>The values that I am given are these:</p> <pre><code>net price for 1 piece: 95 € amount: 3 discount per piece: 5% VAT amount: 19% VAT: 17.15 </code></pre> <p>First, I calculate the discount like this:</p> <pre><code>Dim amount As Integer = 3 Dim discount As Double = 5 Dim VAT As Double = 17.15 All result As Decimal Discount = (amount * discount) / 100 = 4.75 Discounted net price per piece = 95 - 4.75 = 90.25 Discounted net price per piece plus vat = 95 + 17.15 = 107.4 Total price result = discounted net price per piece * amount = 107.4 * 3 = 322.2 € </code></pre> <p>Is there anything that I'm doing wrong by choosing a wrong operator?</p> <p>Is it even possible to get the same amount as they do with the information that I am given?</p> <p>Thank you.</p>
[ { "answer_id": 74324873, "author": "Damzaky", "author_id": 7552340, "author_profile": "https://Stackoverflow.com/users/7552340", "pm_score": 1, "selected": false, "text": "float" }, { "answer_id": 74324912, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": " html {\n margin: 0px;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n }\n\n .header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n }\n \n .content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n }\n \n .main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n }\n \n .article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n }" }, { "answer_id": 74324929, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "html {\n margin: 0px;\n width: 100vw;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n}\n\n.header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n}\n\n.content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n}\n\n.sub-content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-end;\n width: 50%;\n}\n\n.main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n}\n\n.article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1390192/" ]
74,324,862
<p>I am pretty new to JS so please go easy on me.</p> <p>Im trying to increment a value in a JSON file in my JS backend application. Whenever I increment the associated value by the key, it creates a new section &quot;undefined&quot;</p> <p>Here is the entire application:</p> <pre><code>const { response } = require(&quot;express&quot;); const express = require(&quot;express&quot;); const fs = require(&quot;fs&quot;).promises; const path = require(&quot;path&quot;); const app = express(); const dataFile = path.join(__dirname, &quot;data.json&quot;); //support POSTing form data wuth url encoded app.use(express.json()); app.get(&quot;/poll&quot;, async (req, res) =&gt;{ //data is now the js object of the Json data json let data = JSON.parse(await fs.readFile(dataFile, &quot;utf-8&quot;)); const totalVotes = Object.values(data).reduce((total, n) =&gt; total +=n, 0); data = Object.entries(data).map(([label, votes]) =&gt; { return{ label, percentage: (((100 * votes) / totalVotes) || 0).toFixed(0) // or with 0 in the even that you divide by zero } }); res.json(data); }); app.use(express.urlencoded({ extended: true})); app.post(&quot;/poll&quot;, async (req, res) =&gt; { const data = JSON.parse(await fs.readFile(dataFile, &quot;utf-8&quot;)); data[req.body.add]++; await fs.writeFile(dataFile, JSON.stringify(data)); res.json(data); }); app.listen(3000, () =&gt; console.log(&quot;Server is running ...&quot;)); </code></pre> <p>Here is my JSON file before I POST</p> <pre><code>{ &quot;JavaScript&quot;:0, &quot;TypScript&quot;:10, &quot;Both&quot;:3} </code></pre> <p>Here is a picture of my POST request in Insomnia: <a href="https://i.stack.imgur.com/LR2rC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LR2rC.png" alt="Insomnia Screenshot" /></a></p> <p>Here is my JSON file after a Post Requests</p> <pre><code>{ &quot;JavaScript&quot;: 0, &quot;TypScript&quot;: 10, &quot;Both&quot;: 3, &quot;undefined&quot;: null } </code></pre> <p>Here is is after a second POST request:</p> <pre><code>{ &quot;JavaScript&quot;: 0, &quot;TypScript&quot;: 10, &quot;Both&quot;: 3, &quot;undefined&quot;: 1 } </code></pre> <p>I know it might be something very simple, but I am very inexperienced so any help would be greatly appreciated!</p> <p>I tried including some additional middleware to enable bodyParsing as I saw in other posts but that did not fix the issue.</p> <p>I also tried</p> <pre><code>console.logging(req.body) </code></pre> <p>,but that only printed &quot;undefined&quot;.</p> <p>EDIT: I found the problem, I wasn't sending the information in Insomnia correctly, I need to click the form type and either format a JSON input or select the &quot;Form URL Encoded&quot;&quot; Option. Otherwise it doesn't recognize the format.</p> <p>Thank you for your help!</p>
[ { "answer_id": 74324873, "author": "Damzaky", "author_id": 7552340, "author_profile": "https://Stackoverflow.com/users/7552340", "pm_score": 1, "selected": false, "text": "float" }, { "answer_id": 74324912, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": " html {\n margin: 0px;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n }\n\n .header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n }\n \n .content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n }\n \n .main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n }\n \n .article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n }" }, { "answer_id": 74324929, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "html {\n margin: 0px;\n width: 100vw;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n}\n\n.header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n}\n\n.content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n}\n\n.sub-content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-end;\n width: 50%;\n}\n\n.main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n}\n\n.article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19057328/" ]
74,324,881
<p>I want to optionally bind a field to specific class for each profile</p> <p>the example code is as follows ...</p> <pre><code>spring: config: activate: on-profile: test1 app: cash: conn: connection-timeout: 1000 response-timeout: 2000 ... --- spring: config: activate: on-profile: test2 </code></pre> <pre class="lang-java prettyprint-override"><code>@Getter @Validated @ConstructorBinding @ConfigurationProperties(value = &quot;app.cash.conn&quot;) @RequiredArgsConstructor public class CashBoxConnectionProperties { @NotNull @Positive private final Integer connectionTimeout; @NotNull @Positive private final Integer responseTimeout; @NotNull @PositiveOrZero private final Integer retryMaxAttempts; @NotNull @Positive private final Integer retryMaxDelay; } </code></pre> <p>When running as <code>test1</code> profile, the application runs normally because the properties value is set, but when running as <code>test2</code> profile, the error 'Binding to target...' occurs because there is no <code>app.cash.conn</code> properties.</p> <p>The <code>CashBoxConnectionProperties</code> is not required in <code>test2</code> profile, so is there any other way than to remove <code>@NotNull</code> annotation?</p>
[ { "answer_id": 74324873, "author": "Damzaky", "author_id": 7552340, "author_profile": "https://Stackoverflow.com/users/7552340", "pm_score": 1, "selected": false, "text": "float" }, { "answer_id": 74324912, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": " html {\n margin: 0px;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n }\n\n .header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n }\n \n .content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n }\n \n .main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n }\n \n .article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n }\n \n .footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n }" }, { "answer_id": 74324929, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": 0, "selected": false, "text": "html {\n margin: 0px;\n width: 100vw;\n}\n\nbody {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: flex-start;\n width: 100%;\n margin: 0px;\n}\n\n.header {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 100%;\n}\n\n.content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n}\n\n.sub-content-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: flex-end;\n width: 50%;\n}\n\n.main {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 50%;\n padding: 10px;\n}\n\n.article {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.aside {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n width: 200px;\n margin: 5px;\n padding: 10px;\n}\n\n.footer {\n background-color: lightskyblue;\n border: 3px solid red;\n height: 200px;\n padding: 10px;\n width: 100%;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12960592/" ]
74,324,899
<p>Here's the setup:</p> <p>We have a classic <a href="https://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">observer pattern</a>. <code>IObserver</code> is an interface with a <code>notify</code> method. <code>RealObserver</code> implements the <code>IObserver</code> interface. <code>Subject</code> is a class with a <code>List&lt;Observer&gt;</code>. When <code>Subject.tick()</code> is called, it loops over its list of observers and calls <code>notify</code> on each one.</p> <p>How should this be shown in a UML sequence diagram?</p> <p>I had something like the following:</p> <p><a href="https://i.stack.imgur.com/FCsZQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCsZQ.jpg" alt="enter image description here" /></a></p> <p>I was told that this was incorrect because I used <code>IObserver</code> as the type (which I incorrectly labelled <code>Observer</code> -- sorry!). I was told I should never use abstract or interface types and instead use concrete classes only.</p> <p>Is that true? If so, how should I have made this diagram? What if there were more than one implementing class of the <code>IObserver</code> interface?</p> <p>Thanks!</p>
[ { "answer_id": 74326988, "author": "Christophe", "author_id": 3723423, "author_profile": "https://Stackoverflow.com/users/3723423", "pm_score": 3, "selected": true, "text": "observer:IObserver" }, { "answer_id": 74331241, "author": "qwerty_so", "author_id": 3379653, "author_profile": "https://Stackoverflow.com/users/3379653", "pm_score": 0, "selected": false, "text": "OccurrenceSpecification" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16042683/" ]
74,324,901
<p>I'm trying to get back to Python but I don't get why the following code doesn't work as intended.</p> <pre><code>class Cat: age = 0 class Dog(Cat): pass Dog.age = 1 Cat.age = 2 print(Dog.age, Cat.age) </code></pre> <p>My output is:</p> <pre><code>1 2 </code></pre> <p>But why doesn't <code>Dog.age</code> equals 2?</p> <p><code>Dog</code> is a subclass of <code>Cat</code> and modifying the class variable of the superclass <code>Cat</code> would normally affect every subclass that inherits the variable as well.</p>
[ { "answer_id": 74324917, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "Dog" }, { "answer_id": 74325020, "author": "Cynthia168", "author_id": 19464984, "author_profile": "https://Stackoverflow.com/users/19464984", "pm_score": 0, "selected": false, "text": "class Cat:\n def __init__(self):\n self.age = 2\n self.sound = \"meow\"\n\n\nclass Dog(Cat):\n def __init__(self):\n super().__init__()\n self.sound = \"bark\"\n\n\ncat = Cat()\ndog = Dog()\n\nprint(f\"The cat's age is {cat.age}, and the dog's age is {dog.age}.\")\nprint(f\"Cats {cat.sound}, and dogs {dog.sound}.\")\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,324,913
<p>i have problem with cant force restart from management console login as admin. can anyone helping with me about this. i got log like this</p> <pre><code>`[2022-10-01 00:45:04,581] INFO - CarbonCoreActivator Starting WSO2 Carbon... [2022-10-01 00:45:04,581] INFO - CarbonCoreActivator Operating System : Linux 4.18.0-305.el8.x86_64, amd64 [2022-10-01 00:45:04,581] INFO - CarbonCoreActivator Java Home : /usr/java/jdk1.8.0_341-amd64/jre [2022-10-01 00:45:04,581] INFO - CarbonCoreActivator Java Version : 1.8.0_341 [2022-10-01 00:45:04,581] INFO - CarbonCoreActivator Java VM : Java HotSpot(TM) 64-Bit Server VM 25.341-b10,Oracle Corporation [2022-10-01 00:45:04,582] INFO - CarbonCoreActivator Carbon Home : /opt/source/wso2_binary/wso2am-4.1.0 [2022-10-01 00:45:04,582] INFO - CarbonCoreActivator Java Temp Dir : /opt/source/wso2_binary/wso2am-4.1.0/tmp [2022-10-01 00:45:04,582] INFO - CarbonCoreActivator User : abhimata, en-US, Asia/Jakarta [2022-10-01 00:45:04,786] INFO - DefaultCryptoProviderComponent 'CryptoService.Secret' property has not been set. 'org.wso2.carbon.crypto.provider.SymmetricKeyInternalCryptoProvider' won't be registered as an internal crypto provider. Please set the secret if the provider needs to be registered. [2022-10-01 00:45:05,125] INFO - KafkaEventAdapterServiceDS Successfully deployed the Kafka output event adaptor service [2022-10-01 00:45:05,279] INFO - TemplateDeployerServiceTrackerDS Successfully deployed the execution manager tracker service [2022-10-01 00:45:06,716] INFO - ServiceComponent Eventing Hub ServiceComponent is activated [2022-10-01 00:45:07,431] WARN - Digester Match [Server/Service/Engine/Host/Valve] failed to set property [maxDays] to [] [2022-10-01 00:45:08,095] ERROR - DefaultRealm nullType class java.lang.reflect.InvocationTargetException org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:404) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:231) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:136) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:276) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.DefaultRealmService.&lt;init&gt;(DefaultRealmService.java:102) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.DefaultRealmService.&lt;init&gt;(DefaultRealmService.java:115) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:72) ~[?:?] at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61) ~[?:?] at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_341] at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.Module.doStart(Module.java:598) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.Module.start(Module.java:462) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345) ~[org.eclipse.osgi_3.14.0.v20190517-1309.jar:?] Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_341] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_341] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_341] at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_341] at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:358) ~[org.wso2.carbon.user.core_4.6.3.jar:?] ... 25 more Caused by: org.wso2.carbon.user.core.UserStoreException: DB error occurred while persisting domain : PRIMARY &amp; tenant id : -1234 at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:931) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.common.AbstractUserStoreManager.persistDomain(AbstractUserStoreManager.java:9083) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.&lt;init&gt;(JDBCUserStoreManager.java:320) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.&lt;init&gt;(JDBCUserStoreManager.java:262) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at org.wso2.carbon.user.core.jdbc.UniqueIDJDBCUserStoreManager.&lt;init&gt;(UniqueIDJDBCUserStoreManager.java:129) ~[org.wso2.carbon.user.core_4.6.3.jar:?] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_341] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_341] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_341] at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_341] at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:358) ~[org.wso2.carbon.user.core_4.6.3.jar:?] ... 25 more </code></pre> <p>i expecting can force restart from management console or can with restart with command line from linux. please help me about this; thanks</p>
[ { "answer_id": 74324917, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "Dog" }, { "answer_id": 74325020, "author": "Cynthia168", "author_id": 19464984, "author_profile": "https://Stackoverflow.com/users/19464984", "pm_score": 0, "selected": false, "text": "class Cat:\n def __init__(self):\n self.age = 2\n self.sound = \"meow\"\n\n\nclass Dog(Cat):\n def __init__(self):\n super().__init__()\n self.sound = \"bark\"\n\n\ncat = Cat()\ndog = Dog()\n\nprint(f\"The cat's age is {cat.age}, and the dog's age is {dog.age}.\")\nprint(f\"Cats {cat.sound}, and dogs {dog.sound}.\")\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211718/" ]
74,324,924
<p>Is there any way in Javascript to instantly access an object value with a specific depth? </p> <p>There is an example:</p> <pre><code>{ &quot;level&quot;: { &quot;value&quot;: &quot;one&quot;, &quot;level&quot;: { &quot;value&quot;: &quot;two&quot;, &quot;level&quot;: { &quot;value&quot;: &quot;three&quot;, &quot;level&quot;: { &quot;value&quot;: &quot;four&quot;, &quot;level&quot;: { &quot;value&quot;: &quot;five&quot; } } } } } } </code></pre> <p>I can do that with recursion. Check the first object value <code>level</code> and if it exists then go to the next and when depth is what I need, I need to stop. And if depth is not reached and the next <code>level</code> value does not exist, then raise some error.</p> <p>Maybe there is some other way and approach to doing that?</p>
[ { "answer_id": 74324987, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "function flatDepth(obj) {\n let res = [];\n while(typeof obj === 'object') {\n res.push(obj.value);\n obj = obj.level;\n }\n return res;\n}\n\nconst obj = {\n \"level\": {\n \"value\": \"one\",\n \"level\": {\n \"value\": \"two\",\n \"level\": {\n \"value\": \"three\",\n \"level\": {\n \"value\": \"four\",\n \"level\": {\n \"value\": \"five\"\n }\n }\n }\n }\n }\n}\nconst flattened = flatDepth(obj);\nconsole.log(flattened);\n\nconsole.log(flattened[3]); // => 3\nconsole.log(flattened[0]); // => undefined\nconsole.log(flattened[5]); // => undefined" }, { "answer_id": 74325258, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const obj = {\n \"level\": {\n \"value\": \"one\",\n \"level\": {\n \"value\": \"two\",\n \"level\": {\n \"value\": \"three\",\n \"level\": {\n \"value\": \"four\",\n \"level\": {\n \"value\": \"five\"\n }\n }\n }\n }\n }\n};\nconst getValueAtLevel = level => {\n let p = obj.level;\n while(level-- > 1) p = p.level;\n return p.value;\n}\nconsole.log(getValueAtLevel(2));" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18840965/" ]
74,324,937
<pre><code>import random from words import words import string def get_valid_word(word): word = random.choice(words) while '-' in word or ' ' in word: word = random.choice(words) return word def hangman(): word = get_valid_word(words) word_letters = set(word) # letters in word alphabet = set(string.ascii_uppercase) used_letters = set() user_input = (&quot;type something: &quot;) print(user_input) </code></pre> <p>I have been following along a YouTube python project, but when I use the import function the code doesn't seem to run. It executes nothing and says its done.</p>
[ { "answer_id": 74324951, "author": "Anurag Dhadse", "author_id": 8277795, "author_profile": "https://Stackoverflow.com/users/8277795", "pm_score": 1, "selected": false, "text": "hangman()" }, { "answer_id": 74325086, "author": "TCK", "author_id": 14525084, "author_profile": "https://Stackoverflow.com/users/14525084", "pm_score": -1, "selected": false, "text": "hangman()\nget_valid_word()\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422778/" ]
74,324,942
<p>I was creating a note taking program, using the user voice command. When the file already exists, I want to show an error. It runs smoothly when the file name is different though. When the file already exists, I have coded to open in the writing mode. It would erase the earlier file, and write new instead of adding in the append mode.</p> <pre class="lang-py prettyprint-override"><code>elif 'note' in query: try: speak(&quot; Okay master. what's the file name&quot;) b= takecommand() f = open(f&quot;{b}.txt&quot;,&quot;w&quot;) speak(&quot;Okay master. tell me what to note down&quot;) a= takecommand() f.write(f&quot;{a}\n&quot;) f.close() except Exception as e: speak(&quot;file name already exist&quot;) </code></pre> <p>Can you help me with troubleshooting the script? Like how could I first make it thrown an error when the filename is same?</p>
[ { "answer_id": 74325045, "author": "TCK", "author_id": 14525084, "author_profile": "https://Stackoverflow.com/users/14525084", "pm_score": 2, "selected": false, "text": "elif 'note' in query:\n try:\n Looper = True # Added a loop so it can repeatedly ask the user until they give a valid answer.\n speak(\" Okay master. what's the file name\") # Put here instead of in the loop so it will repeat once since the else condition already asks for a new file name aswell.\n while Looper == True:\n b = takecommand()\n if os.path.exists(f\"{b}.txt\"):\n f = open(f\"{b}.txt\",\"w\")\n speak(\"Okay master. tell me what to note down\")\n a= takecommand()\n f.write(f\"{a}\\n\")\n Looper = False # So the loop won't repeat again (regardless of the below line).\n f.close()\n else:\n speak(\"That file already exists. Give me a new file name.\")\n except Exception as e:\n speak(\"Hm, an error occured. Try again later.\")\n" }, { "answer_id": 74325046, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "try:\n # ...\n f = open(f\"{b}.txt\",\"x\")\n # ...\nexcept FileExistsError:\n speak(\"file name already exist\")\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8928135/" ]
74,324,961
<p>why is there no error for <code>a = [10,]</code> but error for <code>[10,,]</code> in Python ? <a href="https://i.stack.imgur.com/c6QTz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6QTz.png" alt="enter image description here" /></a><br /> what is interpreter expecting from comma/s in both the cases?</p> <p>I understand it's more of a syntax error but there has to rationale/logical explanation of this.</p>
[ { "answer_id": 74324993, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "lst = [1,2,3,4,]\n" }, { "answer_id": 74325592, "author": "Luicfer Ai", "author_id": 18416403, "author_profile": "https://Stackoverflow.com/users/18416403", "pm_score": 0, "selected": false, "text": "value of any datatype" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5214109/" ]
74,324,976
<p>I am trying to search the object from the ArrayList</p> <p>For example, in the below code the object of Product class is going to stored in the ArrayList. Now, I want to find the Product using its product name (by contain method).</p> <pre><code>import java.util.*; class Product { String name; int price; int id; Product(int i, String name, int price) { this.id=i; this.name = name; this.price = price; } } public class Test{ public static void main(String[] args) { ArrayList&lt;Product&gt; al = new ArrayList&lt;Product&gt;(); al.add(new Product(1, &quot;Samsung&quot;, 10000)); al.add(new Product(2, &quot;Apple&quot;, 20000)); al.add(new Product(3, &quot;Nokia&quot;, 30000)); al.add(new Product(4, &quot;Sony&quot;, 40000)); al.add(new Product(5, &quot;LG&quot;, 50000)); for (Product p : al) { System.out.println(p.id + &quot; &quot; + p.name + &quot; &quot; + p.price); } System.out.println(&quot;Enter the name of the product to search:&quot;); Scanner sc = new Scanner(System.in); String name = sc.nextLine(); if (al.contains(name)) { System.out.println(&quot;Product found&quot;); } else { System.out.println(&quot;Product not found&quot;); } } } </code></pre>
[ { "answer_id": 74324993, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "lst = [1,2,3,4,]\n" }, { "answer_id": 74325592, "author": "Luicfer Ai", "author_id": 18416403, "author_profile": "https://Stackoverflow.com/users/18416403", "pm_score": 0, "selected": false, "text": "value of any datatype" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14161071/" ]
74,324,983
<p>I am using Azure DevOps for some application deployment. I need to have a saved variable build number that would update every time I do a build successfully and send the apk/ipa to the store.</p> <p>Right now, from what I read in the Azure documentation and other post on StackOverflow about this, I setup my scripts this way.</p> <p>This is my pipeline variable <a href="https://i.stack.imgur.com/24Iic.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/24Iic.png" alt="enter image description here" /></a></p> <p>This is my current script <a href="https://i.stack.imgur.com/MEBhL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MEBhL.png" alt="enter image description here" /></a></p> <p>the output is: <a href="https://i.stack.imgur.com/dvRxe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dvRxe.png" alt="enter image description here" /></a></p> <p>So, it seems to update my local variable but not my pipeline variable. I am unsure why since this is the example provided EVERYWHERE.</p> <p>Sources:</p> <ul> <li><a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&amp;tabs=bash" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&amp;tabs=bash</a></li> <li><a href="https://stackoverflow.com/questions/73113958/how-to-increment-and-save-variable-in-azure-devops-pipeline">how to increment and save variable in azure devops pipeline</a></li> </ul> <p>Thank you for the help!</p> <p>Edit 1: Ok, so it seems that there is a variable/function called <code>counter</code>. I haven't figured out how to use it yet, but looking into it.</p> <p>Edit 2: Updated my <code>azure-pipelines.yml</code></p> <pre><code>variables: major: 1 minor: 0 patch: 0 build: $[counter(variables['patch'], 1)] </code></pre> <p>On my pipeline it looks like this <a href="https://i.stack.imgur.com/aMt1J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aMt1J.png" alt="enter image description here" /></a></p> <p>and my fastlane (ruby script ) lane looks like this</p> <pre><code>lane :tf do `echo $major` `echo $minor` `echo $patch` `echo $build` # Nothing `echo $MAJOR` `echo $MINOR` `echo $PATCH` `echo $BUILD` # Nothing `echo $(major)` # fails end </code></pre> <p>those show nothing.</p> <p>This azure DevOps is very depressing. It says here I can do a bash call to this variable. <a href="https://i.stack.imgur.com/bd7vw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bd7vw.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74324993, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "lst = [1,2,3,4,]\n" }, { "answer_id": 74325592, "author": "Luicfer Ai", "author_id": 18416403, "author_profile": "https://Stackoverflow.com/users/18416403", "pm_score": 0, "selected": false, "text": "value of any datatype" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5899647/" ]
74,324,986
<p>I am a total beginner to Python and recently had a question while experimenting with lists. I have a for loop that increases a variable 'x' and generates a random number every time. I want to add this random number to a list, but when I try assigning the index value of the random number to x, I get this error message:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 6, in &lt;module&gt; IndexError: list assignment index out of range </code></pre> <p>Any help would be greatly appreciated!</p> <p>My code:</p> <pre><code>import random as number x = 0 values = [] while x &lt; 9: values[x] = number.randint(1,91) x += 1 print(values) </code></pre>
[ { "answer_id": 74325009, "author": "Seyed Mehrshad Hosseini", "author_id": 11733513, "author_profile": "https://Stackoverflow.com/users/11733513", "pm_score": 3, "selected": true, "text": "import random as number\n\nvalues = [number.randint(1,91) for _ in range(9)]\n" }, { "answer_id": 74325011, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 2, "selected": false, "text": ".append()" }, { "answer_id": 74325200, "author": "botaskay", "author_id": 9954654, "author_profile": "https://Stackoverflow.com/users/9954654", "pm_score": 0, "selected": false, "text": "values = []" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422817/" ]
74,324,995
<p>I have been writing program about dragging turtles to different designated position.</p> <p>However, <code>turtle.ondrag(turtle.goto)</code> nor <code>at[i].ondrag(at[i].goto)</code> does not work.</p> <p>I've been amended with the solution from here <a href="https://stackoverflow.com/questions/19867476">Python turtle.ondrag not working @ Jellominer</a>, but that's seems not working for my case (with multiple turtles). The code snippet at below.</p> <pre><code>import turtle as t def handler(x, y, i): global at curTurtle = at[i] curTurtle.ondrag(None) # disable handler inside handler curTurtle.setheading(curTurtle.towards(x, y)) # turn toward cursor curTurtle.goto(x, y) # move toward cursor print(x, y, i) curTurtle.ondrag(handler) at = [] for i in range(3): at.append(t.Turtle()) # Just to seperated turtles with color at[0].color('grey') at[0].goto(100, 100) at[1].color('blue') at[1].goto(0, 100) at[2].color('green') at[2].goto(100, 0) for i in range(3): at[i].ondrag(lambda x, y: handler(x, y, i)) t.listen() t.mainloop() </code></pre> <p>Only the turtle with the largest index could be dragged, as seen from the <code>print(x, y, i)</code>. It's there anyways to let the drag other turtle move as well?</p>
[ { "answer_id": 74325155, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 1, "selected": true, "text": "import turtle as t\n\nclass T(t.Turtle):\n def dragging(self, x, y):\n self.ondrag(None)\n self.setheading(self.towards(x,y))\n self.goto(x,y)\n self.ondrag(self.dragging)\n\nat = []\nfor i in range(3):\n turtle = T()\n turtle.ondrag(turtle.dragging)\n at.append(turtle)\n\n\n# Just to seperated turtles with color\nat[0].color('grey')\nat[0].goto(100, 100)\nat[1].color('blue')\nat[1].goto(0, 100)\nat[2].color('green')\nat[2].goto(100, 0)\n\n# t.Screen().tracer(3) # uncomment to remove lagging.\nt.listen()\nt.mainloop()\n" }, { "answer_id": 74325573, "author": "cdlane", "author_id": 5771269, "author_profile": "https://Stackoverflow.com/users/5771269", "pm_score": 1, "selected": false, "text": "lambda" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74324995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17260184/" ]
74,325,043
<p>Each 2 div is of different size and they must be the same height.</p> <p>CSS:</p> <pre><code>.bbb { width: 333px; height: 2px; max-height: 2px; background: black; } </code></pre> <p>HTML:</p> <pre><code>&lt;div class=&quot;bbb&quot;&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;bbb&quot;&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;bbb&quot;&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;bbb&quot;&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;bbb&quot;&gt;&lt;/div&gt; </code></pre> <p><a href="https://jsfiddle.net/3dgujw5k/" rel="nofollow noreferrer">JSFiddle</a> and <a href="https://i.stack.imgur.com/QqpYF.png" rel="nofollow noreferrer">IMG</a></p> <p>How to fix it?</p>
[ { "answer_id": 74325192, "author": "Akash ", "author_id": 20271116, "author_profile": "https://Stackoverflow.com/users/20271116", "pm_score": 1, "selected": false, "text": ".bbb {\n width: 333px;\n height: 2px;\n max-height: 2px;\n background: black;\n margin: 2rem;\n}\n\n.bbb:nth-child(1) {\n margin-top: 0rem;\n}\n" }, { "answer_id": 74325365, "author": "Abhilash C S", "author_id": 20423077, "author_profile": "https://Stackoverflow.com/users/20423077", "pm_score": 2, "selected": true, "text": ".bbb {\n width: 333px;\n height: 0px;\n background: transparent;\n border-bottom: 2px solid #000;\n margin-bottom: 30px;\n}" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422826/" ]
74,325,067
<p>I had the following pipeline:</p> <pre><code>from typing import Sequence, List import apache_beam as beam def add_type(x) -&gt; int: return x # no type error with Sequence, type error with List. def print_with_type(x: Sequence[int]): print(x) with beam.Pipeline(argv=[&quot;--type_check_additional&quot;, &quot;all&quot;]) as pipeline: lines = ( pipeline | beam.Create([1, 2]) | beam.Map(add_type) # removing this line should trigger type error # | beam.combiners.ToList() | beam.Map(print_with_type)) </code></pre> <p>I expected a type checking error when building the pipeline, but did not get it. Only after much debugging did I realize that I should use <code>List</code> instead of <code>Sequence</code>.</p> <p>Is this expected, as <code>Sequence</code> is one of the supported types (<a href="https://beam.apache.org/documentation/sdks/python-type-safety/#parameterized-type-hints" rel="nofollow noreferrer">doc</a>)? Is it possible to have a warning in such cases?</p>
[ { "answer_id": 74326930, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 1, "selected": false, "text": "List" }, { "answer_id": 74342652, "author": "CaptainNabla", "author_id": 16622985, "author_profile": "https://Stackoverflow.com/users/16622985", "pm_score": 2, "selected": false, "text": "List" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4696339/" ]
74,325,068
<p>I'm trying to use <code>to_json</code> to create a json file with python. I have it working so far to produce the following sort of output:</p> <pre><code>[ { &quot;Country&quot;: &quot;A&quot;, &quot;Title&quot;: &quot;B&quot;, &quot;Category&quot;: &quot;C&quot; }, { &quot;Country&quot;: &quot;D&quot;, &quot;Title&quot;: &quot;E&quot;, &quot;Category&quot;: &quot;F&quot; } ] </code></pre> <p>But I need it to create a json file that looks like this. Quite simply, to add the &quot;data&quot; name. Any tips on how to do so?</p> <pre><code>{ &quot;data&quot;: [ { &quot;Country&quot;: &quot;A&quot;, &quot;Title&quot;: &quot;B&quot;, &quot;Category&quot;: &quot;C&quot; }, { &quot;Country&quot;: &quot;D&quot;, &quot;Title&quot;: &quot;E&quot;, &quot;Category&quot;: &quot;F&quot; } ] } </code></pre>
[ { "answer_id": 74325095, "author": "Raibek", "author_id": 11040577, "author_profile": "https://Stackoverflow.com/users/11040577", "pm_score": -1, "selected": false, "text": "df.to_json(....., orient='records')\n" }, { "answer_id": 74325104, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": ".to_json()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15439406/" ]
74,325,069
<p>One requirement of mine is - Using windows, not use any tools not already available as part of aws cli or windows For example, I have this json file test.json with below content:</p> <p><code>&quot;My number is $myvar&quot;</code></p> <p>I read this into a powershell variable like so:</p> <pre><code>$myobj=(get-content .\test.json | convertfrom-json) $myvar=1 </code></pre> <p>From here, I would like to do something with this <code>$myobj</code> which will enable me to get this output:</p> <pre><code>$myobj | tee json_with_values_from_environment.json My number is 1 </code></pre> <p>I got some limited success with iex, but not sure if it can be made to work for this example</p>
[ { "answer_id": 74325095, "author": "Raibek", "author_id": 11040577, "author_profile": "https://Stackoverflow.com/users/11040577", "pm_score": -1, "selected": false, "text": "df.to_json(....., orient='records')\n" }, { "answer_id": 74325104, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": ".to_json()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1924658/" ]
74,325,166
<p>I am using <strong>Google Photos</strong> to host photos for a website I am managing, and accessing them via <strong>GraphQL</strong> and <strong>Gastby</strong> (gatsby-image-plugin)</p> <p>The images are shown in a gallery, but open up in a light-box gallery slider - I'm using FancyApps/ui (v4.x). Anyway the maximum size of the images are the maximum size of the source set (i.e. 512px). This means on a big screen the full screen image looks small (only 512px wide). You can see these values on the screen-grab below:</p> <pre><code>&quot;original&quot;: { &quot;width&quot;: 512, &quot;height&quot;: 341 } </code></pre> <p>The original image is 1200px width, which is confirmed by the media metadata:</p> <pre><code>&quot;mediaMetadata&quot;: { &quot;height&quot;: &quot;800&quot;, &quot;width&quot;: &quot;1200&quot; }&quot; </code></pre> <p>Which is the same as images &gt; sources &gt; sizes: <code>&quot;sizes&quot;: &quot;(min-width: 512px) 512px, 100vw&quot;</code></p> <p>I realise I can force the value by specifying gatsbyImageSharp to have a width of 1200.</p> <pre><code>{ allGooglePhotosAlbum(filter: {title: {eq: &quot;assorted&quot;}}) { nodes { title photos { file { childImageSharp { id gatsbyImageData(placeholder: BLURRED, width: 1200) original { width height } } } mediaMetadata { height width } } } } } </code></pre> <p>However some of the images are not 1200px wide (i.e. the portrait images), I get the following warning:</p> <pre><code>The requested width &quot;1200px&quot; for a resolutions field for the file URL_HERE was larger than the actual image width of 512px! If possible, replace the current image with a larger one. </code></pre> <p>I don't like the warning, but more importantly I think this might make the height of the image too large to be displayed properly (i.e. either would be cropped or larger than the screen height - 100vh).</p> <p>Surely there, should be a way to set the largest image width/height to the heights provided by the media metadata (i.e. the full un-adulterated image).</p> <p><a href="https://i.stack.imgur.com/9z5a3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9z5a3.jpg" alt="GraphQL ScreenGrab" /></a></p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14235783/" ]
74,325,190
<p>I have a simple table like this,</p> <pre><code>CREATE TABLE `domain` ( `id` varchar(191) NOT NULL, `time` bigint(20) DEFAULT NULL, `task_id` bigint(20) DEFAULT NULL, `name` varchar(512) DEFAULT NULL PRIMARY KEY (`id`), KEY `idx_domain_time` (`time`), KEY `idx_domain_task_id` (`task_id`), FULLTEXT KEY `idx_domain_name` (`name`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 </code></pre> <p>And indexed like this:</p> <pre><code>mysql&gt; show index from domain; +--------+------------+------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Ignored | +--------+------------+------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ | domain | 0 | PRIMARY | 1 | id | A | 2036092 | NULL | NULL | | BTREE | | | NO | | domain | 1 | idx_domain_name | 1 | name | NULL | NULL | NULL | NULL | YES | FULLTEXT | +--------+------------+------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+ </code></pre> <p>Index is used when I select only the <code>id</code> field:</p> <pre><code>mysql&gt; explain SELECT id FROM `domain` WHERE task_id = '3'; +------+-------------+--------+------+--------------------+--------------------+---------+-------+---------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+--------+------+--------------------+--------------------+---------+-------+---------+-------------+ | 1 | SIMPLE | domain | ref | idx_domain_task_id | idx_domain_task_id | 9 | const | 1018046 | Using index | +------+-------------+--------+------+--------------------+--------------------+---------+-------+---------+-------------+ 1 row in set (0.00 sec) </code></pre> <p>When I select all fields, it does not work:</p> <pre><code>mysql&gt; explain SELECT * FROM `domain` WHERE task_id = '3'; +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ | 1 | SIMPLE | domain | ALL | idx_domain_task_id | NULL | NULL | NULL | 2036092 | Using where | +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ 1 row in set (0.00 sec) mysql&gt; explain SELECT id, name FROM `domain` WHERE task_id = '3'; +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ | 1 | SIMPLE | domain | ALL | idx_domain_task_id | NULL | NULL | NULL | 2036092 | Using where | +------+-------------+--------+------+--------------------+------+---------+------+---------+-------------+ 1 row in set (0.00 sec) </code></pre> <p>What's wrong?</p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
74,325,199
<p>I want to write a function that will print the title and x and y labels. I managed to get the title to display but my code does not display the axis labels.</p> <pre><code>def title(t, y, x): return ax.set_title(t) ax.set_ylabel(y) ax.set_xlabel(x) </code></pre> <p>I expect the code to display the Title, y-axis label, and x-axis label I enter the function like this:</p> <pre><code>title('LKJH', 'gg', 'ff') </code></pre> <p>I get the following chart instead <a href="https://i.stack.imgur.com/vDP04.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vDP04.png" alt="Chart that is produced from code" /></a></p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18787560/" ]
74,325,201
<p>I'm Creating the App Registration, App Registration Secrets, API Permissions, and Role Assignment via Terraform. I'm Able to allocate the MicroSoft Graph API Permissions and able to Grant Permissions. For Log Analytic API Permission Grant, I'm Getting Error on the Terraform code.</p> <pre><code>data &quot;azuread_client_config&quot; &quot;current&quot; {} data &quot;azuread_application_published_app_ids&quot; &quot;well_known&quot; {} resource &quot;azuread_service_principal&quot; &quot;msgraph&quot; { application_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph use_existing = true owners = [data.azuread_client_config.current.object_id] } data &quot;azuread_application_published_app_ids&quot; &quot;log&quot; {} resource &quot;azuread_service_principal&quot; &quot;LogAnalyticsApi&quot; { application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI use_existing = true owners = [data.azuread_client_config.current.object_id] } # Retrieve domain information data &quot;azuread_domains&quot; &quot;domain&quot; { only_initial = true } # Create an application resource &quot;azuread_application&quot; &quot;appreg&quot; { display_name = &quot;Demo_App_Registration_Portal&quot; owners = [data.azuread_client_config.current.object_id] sign_in_audience = &quot;AzureADMultipleOrgs&quot; required_resource_access { resource_app_id = data.azuread_application_published_app_ids.well_known.result.MicrosoftGraph resource_access { id = azuread_service_principal.msgraph.app_role_ids[&quot;User.Read.All&quot;] type = &quot;Role&quot; } resource_access { id = azuread_service_principal.msgraph.app_role_ids[&quot;Directory.Read.All&quot;] type = &quot;Role&quot; } resource_access { id = azuread_service_principal.msgraph.app_role_ids[&quot;Domain.Read.All&quot;] type = &quot;Role&quot; } resource_access { id = azuread_service_principal.msgraph.app_role_ids[&quot;Domain.ReadWrite.All&quot;] type = &quot;Role&quot; } resource_access { id = azuread_service_principal.msgraph.oauth2_permission_scope_ids[&quot;User.Read&quot;] type = &quot;Scope&quot; } resource_access { id = azuread_service_principal.msgraph.oauth2_permission_scope_ids[&quot;Domain.ReadWrite.All&quot;] type = &quot;Scope&quot; } ##### resource_access { id = azuread_service_principal.msgraph.app_role_ids[&quot;UserAuthenticationMethod.Read.All&quot;] type = &quot;Role&quot; } ##### } #Log Analytic API Data Read Access required_resource_access { resource_app_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI resource_access { id = azuread_service_principal.LogAnalyticsAPI.app_role_ids[&quot;Data.Read&quot;] type = &quot;Role&quot; } } } #Creating Client Password for the Application resource &quot;azuread_application_password&quot; &quot;appregpassword&quot; { display_name = &quot;Demo_App_Registration_Portal_Password&quot; application_object_id = azuread_application.appreg.object_id depends_on = [ azuread_application.appreg ] } output &quot;azuread_application_password&quot; { value = azuread_application_password.appregpassword.id } # Create a service principal resource &quot;azuread_service_principal&quot; &quot;appregsp&quot; { application_id = azuread_application.appreg.application_id app_role_assignment_required = true owners = [data.azuread_client_config.current.object_id] } resource &quot;azuread_app_role_assignment&quot; &quot;example&quot; { app_role_id = azuread_service_principal.msgraph.app_role_ids[&quot;User.Read.All&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.msgraph.object_id } resource &quot;azuread_app_role_assignment&quot; &quot;Directory&quot; { app_role_id = azuread_service_principal.msgraph.app_role_ids[&quot;Directory.Read.All&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.msgraph.object_id } resource &quot;azuread_app_role_assignment&quot; &quot;Domain-Read&quot; { app_role_id = azuread_service_principal.msgraph.app_role_ids[&quot;Domain.Read.All&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.msgraph.object_id } resource &quot;azuread_app_role_assignment&quot; &quot;Domain-Read-Write&quot; { app_role_id = azuread_service_principal.msgraph.app_role_ids[&quot;Domain.ReadWrite.All&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.msgraph.object_id } #### resource &quot;azuread_app_role_assignment&quot; &quot;UserAuthenticationMethod-Read-All&quot; { app_role_id = azuread_service_principal.msgraph.app_role_ids[&quot;UserAuthenticationMethod.Read.All&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.msgraph.object_id } #### resource &quot;azuread_service_principal_delegated_permission_grant&quot; &quot;example&quot; { service_principal_object_id = azuread_service_principal.appregsp.object_id resource_service_principal_object_id = azuread_service_principal.msgraph.object_id claim_values = [&quot;User.Read&quot;, &quot;Domain.ReadWrite.All&quot;] } ##Log Analytics API Role Assignment resource &quot;azuread_app_role_assignment&quot; &quot;LogAnalytics-Read&quot; { app_role_id = azuread_service_principal.LogAnalyticsAPI.app_role_ids[&quot;Data.Read&quot;] principal_object_id = azuread_service_principal.appregsp.object_id resource_object_id = azuread_service_principal.LogAnalyticsAPI.object_id } #Role Assigning to the App data &quot;azurerm_subscription&quot; &quot;primary&quot; { } data &quot;azurerm_client_config&quot; &quot;appregclient&quot; { } resource &quot;azurerm_role_assignment&quot; &quot;example&quot; { scope = data.azurerm_subscription.primary.id role_definition_name = &quot;Reader&quot; principal_id = azuread_service_principal.appregsp.object_id depends_on = [ azuread_application.appreg ] } </code></pre> <p>I'm Creating the App Registration, App Registration Secrets, API Permissions, and Role Assignment via Terraform. I'm Able to allocate the MicroSoft Graph API Permissions and able to Grant Permissions. For Log Analytic API Permission Grant, I'm Getting Error on the Terraform code. I have upload how I want Log Analytic API Permission in the Image.</p> <p><a href="https://i.stack.imgur.com/28Ouz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/28Ouz.png" alt="enter image description here" /></a></p> <p>But I'm getting the Error Message as below:</p> <p><a href="https://i.stack.imgur.com/4g57a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4g57a.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20362753/" ]
74,325,224
<p><a href="https://i.stack.imgur.com/tmvtG.jpg" rel="nofollow noreferrer">enter image description here</a>I'm using Hibernate to Auto Create a Table on pgAdmin. -The log is not showing any errors -It is recognizing the existence of the db since i get an error if i delete it -Im using dll-auto: update</p> <p>I'm trying to auto create a table using Hibernate on pgadmin. Code is giving no errors but the table is not being created</p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20413172/" ]
74,325,233
<p>I have reacted app and there are many components, and I want that the text will support multiple languages, I mean if the user wants English then all content of the component translates into English.</p> <p>I try to add multilanguage in my react app using the i18next library but I found that I need to write all text in every language and store somewhere then use that.</p> <p>But I want it when the user selects language and then it translates into the desired language without hard code.</p> <p>like when we write anything in google translator then it translates all the page with the desired language.</p>
[ { "answer_id": 74326690, "author": "Ferran Buireu", "author_id": 5585371, "author_profile": "https://Stackoverflow.com/users/5585371", "pm_score": 1, "selected": false, "text": "{\n allGooglePhotosAlbum(filter: {title: {eq: \"assorted\"}}) {\n nodes {\n title\n photos {\n file {\n childImageSharp {\n id\n gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)\n original {\n width\n height\n }\n }\n }\n mediaMetadata {\n height\n width\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423054/" ]
74,325,246
<p>I am writing a simple car rental system to check price of a car.</p> <p>This is the <code>Available Vehicles.txt</code> In which the 3rd row is the car price.</p> <pre><code>RegNumber | Car Name | Price | Transmission Type </code></pre> <pre><code>H4E-11,Toyota,66,Automatic Transmission X11-11,Volkswagen,62,Automatic Transmission JBA-123,Ibiza,65,Automatic Transmission MDZ-A1A,Kodiaq,71,Automatic Transmission </code></pre> <p>I want to loop through the first row and if the registration number matches the entered registration number it goes through the line and checks the price in the third column</p> <p>I have a function that asks user to enter his/her car registration number it then checks if the registration number is available in the first row of a file.</p> <pre class="lang-py prettyprint-override"><code>def returnCar(): # Ask registration number of car to rent regNumber = str(input(&quot;Please enter Registration Number of Car: &quot;)) # Check if Car is in the system regNumbers = [] # List of registration number [H4E-11, X11-11, JBA-123, MDZ-A1A] with open(&quot;../AvailableVehicles.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f: for data in f: regRow = str(data.split(&quot;,&quot;)[0]) regNumbers += [regRow] # append registration number to the list if regNumber in regNumbers: # get price from equivalent row </code></pre> <p>I want to print something like:</p> <pre><code>Please enter Registration Number of Car: H4E-11 The price is: 66 dollars </code></pre>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18105834/" ]
74,325,280
<p>so I take a user input in a loop seen below</p> <pre><code>mail_list = [] x = 0 while x &gt;= 0: user_input = input('enter first name, last name, ID, and email domain: ') mail_list.append(user_input) if user_input == 'done': break </code></pre> <p>so it is supposed to add the first name, last name, and email domain together to make a full email address. not sure if lists are the best path to go or splicing the spring. The problem I ran into when trying to just splice it would only use 'done' as the last input so I assumed adding it to a list would be the best path. just lost</p>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423088/" ]
74,325,302
<p>I want to grab the string after the <code>CN=</code> in each of the strings below, and nothing else:</p> <pre><code>&quot;CN=*.company.com,O=WWT,L=STL,ST=Missouri,C=US&quot;, &quot;emailAddress=root@localhost.localdomain,CN=localhost.localdomain,OU=IT,O=MyCompany,L=Seattle,ST=WA,C=US&quot; </code></pre> <p>I want <code>*.company.com</code> and <code>localhost.localdomain</code></p> <p>I think I'm close, but I'm getting more returned that I want:</p> <pre><code>(ansible) ➜ ~ ansible --version ansible 2.10.17 </code></pre> <pre><code>--- - hosts: localhost connection: local gather_facts: false vars: str1: &quot;CN=*.company.com,O=WWT,L=STL,ST=Missouri,C=US&quot; str2: &quot;emailAddress=root@localhost.localdomain,CN=localhost.localdomain,OU=IT,O=MyCompany,L=Seattle,ST=WA,C=US&quot; tasks: - debug: msg: - &quot;{{ str1 | regex_search('CN=(.*),(.*$)', '\\1', '\\2') }}&quot; - &quot;{{ str1.split(',') | regex_search('CN=(.*)', '\\1') }}&quot; - &quot;{{ str2 | regex_search('CN=(.*),(.*$)', '\\1', '\\2') }}&quot; - &quot;{{ str2.split(',') | regex_search('CN=(.*)', '\\1') }}&quot; </code></pre> <pre><code>(ansible) ➜ ~ ansible-playbook test2.yaml [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ******************************************************************************************************************************************************************************************************************* TASK [debug] *********************************************************************************************************************************************************************************************************************** ok: [localhost] =&gt; { &quot;msg&quot;: [ [ &quot;*.company.com,O=WWT,L=STL,ST=Missouri,&quot;, &quot;C=US&quot; ], [ &quot;*.company.com', 'O=WWT', 'L=STL', 'ST=Missouri', 'C=US']&quot; ], [ &quot;localhost.localdomain,OU=IT,O=MyCompany,L=Seattle,ST=WA,&quot;, &quot;C=US&quot; ], [ &quot;localhost.localdomain', 'OU=IT', 'O=MyCompany', 'L=Seattle', 'ST=WA', 'C=US']&quot; ] ] } PLAY RECAP ************************************************************************************************************************************************************************************************************************* localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 </code></pre>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371155/" ]
74,325,310
<p>I am new to postgresql and am trying to update a table based on conditions using PostgreSQL stored procedure. The table 'pref2' looks like this:</p> <pre><code>geneid pred_perf_r2 pred_perf_pval vers ENSG00000107959 0.03 0.02 1.0 ENSG00000106321 0.05 0.01 1.0 ENSG00000102222 0.22 0.05 1.0 ENSG00000101111 0.11 0.03 1.0 ENSG00000102355 0.33 0.01 1.0 </code></pre> <p>I want to create a stored procedure for updating this table for pred_perf_r2 and pred_perf_pval if the new scores are better (bigger R2 and smaller pval). My attempt:</p> <pre><code>create or replace procedure new_version( gene varchar(50), new_r2 numeric, new_p numeric, new_v numeric ) language plpgsql as $$ begin if (new_r2 &gt; perf2.pred_perf_r2) and (new_p &lt; perf2.pred_perf_pval) then update perf2 set perf2.pred_perf_r2 = new_r2, perf2.pred_perf_pval = new_p , perf2.vers = new_v where perf2.geneid = gene; end if; commit; END;$$ call new_version('ENSG00000107959',0.55,0.01,2.0); select * from perf2; </code></pre> <p>It gives me this error:</p> <pre><code>ERROR: missing FROM-clause entry for table &quot;perf2&quot; LINE 1: (new_r2 &gt; perf2.pred_perf_r2) ^ QUERY: (new_r2 &gt; perf2.pred_perf_r2) and (new_p &lt; perf2.pred_perf_pval) CONTEXT: PL/pgSQL function new_version(character varying,numeric,numeric,numeric) line 3 at IF SQL state: 42P01 </code></pre> <p>My desired result will look like this when calling the stored procedure:</p> <pre><code>geneid pred_perf_r2 pred_perf_pval vers ENSG00000107959 0.55 0.01 2.0 ENSG00000106321 0.05 0.01 1.0 ENSG00000102222 0.22 0.05 1.0 ENSG00000101111 0.11 0.03 1.0 ENSG00000102355 0.33 0.01 1.0 </code></pre> <p>if</p> <pre><code>call new_version('ENSG00000107959',0.02,0.05,2.0); </code></pre> <p>The original table should not change since R square is worse (0.02 &lt; 0.03) and pval is larger (0.05&gt;0.02) It keeps giving me errors. Any ideas on how I can fix this?</p>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12335546/" ]
74,325,311
<p><a href="https://i.stack.imgur.com/ns32u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ns32u.png" alt="1" /></a></p> <p>I have a dataset like the above. Basically it's like a website session which I have a start + end activity, and in between there could be other unrelated records.</p> <p>I need to pull the records based on:</p> <ul> <li>I need to report all the &quot;end&quot; activity from the table</li> <li>In each &quot;end&quot; record, I need to find its nearest previous &quot;start&quot; row's &quot;Content_ID&quot; value. The record must also match the &quot;Profile_ID&quot; as well</li> <li>The result I expected is as follows:</li> </ul> <p><a href="https://i.stack.imgur.com/BT9iQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BT9iQ.png" alt="enter image description here" /></a></p> <p>May I ask how could I construct the SQL to do this?</p> <p>Thanks so much!</p>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12718820/" ]
74,325,312
<p>I connected 2D barcode scanner with Raspberry Pi 4 Model B and tried to scan few codes. on using <strong>evdev</strong> library I got the output successfully. But the issue is after 3 continues scans it's throwing me an exception saying <em><strong>&quot;[Error 16] Device or resource busy&quot;</strong></em>. I can't able to find the root cause of this issue and tried many troubleshooting methods but nothing seems to work. Can anyone please help me. Here is the code I used.</p> <pre><code>from evdev import InputDevice, categorize, ecodes from datetime import datetime import calendar scancodes = { # Scancode: ASCIICode 0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8', 10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'q', 17: u'w', 18: u'e', 19: u'r', 20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL', 30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';', 40: u'&quot;', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n', 50: u'm', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 57: u' ', 100: u'RALT' } capscodes = { 0: None, 1: u'ESC', 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&amp;', 9: u'*', 10: u'(', 11: u')', 12: u'_', 13: u'+', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R', 20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}', 28: u'CRLF', 29: u'LCTRL', 30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':', 40: u'\'', 41: u'~', 42: u'LSHFT', 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N', 50: u'M', 51: u'&lt;', 52: u'&gt;', 53: u'?', 54: u'RSHFT', 56: u'LALT', 57: u' ', 100: u'RALT' } class scan_barcode: def __init__(self,devicePath): self.devicePath = devicePath def readBarcode(self): dev = InputDevice(self.devicePath) dev.grab() # grab provides exclusive access to the device x = '' caps = False for event in dev.read_loop(): if event.type == ecodes.EV_KEY: data = categorize(event) # Save the event temporarily to introspect it if data.scancode == 42: if data.keystate == 1: caps = True if data.keystate == 0: caps = False if data.keystate == 1: # Down events only if caps: key_lookup = u'{}'.format(capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode) # Lookup or return UNKNOWN:XX else: key_lookup = u'{}'.format(scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode) # Lookup or return UNKNOWN:XX if (data.scancode != 42) and (data.scancode != 28): x += key_lookup if(data.scancode == 28): return(x) scanned_data = scan_barcode('/dev/input/event0') def scanner_function(): try: value = scanned_data.readBarcode() print(f&quot;Scanned value:{str(value)}&quot;) except Exception as e: print(e) pass while True: scanner_function() </code></pre> <p>Even though when I pass the exception It's not letting me to move to other tasks. The entire process stops here.</p> <p>This is the output:</p> <pre><code>Scanned value: 4568hidhXGu Scanned value: 1238fujXjje75 Scanned value: 789665 [Error 16] Device or resource busy [Error 16] Device or resource busy [Error 16] Device or resource busy [Error 16] Device or resource busy [Error 16] Device or resource busy </code></pre>
[ { "answer_id": 74325273, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "index" }, { "answer_id": 74325316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "csv" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16392499/" ]
74,325,343
<p>This is my code.</p> <pre><code>struct node_struct { char *data; struct node_struct *next; }; typedef struct node_struct Node; struct queue_struct { Node *head, *tail; }; typedef struct queue_struct Queue; </code></pre> <pre><code>void push(Queue **q, char *word) { // q hasn't been allocated if (*q == NULL) { (*q) = malloc(sizeof(Queue)); } Node *temp; temp = malloc(sizeof(Node)); temp-&gt;data = malloc(sizeof(char)*strlen(word)); strcpy(temp-&gt;data, word); temp-&gt;next = NULL; if ((*q)-&gt;head == NULL) { (*q)-&gt;head = (*q)-&gt;tail = temp; } else { (*q)-&gt;tail-&gt;next = temp; (*q)-&gt;tail = temp; } } </code></pre> <p>I will use <code>push</code> to pushes a string word to the back of a queue q. Instead of keeping the pointer to the array, it keeps a copy of the word inside the queue.</p> <p>Finally, I want to deallocates the queue as well as all items in it. So, I use <code>free()</code> and this is what I write.</p> <pre><code>void delete(Queue *q) { Node *temp; for (temp = q-&gt;head; temp != NULL; temp = temp-&gt;next) { free(temp-&gt;data); free(temp); } free(q); } </code></pre> <p>But, this lead to segmentation fault. Why this happen, and how can I fix this?</p>
[ { "answer_id": 74325435, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 2, "selected": true, "text": "malloc()" }, { "answer_id": 74325442, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "for (temp = q->head; temp != NULL; temp = temp->next) {\n free(temp->data); \n free(temp);\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376070/" ]
74,325,368
<p>I have a Kafka application which suffers from intermittent deserialisation errors (due to connectivity problems to the host which provides Avro schemas)</p> <p>I would like to back off and retry serialisation exceptions, but I have not been able to figure out how to set that up.</p> <p>Here's my test configuration:</p> <pre class="lang-java prettyprint-override"><code>@org.springframework.context.annotation.Configuration @EnableKafka public class Configuration { @Bean(&quot;myContainerFactory&quot;) public ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; createFactory( KafkaProperties properties ) { var factory = new ConcurrentKafkaListenerContainerFactory&lt;String, String&gt;(); factory.setConsumerFactory( new DefaultKafkaConsumerFactory( properties.buildConsumerProperties(), new StringDeserializer(), new ErrorHandlingDeserializer(new MyDeserializer()) ) ); factory.getContainerProperties().setAckMode( ContainerProperties.AckMode.MANUAL_IMMEDIATE ); factory.setCommonErrorHandler(new DefaultErrorHandler()); return factory; } // this fakes occasional errors which succeed after a retry static class MyDeserializer implements Deserializer&lt;String&gt; { int retries = 0; @Override public String deserialize(String topic, byte[] bytes) { String s = new String(bytes); if (s.contains(&quot;7&quot;) &amp;&amp; retries == 0) { retries = 1; throw new RuntimeException(); } retries = 0; return s; } } } </code></pre> <p>and my consumer:</p> <pre class="lang-java prettyprint-override"><code>@Component public class StringListener { @KafkaListener( topics = {&quot;string-test&quot;}, groupId = &quot;test&quot;, batch = &quot;true&quot;, containerFactory = &quot;myContainerFactory&quot; ) public void listen(List&lt;String&gt; messages, Acknowledgment acknowledgment) { for (String s: messages) { System.out.println(s); } acknowledgment.acknowledge(); } } </code></pre> <p>At present the <code>ErrorHandlingDeserializer</code> just returns <code>null</code>.</p> <p>Do I need to implement a <code>failedDeserializationFunction</code>, or is there a there a simple way to configure the factory so that my deserialiser is called again, after a configurable wait, for some configurable number of times?</p>
[ { "answer_id": 74325435, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 2, "selected": true, "text": "malloc()" }, { "answer_id": 74325442, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "for (temp = q->head; temp != NULL; temp = temp->next) {\n free(temp->data); \n free(temp);\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002/" ]
74,325,370
<p>I have a table &quot;store&quot; and a table &quot;product&quot;. Each store has multiple products but a product only has one store ( one to many relationship ). The tables might look something like:</p> <p>store: id, name<br /> product: id, name, store_id</p> <p>when querying the store and its products using supabase I simply do:</p> <pre><code> .from(&quot;store&quot;) .select( id name, product(name) ) </code></pre> <p>which would return</p> <pre><code> id: &quot;some_id&quot;, name: &quot;some_name&quot;, products: [ {...}, {...} ] } </code></pre> <p>or something along those lines depending on what data I want. However, I need to run this query in pure SQL and I can't seem to figure it out.</p> <p>I tried to JOIN the tables together but it leads to a lot of duplicated data since the store's data is in all the rows</p>
[ { "answer_id": 74325494, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 0, "selected": false, "text": "SELECT \n CONCAT(\"{id:'\", s.id, \"', Name:'\" , s.`Name`, \"', products: [\", \n GROUP_CONCAT(CONCAT(\"{id:'\",p.id,\"', Name:'\", p.`Name`, \"'} \"))\n ,\"]}\")\nFROM\n store AS s, product AS p\nWHERE\n (s.id = p.store_id) AND (s.id=1)\nGROUP BY\n s.Id\n" }, { "answer_id": 74331605, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 3, "selected": true, "text": "select to_jsonb(s)||jsonb_build_object('products', p.products)\nfrom store s\n join (\n select p.store_id, jsonb_agg(to_jsonb(p) - 'store_id' order by p.store_id) products\n from product p\n group by p.store_id\n ) p on p.store_id = s.id\n;\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423110/" ]
74,325,381
<p>I have an API response</p> <p>const response = [</p> <p>{ id:1, tags:[data:&quot;save1&quot;] },</p> <p>{ id:2, tags:[data:&quot;save2&quot;] },</p> <p>{ id:3, tags:[data:&quot;save3&quot;] },</p> <p>]</p> <p>I want to save the data of all tags into a single array like below e.g</p> <p>const newArr = [{save1},{save2},{save3}]</p> <p>how can i achieve that</p> <p>I am new to in this any help will be appreciated. thank you</p>
[ { "answer_id": 74325494, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 0, "selected": false, "text": "SELECT \n CONCAT(\"{id:'\", s.id, \"', Name:'\" , s.`Name`, \"', products: [\", \n GROUP_CONCAT(CONCAT(\"{id:'\",p.id,\"', Name:'\", p.`Name`, \"'} \"))\n ,\"]}\")\nFROM\n store AS s, product AS p\nWHERE\n (s.id = p.store_id) AND (s.id=1)\nGROUP BY\n s.Id\n" }, { "answer_id": 74331605, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 3, "selected": true, "text": "select to_jsonb(s)||jsonb_build_object('products', p.products)\nfrom store s\n join (\n select p.store_id, jsonb_agg(to_jsonb(p) - 'store_id' order by p.store_id) products\n from product p\n group by p.store_id\n ) p on p.store_id = s.id\n;\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20237991/" ]
74,325,399
<p>Currently I have 2 array lists showing words and their frequency. So &quot;the&quot; has a frequency of 1, &quot;I&quot; has a frequency of 10 and so on.</p> <pre><code> ArrayList&lt;String&gt; words = new ArrayList&lt;&gt;(Arrays.asList(&quot;the&quot;, &quot;I&quot;, &quot;false&quot;,&quot;too&quot;)); ArrayList&lt;Integer&gt; frequency = new ArrayList&lt;&gt;(Arrays.asList(1, 10, 5, 7)); Collections.sort(frequency, Collections.reverseOrder()); </code></pre> <p>What I want to do is sort them from highest word frequency to lowest, so I used Collections.sort to sort frequency from highest values to lowest. This gives me the expected result of</p> <p>[10, 7, 5, 1]</p> <p>But now I'm at a complete standstill has to how to sort the words ArrayList so that the indexes of each list still correspond to each other.</p> <p>My desired output would be for the words arraylist would be.</p> <p>[&quot;I&quot;, &quot;too&quot;, &quot;false&quot;, &quot;the&quot;]</p> <p>Is there some kind of method within Collections that can accomplish this?</p>
[ { "answer_id": 74325554, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "[0, 1, 2, 3]" }, { "answer_id": 74327054, "author": "Chaosfire", "author_id": 17795888, "author_profile": "https://Stackoverflow.com/users/17795888", "pm_score": 0, "selected": false, "text": "public class Test {\n\n public static void main(String[] args) {\n ArrayList<String> words = new ArrayList<>(Arrays.asList(\"the\", \"I\", \"false\",\"too\"));\n ArrayList<Integer> frequency = new ArrayList<>(Arrays.asList(1, 10, 5, 7));\n\n Map<String, Integer> wordFrequency = new HashMap<>();\n for (int i = 0; i < words.size(); i++) {\n wordFrequency.put(words.get(i), frequency.get(i));\n }\n List<String> sortedByFrequency = wordFrequency.entrySet()\n .stream()\n .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))\n .map(Map.Entry::getKey)\n .collect(Collectors.toList());\n System.out.println(sortedByFrequency);\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,325,419
<p>I have two datetime-local input star time is for user changeable and the other one is read-only and I want to update that field by jquery.</p> <pre><code>&lt;input class=&quot;form-control&quot; type=&quot;datetime-local&quot; name=&quot;deliveryTime&quot; id=&quot;DeliveryTime&quot; required&gt; </code></pre> <pre><code>&lt;input class=&quot;form-control&quot; type=&quot;datetime-local&quot; name=&quot;deliveryTimeEnd&quot; id=&quot;DeliveryTimeEnd&quot; readonly&gt; </code></pre> <pre><code> </code></pre> <pre><code>$(&quot;#DeliveryTime&quot;).on(&quot;change&quot;, function() { var startTime = $(&quot;#DeliveryTime&quot;).val(); startTime.setHours(startTime.getHours()+2); alert(startTime); $(&quot;#DeliveryTimeEnd&quot;).val(startTime); }); </code></pre> <pre><code></code></pre>
[ { "answer_id": 74325554, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "[0, 1, 2, 3]" }, { "answer_id": 74327054, "author": "Chaosfire", "author_id": 17795888, "author_profile": "https://Stackoverflow.com/users/17795888", "pm_score": 0, "selected": false, "text": "public class Test {\n\n public static void main(String[] args) {\n ArrayList<String> words = new ArrayList<>(Arrays.asList(\"the\", \"I\", \"false\",\"too\"));\n ArrayList<Integer> frequency = new ArrayList<>(Arrays.asList(1, 10, 5, 7));\n\n Map<String, Integer> wordFrequency = new HashMap<>();\n for (int i = 0; i < words.size(); i++) {\n wordFrequency.put(words.get(i), frequency.get(i));\n }\n List<String> sortedByFrequency = wordFrequency.entrySet()\n .stream()\n .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))\n .map(Map.Entry::getKey)\n .collect(Collectors.toList());\n System.out.println(sortedByFrequency);\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12642377/" ]
74,325,452
<p>How do I perform the following dataframe operation going from Dataframe A to dataframe B in pandas for python? I have tried pivot and groupby but I keep getting errors. Any support is greatly appreciated.</p> <p>DataFrame A</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col A</th> <th>Col B</th> </tr> </thead> <tbody> <tr> <td>100</td> <td>1</td> </tr> <tr> <td>100</td> <td>2</td> </tr> <tr> <td>200</td> <td>3</td> </tr> <tr> <td>200</td> <td>4</td> </tr> </tbody> </table> </div> <p>DataFrame B</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col A &amp; B</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>100</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> <tr> <td>200</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74325516, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "groupby" }, { "answer_id": 74327761, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "out = pd.DataFrame({'Col A&B': np.unique(df)})\nout\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8371891/" ]
74,325,460
<p>My react native project build fails somehow because of this error:</p> <pre><code>Execution failed for task ':app:mergeDebugNativeLibs'. &gt; A failure occurred while executing com.android.build.gradle.internal.tasks.MergeNativeLibsTask$MergeNativeLibsTaskWorkAction &gt; 2 files found with path 'lib/arm64-v8a/libfbjni.so' from inputs: - C:\Users\Antonio\.gradle\caches\transforms-3\7cca348744e25f57fc2d9f871aa73c9a\transformed\jetified-react-native-0.71.0-rc.0-debug\jni\arm64-v8a\libfbjni.so - C:\Users\Antonio\.gradle\caches\transforms-3\08b0f5c7017bf081f79b63ea5b053dc0\transformed\jetified-fbjni-0.3.0\jni\arm64-v8a\libfbjni.so If you are using jniLibs and CMake IMPORTED targets, see https://developer.android.com/r/tools/jniLibs-vs-imported-targets </code></pre> <p>Anybody got a clue what could cause the build to fail? I haven't edited any build file and/or removed/installed/upgraded new packages thanks</p>
[ { "answer_id": 74331998, "author": "Bogdan", "author_id": 12681742, "author_profile": "https://Stackoverflow.com/users/12681742", "pm_score": 4, "selected": false, "text": "implementation \"com.facebook.react:react-native:+\" // From node_modules\n" }, { "answer_id": 74339892, "author": "مصطفى", "author_id": 5509892, "author_profile": "https://Stackoverflow.com/users/5509892", "pm_score": 1, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:0.68.2'\n }\n}\n" }, { "answer_id": 74345193, "author": "Yusuf", "author_id": 14184139, "author_profile": "https://Stackoverflow.com/users/14184139", "pm_score": 2, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:CURRENT_VERSION_OF_REACT_NATIVE'\n }\n}\n" }, { "answer_id": 74352015, "author": "Mudasir Bilal", "author_id": 20443547, "author_profile": "https://Stackoverflow.com/users/20443547", "pm_score": 0, "selected": false, "text": "\"react-native\": \"^0.70.3\"\n" }, { "answer_id": 74356132, "author": "mabc21", "author_id": 723305, "author_profile": "https://Stackoverflow.com/users/723305", "pm_score": 0, "selected": false, "text": "def REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nallprojects {\n configurations.all {\n resolutionStrategy {\n // Remove this override in 0.65+, as a proper fix is included in react-native itself.\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n}\n" }, { "answer_id": 74359919, "author": "Sherif Samir", "author_id": 13174364, "author_profile": "https://Stackoverflow.com/users/13174364", "pm_score": 3, "selected": false, "text": "implementation 'com.facebook.react:react-native:+'" }, { "answer_id": 74366430, "author": "sugaith", "author_id": 7546092, "author_profile": "https://Stackoverflow.com/users/7546092", "pm_score": 1, "selected": false, "text": "allprojects {\n repositories {\n exclusiveContent {\n // Official recommended fix for Android build problem with React Native versions below 0.71\n // https://github.com/facebook/react-native/issues/35210\n // TODO: remove this exclusiveContent section when we upgrade to React Native 0.71 (or above)\n // copied from https://github.com/Scottish-Tech-Army/Volunteer-app/pull/101/commits/40a30310ee46194efbaf1c07aef8a0df70231eeb\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12098789/" ]
74,325,482
<p>I would like to write a function that accepts the knex instance as a parameter.</p> <p>I try to do that by</p> <pre><code>import knex from &quot;knex&quot;; export async function createTestTable(_knex: ReturnType&lt;knex&gt;) { ... } </code></pre> <p>But it returns the <code>Cannot use namespace 'knex' as a type.ts(2709) error.</code> Is there any method I can do the correct type annotation?</p>
[ { "answer_id": 74331998, "author": "Bogdan", "author_id": 12681742, "author_profile": "https://Stackoverflow.com/users/12681742", "pm_score": 4, "selected": false, "text": "implementation \"com.facebook.react:react-native:+\" // From node_modules\n" }, { "answer_id": 74339892, "author": "مصطفى", "author_id": 5509892, "author_profile": "https://Stackoverflow.com/users/5509892", "pm_score": 1, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:0.68.2'\n }\n}\n" }, { "answer_id": 74345193, "author": "Yusuf", "author_id": 14184139, "author_profile": "https://Stackoverflow.com/users/14184139", "pm_score": 2, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:CURRENT_VERSION_OF_REACT_NATIVE'\n }\n}\n" }, { "answer_id": 74352015, "author": "Mudasir Bilal", "author_id": 20443547, "author_profile": "https://Stackoverflow.com/users/20443547", "pm_score": 0, "selected": false, "text": "\"react-native\": \"^0.70.3\"\n" }, { "answer_id": 74356132, "author": "mabc21", "author_id": 723305, "author_profile": "https://Stackoverflow.com/users/723305", "pm_score": 0, "selected": false, "text": "def REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nallprojects {\n configurations.all {\n resolutionStrategy {\n // Remove this override in 0.65+, as a proper fix is included in react-native itself.\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n}\n" }, { "answer_id": 74359919, "author": "Sherif Samir", "author_id": 13174364, "author_profile": "https://Stackoverflow.com/users/13174364", "pm_score": 3, "selected": false, "text": "implementation 'com.facebook.react:react-native:+'" }, { "answer_id": 74366430, "author": "sugaith", "author_id": 7546092, "author_profile": "https://Stackoverflow.com/users/7546092", "pm_score": 1, "selected": false, "text": "allprojects {\n repositories {\n exclusiveContent {\n // Official recommended fix for Android build problem with React Native versions below 0.71\n // https://github.com/facebook/react-native/issues/35210\n // TODO: remove this exclusiveContent section when we upgrade to React Native 0.71 (or above)\n // copied from https://github.com/Scottish-Tech-Army/Volunteer-app/pull/101/commits/40a30310ee46194efbaf1c07aef8a0df70231eeb\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10683308/" ]
74,325,524
<p>I am trying to solve this problem on HackerRank and I am having a issue with my logic. I am confused and not able to think what I'm doing wrong, feels like I'm stuck in logic.</p> <p>Question link: <a href="https://www.hackerrank.com/challenges/game-of-thrones/" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/game-of-thrones/</a></p> <p>I created a dictionary of alphabets with value 0. And then counting number of times the alphabet appears in the string. If there are more than 1 alphabet characters occurring 1 times in string, then obviously that string cannot become a palindrome. That's my logic, however it only pass 10/21 test cases.</p> <p>Here's my code:</p> <pre><code>def gameOfThrones(s): alpha_dict = {chr(x): 0 for x in range(97,123)} counter = 0 for i in s: if i in alpha_dict: alpha_dict[i] += 1 for key in alpha_dict.values(): if key == 1: counter += 1 if counter &lt;= 1: return 'YES' else: return 'NO' </code></pre> <p>Any idea where I'm going wrong?</p>
[ { "answer_id": 74331998, "author": "Bogdan", "author_id": 12681742, "author_profile": "https://Stackoverflow.com/users/12681742", "pm_score": 4, "selected": false, "text": "implementation \"com.facebook.react:react-native:+\" // From node_modules\n" }, { "answer_id": 74339892, "author": "مصطفى", "author_id": 5509892, "author_profile": "https://Stackoverflow.com/users/5509892", "pm_score": 1, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:0.68.2'\n }\n}\n" }, { "answer_id": 74345193, "author": "Yusuf", "author_id": 14184139, "author_profile": "https://Stackoverflow.com/users/14184139", "pm_score": 2, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:CURRENT_VERSION_OF_REACT_NATIVE'\n }\n}\n" }, { "answer_id": 74352015, "author": "Mudasir Bilal", "author_id": 20443547, "author_profile": "https://Stackoverflow.com/users/20443547", "pm_score": 0, "selected": false, "text": "\"react-native\": \"^0.70.3\"\n" }, { "answer_id": 74356132, "author": "mabc21", "author_id": 723305, "author_profile": "https://Stackoverflow.com/users/723305", "pm_score": 0, "selected": false, "text": "def REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nallprojects {\n configurations.all {\n resolutionStrategy {\n // Remove this override in 0.65+, as a proper fix is included in react-native itself.\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n}\n" }, { "answer_id": 74359919, "author": "Sherif Samir", "author_id": 13174364, "author_profile": "https://Stackoverflow.com/users/13174364", "pm_score": 3, "selected": false, "text": "implementation 'com.facebook.react:react-native:+'" }, { "answer_id": 74366430, "author": "sugaith", "author_id": 7546092, "author_profile": "https://Stackoverflow.com/users/7546092", "pm_score": 1, "selected": false, "text": "allprojects {\n repositories {\n exclusiveContent {\n // Official recommended fix for Android build problem with React Native versions below 0.71\n // https://github.com/facebook/react-native/issues/35210\n // TODO: remove this exclusiveContent section when we upgrade to React Native 0.71 (or above)\n // copied from https://github.com/Scottish-Tech-Army/Volunteer-app/pull/101/commits/40a30310ee46194efbaf1c07aef8a0df70231eeb\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13015087/" ]
74,325,526
<p>getting error whenever i'm trying to ionic build.showing cordova-plugin-androidx-adapter: Processed 16 source files in 387ms Checking Java JDK and Android SDK versions ANDROID_SDK_ROOT=undefined (recommended setting) ANDROID_HOME=undefined (DEPRECATED)</p> <p>i changed sdk version and i'm using sdk 30 version also change path.but still getting same error</p>
[ { "answer_id": 74331998, "author": "Bogdan", "author_id": 12681742, "author_profile": "https://Stackoverflow.com/users/12681742", "pm_score": 4, "selected": false, "text": "implementation \"com.facebook.react:react-native:+\" // From node_modules\n" }, { "answer_id": 74339892, "author": "مصطفى", "author_id": 5509892, "author_profile": "https://Stackoverflow.com/users/5509892", "pm_score": 1, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:0.68.2'\n }\n}\n" }, { "answer_id": 74345193, "author": "Yusuf", "author_id": 14184139, "author_profile": "https://Stackoverflow.com/users/14184139", "pm_score": 2, "selected": false, "text": "configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:CURRENT_VERSION_OF_REACT_NATIVE'\n }\n}\n" }, { "answer_id": 74352015, "author": "Mudasir Bilal", "author_id": 20443547, "author_profile": "https://Stackoverflow.com/users/20443547", "pm_score": 0, "selected": false, "text": "\"react-native\": \"^0.70.3\"\n" }, { "answer_id": 74356132, "author": "mabc21", "author_id": 723305, "author_profile": "https://Stackoverflow.com/users/723305", "pm_score": 0, "selected": false, "text": "def REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nallprojects {\n configurations.all {\n resolutionStrategy {\n // Remove this override in 0.65+, as a proper fix is included in react-native itself.\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n}\n" }, { "answer_id": 74359919, "author": "Sherif Samir", "author_id": 13174364, "author_profile": "https://Stackoverflow.com/users/13174364", "pm_score": 3, "selected": false, "text": "implementation 'com.facebook.react:react-native:+'" }, { "answer_id": 74366430, "author": "sugaith", "author_id": 7546092, "author_profile": "https://Stackoverflow.com/users/7546092", "pm_score": 1, "selected": false, "text": "allprojects {\n repositories {\n exclusiveContent {\n // Official recommended fix for Android build problem with React Native versions below 0.71\n // https://github.com/facebook/react-native/issues/35210\n // TODO: remove this exclusiveContent section when we upgrade to React Native 0.71 (or above)\n // copied from https://github.com/Scottish-Tech-Army/Volunteer-app/pull/101/commits/40a30310ee46194efbaf1c07aef8a0df70231eeb\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11374352/" ]
74,325,532
<p>I am currently woking in a react native projects</p> <p>It have these packages as dependencies</p> <pre><code> &quot;dependencies&quot;: { &quot;@react-native-async-storage/async-storage&quot;: &quot;^1.15.5&quot;, &quot;@react-native-community/checkbox&quot;: &quot;^0.5.8&quot;, &quot;@react-native-community/cli&quot;: &quot;^7.0.3&quot;, &quot;@react-native-community/clipboard&quot;: &quot;^1.5.1&quot;, &quot;@react-native-community/datetimepicker&quot;: &quot;^3.5.2&quot;, &quot;@react-native-community/masked-view&quot;: &quot;^0.1.11&quot;, &quot;@react-native-picker/picker&quot;: &quot;^1.16.3&quot;, &quot;@react-navigation/drawer&quot;: &quot;^5.12.5&quot;, &quot;@react-navigation/material-top-tabs&quot;: &quot;^5.3.15&quot;, &quot;@react-navigation/native&quot;: &quot;^5.9.4&quot;, &quot;@react-navigation/stack&quot;: &quot;^5.14.5&quot;, &quot;@twotalltotems/react-native-otp-input&quot;: &quot;^1.3.11&quot;, &quot;axios&quot;: &quot;^0.21.1&quot;, &quot;axios-oauth-client&quot;: &quot;^1.4.2&quot;, &quot;axios-token-interceptor&quot;: &quot;^0.2.0&quot;, &quot;moment&quot;: &quot;^2.29.1&quot;, &quot;prop-types&quot;: &quot;^15.8.1&quot;, &quot;react&quot;: &quot;17.0.1&quot;, &quot;react-native&quot;: &quot;0.64.1&quot;, &quot;react-native-animatable&quot;: &quot;^1.3.3&quot;, &quot;react-native-app-intro-slider&quot;: &quot;^4.0.4&quot;, &quot;react-native-calendars&quot;: &quot;^1.1264.0&quot;, &quot;react-native-cardview&quot;: &quot;^2.0.5&quot;, &quot;react-native-date-picker&quot;: &quot;^4.2.1&quot;, &quot;react-native-device-info&quot;: &quot;^8.1.3&quot;, &quot;react-native-eject&quot;: &quot;^0.1.2&quot;, &quot;react-native-geolocation-service&quot;: &quot;^5.3.0&quot;, &quot;react-native-gesture-handler&quot;: &quot;^1.10.3&quot;, &quot;react-native-get-random-values&quot;: &quot;^1.8.0&quot;, &quot;react-native-image-picker&quot;: &quot;^4.0.3&quot;, &quot;react-native-material-dropdown&quot;: &quot;^0.11.1&quot;, &quot;react-native-modal-datetime-picker&quot;: &quot;^10.2.0&quot;, &quot;react-native-modal-picker&quot;: &quot;^0.0.16&quot;, &quot;react-native-pager-view&quot;: &quot;^5.4.23&quot;, &quot;react-native-phone-number-input&quot;: &quot;^2.1.0&quot;, &quot;react-native-picker-select&quot;: &quot;^8.0.4&quot;, &quot;react-native-reanimated&quot;: &quot;^2.2.0&quot;, &quot;react-native-safe-area-context&quot;: &quot;^3.2.0&quot;, &quot;react-native-screens&quot;: &quot;^3.3.0&quot;, &quot;react-native-searchable-dropdown&quot;: &quot;^1.1.3&quot;, &quot;react-native-signature-canvas&quot;: &quot;^4.3.0&quot;, &quot;react-native-simple-toast&quot;: &quot;^1.1.4&quot;, &quot;react-native-slider&quot;: &quot;^0.11.0&quot;, &quot;react-native-step-indicator&quot;: &quot;^1.0.3&quot;, &quot;react-native-tab-view&quot;: &quot;^2.16.0&quot;, &quot;react-native-text-input-mask&quot;: &quot;^3.1.4&quot;, &quot;react-native-vector-icons&quot;: &quot;^9.1.0&quot;, &quot;react-native-webview&quot;: &quot;^11.13.0&quot;, &quot;react-redux&quot;: &quot;^7.2.4&quot;, &quot;uuid&quot;: &quot;^8.3.2&quot; }, </code></pre> <p>It is not running now without doing anything with the previous working code, not even updating anything in the system also.</p> <p>Here is that error</p> <p>FAILURE: Build failed with an exception.</p> <ul> <li>What went wrong: Execution failed for task ':app:checkDebugAarMetadata'.</li> </ul> <blockquote> <p>Could not resolve all files for configuration ':app:debugRuntimeClasspath'. Failed to transform react-native-0.71.0-rc.0-debug.aar (com.facebook.react:react-native:0.71.0-rc.0) to match attributes {artifactType=android-aar-metadata, com.android.build.api.attributes.BuildTypeAttr=debug, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}. &gt; Execution failed for JetifyTransform: /Users/username/.gradle/caches/modules-2/files-2.1/com.facebook.react/react-native/0.71.0-rc.0/7a7f5a0af6ebd8eb94f7e5f7495e9d9684b4f543/react-native-0.71.0-rc.0-debug.aar. &gt; Java heap space</p> </blockquote> <ul> <li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p> </li> <li><p>Get more help at <a href="https://help.gradle.org" rel="noreferrer">https://help.gradle.org</a></p> </li> </ul> <p>BUILD FAILED in 4s</p> <p>error Failed to install the app. Make sure you have the Android development environment set up: <a href="https://reactnative.dev/docs/environment-setup" rel="noreferrer">https://reactnative.dev/docs/environment-setup</a>. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081</p> <p>FAILURE: Build failed with an exception.</p> <ul> <li>What went wrong: Execution failed for task ':app:checkDebugAarMetadata'.</li> </ul> <blockquote> <p>Could not resolve all files for configuration ':app:debugRuntimeClasspath'. Failed to transform react-native-0.71.0-rc.0-debug.aar (com.facebook.react:react-native:0.71.0-rc.0) to match attributes {artifactType=android-aar-metadata, com.android.build.api.attributes.BuildTypeAttr=debug, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}. &gt; Execution failed for JetifyTransform: /Users/username/.gradle/caches/modules-2/files-2.1/com.facebook.react/react-native/0.71.0-rc.0/7a7f5a0af6ebd8eb94f7e5f7495e9d9684b4f543/react-native-0.71.0-rc.0-debug.aar. &gt; Java heap space</p> </blockquote> <ul> <li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p> </li> <li><p>Get more help at <a href="https://help.gradle.org" rel="noreferrer">https://help.gradle.org</a></p> </li> </ul> <p>BUILD FAILED in 4s</p> <pre><code>at makeError (/Users/username/Desktop/Gitlab/projectname/node_modules/execa/index.js:174:9) at /Users/username/Desktop/Gitlab/projectname/node_modules/execa/index.js:278:16 at processTicksAndRejections (node:internal/process/task_queues:96:5) at async runOnAllDevices (/Users/username/Desktop/Gitlab/projectname/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5) at async Command.handleAction (/Users/username/Desktop/Gitlab/projectname/node_modules/@react-native-community/cli/build/index.js:192:9) </code></pre>
[ { "answer_id": 74326271, "author": "Guna", "author_id": 15208727, "author_profile": "https://Stackoverflow.com/users/15208727", "pm_score": 6, "selected": true, "text": "allprojects {\n repositories {\n exclusiveContent {\n // We get React Native's Android binaries exclusively through npm,\n // from a local Maven repo inside node_modules/react-native/.\n // (The use of exclusiveContent prevents looking elsewhere like Maven Central\n // and potentially getting a wrong version.)\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n // ...\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15208727/" ]
74,325,536
<p><a href="https://i.stack.imgur.com/KPEJz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPEJz.png" alt="vs code my code" /></a></p> <p>now i was doing a project. for fun with my friends wanted to do a circle where it rotates in the Z axis but i needed a gradient so did some research how to put a gradient on a border found this did it but my border radius went missing what do you guys recommend?</p>
[ { "answer_id": 74326271, "author": "Guna", "author_id": 15208727, "author_profile": "https://Stackoverflow.com/users/15208727", "pm_score": 6, "selected": true, "text": "allprojects {\n repositories {\n exclusiveContent {\n // We get React Native's Android binaries exclusively through npm,\n // from a local Maven repo inside node_modules/react-native/.\n // (The use of exclusiveContent prevents looking elsewhere like Maven Central\n // and potentially getting a wrong version.)\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n // ...\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19813493/" ]
74,325,558
<p>I have two tables Table products : product_id,name,barcode1,barcode2,barcode3 Table more_barcodes: product_id,barcode</p> <p>How to join those two tables when user search barcode ?</p> <pre><code>select products.* from products LEFT JOIN more_barcodes ON products.product_id=more_barcodes.product_id where ( (products.barcode1 LIKE '%$user_search%') OR (products.barcode2 LIKE '%$user_search%' ) OR (products.barcode3 LIKE '%$user_search%' ) OR (more_barcodes.barcode LIKE '%$user_search%' ) ) GROUP by products.products_id $sql_check=mysql_query($query); while ($row_check = mysql_fetch_array($sql_check)) { echo &quot;&lt;br&gt;&quot;.$row_check[name]; // show results from table products echo $row_check[barcode]; if ($row_check[barcode2]!=&quot;&quot;) { echo &quot;&lt;br&gt;&quot;.$row_check[barcode2]; } if ($row_check[barcode3]!=&quot;&quot;) { echo &quot;&lt;br&gt;&quot;.$row_check[barcode3]; } // show results from table more_barcodes // here is the problem /////////////////////////////////////////// if (barcode in table more_barcodes) { echo &quot;ALL BARCODES&quot;; } ////////////////////////////////////////////////////////////////// } </code></pre>
[ { "answer_id": 74326271, "author": "Guna", "author_id": 15208727, "author_profile": "https://Stackoverflow.com/users/15208727", "pm_score": 6, "selected": true, "text": "allprojects {\n repositories {\n exclusiveContent {\n // We get React Native's Android binaries exclusively through npm,\n // from a local Maven repo inside node_modules/react-native/.\n // (The use of exclusiveContent prevents looking elsewhere like Maven Central\n // and potentially getting a wrong version.)\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n // ...\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13957526/" ]
74,325,560
<p>I have tried to update category information and it's updated but not updated in the database. I am trying to <strong>return <strong>$category;</strong></strong> before <strong>$category-&gt;update();</strong> and see it's updated. But in the database not see updated data.</p> <p><a href="https://i.stack.imgur.com/6cY5b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6cY5b.png" alt="enter image description here" /></a></p> <p><strong>1.Web</strong></p> <pre><code>// Admin Dashboard Route </code></pre> <p>Route::prefix('admin')-&gt;middleware(['auth','isAdmin'])-&gt;group(function () {</p> <pre><code>Route::get('dashboard', [App\Http\Controllers\Admin\DashboardController::class, 'index']); // Category Route Route::controller(App\Http\Controllers\Admin\CategoryController::class)-&gt;group(function () { Route::get('/category', 'index'); Route::get('/category/create', 'create'); Route::post('/category', 'store'); Route::get('/category/view/{id}', 'view'); Route::get('/category/{category}/edit', 'edit'); Route::put('/category/{category}', 'update'); }); </code></pre> <p>});</p> <p><strong>2. Controller</strong></p> <pre><code>public function update(CategoryFormRequest $request, $category){ $category = Category::findOrFail($category); $validatedData = $request-&gt;validated(); $category = new Category; $category-&gt;name = $validatedData['name']; $category-&gt;slug = Str::slug($validatedData['slug']); $category-&gt;description = $validatedData['description']; if($request-&gt;hasFile('image')){ $path = 'uploads/category/' .$category-&gt;image; if(File::exists($path)){ File::delete($path); } $file = $request-&gt;file('image'); $ext = $file-&gt;getClientOriginalExtension(); $fileName = 'PC' .'-'. time() .'.'. $ext; $file-&gt;move('uploads/category/', $fileName); $category-&gt;image = $fileName; } $category-&gt;meta_title = $validatedData['meta_title']; $category-&gt;meta_keywords = $validatedData['meta_keywords']; $category-&gt;meta_description = $validatedData['meta_description']; $category-&gt;status = $request-&gt;status == true ? '0':'1'; $category-&gt;update(); return $category; return redirect('admin/category')-&gt;with('message','Category Updated Successfully'); } </code></pre> <p><strong>3. View</strong></p> <pre><code>@extends('layouts.admin') </code></pre> <p>@section('content')</p> <pre><code>&lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-12&quot;&gt; &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-header d-flex align-items-center justify-content-between&quot;&gt; &lt;h4 class=&quot;mb-0&quot;&gt;Edit Category&lt;/h4&gt; &lt;a href=&quot;{{ url('admin/category') }}&quot; class=&quot;btn btn-primary btn-sm float-end text-light&quot;&gt;View Category&lt;/a&gt; &lt;/div&gt; &lt;form action=&quot;{{ url('admin/category/'.$category-&gt;id) }}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt; @method('PUT') @csrf &lt;div class=&quot;card-body&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-12 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Status&lt;/label&gt; &lt;input type=&quot;checkbox&quot; name=&quot;status&quot; {{ $category-&gt;status == 0 ? 'Checked':'' }}&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;name&quot; id=&quot;&quot; value=&quot;{{ $category-&gt;name }}&quot; placeholder=&quot;Enter category name&quot;&gt; @error('name') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-6 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Slug&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;slug&quot; id=&quot;&quot; value=&quot;{{ $category-&gt;slug }}&quot; placeholder=&quot;Enter category slug&quot;&gt; @error('slug') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-6 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Image&lt;/label&gt; &lt;input type=&quot;file&quot; class=&quot;form-control&quot; name=&quot;image&quot; id=&quot;&quot;&gt; &lt;img src=&quot;{{ asset('uploads/category/' .$category-&gt;image) }}&quot; width=&quot;60&quot; height=&quot;60&quot; class=&quot;img-fluid rounded-top&quot; alt=&quot;&quot;&gt; @error('image') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-6 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Description&lt;/label&gt; &lt;textarea class=&quot;form-control&quot; name=&quot;description&quot; id=&quot;&quot; rows=&quot;5&quot; placeholder=&quot;Enter Description&quot;&gt;{{ $category-&gt;description }}&lt;/textarea&gt; @error('description') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-12 mb-3&quot;&gt; &lt;h4&gt;SEO Tags&lt;/h4&gt; &lt;/div&gt; &lt;div class=&quot;col-md-12 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Meta Title&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;meta_title&quot; value=&quot;{{ $category-&gt;meta_title }}&quot; id=&quot;&quot; placeholder=&quot;Enter meta title&quot;&gt; @error('meta_title') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-12 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Meta Keywords&lt;/label&gt; &lt;textarea class=&quot;form-control&quot; name=&quot;meta_keywords&quot; id=&quot;&quot; rows=&quot;3&quot; placeholder=&quot;Enter Meta keywords&quot;&gt;{{ $category-&gt;meta_keywords }}&lt;/textarea&gt; @error('meta_keywords') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;div class=&quot;col-md-12 mb-3&quot;&gt; &lt;label for=&quot;&quot; class=&quot;form-label&quot;&gt;Meta Description&lt;/label&gt; &lt;textarea class=&quot;form-control&quot; name=&quot;meta_description&quot; id=&quot;&quot; rows=&quot;3&quot; placeholder=&quot;Enter Meta Description&quot;&gt;{{ $category-&gt;meta_description }}&lt;/textarea&gt; @error('meta_description') &lt;small class=&quot;text-danger&quot;&gt;{{ $message }}&lt;/small&gt; @enderror &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;card-footer&quot;&gt; &lt;div class=&quot;col-12 text-center&quot;&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary text-light&quot;&gt;Update Category&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>@endsection</p>
[ { "answer_id": 74326271, "author": "Guna", "author_id": 15208727, "author_profile": "https://Stackoverflow.com/users/15208727", "pm_score": 6, "selected": true, "text": "allprojects {\n repositories {\n exclusiveContent {\n // We get React Native's Android binaries exclusively through npm,\n // from a local Maven repo inside node_modules/react-native/.\n // (The use of exclusiveContent prevents looking elsewhere like Maven Central\n // and potentially getting a wrong version.)\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n // ...\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14154959/" ]
74,325,565
<p>This maybe a simple question but I couldn't figure it out myself nor could I find an online resource for it.</p> <p>I have to develop a REST API using spring boot. I see two options to accept the json payload (max payload size 3 MB in some cases)</p> <p><strong>Option 1: Ask clients to send json in request body. Let Jackson convert it to Java object</strong></p> <pre><code>@RestController public class EmployeeController { @PostMapping public void createEmployees(@RequestBody List&lt;Employee&gt; employees) { // do something with employees } } </code></pre> <p><strong>Option 2: Ask clients to upload a json file and let the controller accept Multipart payload</strong></p> <pre><code>@RestController public class EmployeeController { @PostMapping(consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) public void createEmployees(@RequestParam(name = &quot;file&quot;) MultipartFile file) { // convert multipart file data to List of Employee objects //do something with employees } } </code></pre> <p>Which option is better and why?</p>
[ { "answer_id": 74326271, "author": "Guna", "author_id": 15208727, "author_profile": "https://Stackoverflow.com/users/15208727", "pm_score": 6, "selected": true, "text": "allprojects {\n repositories {\n exclusiveContent {\n // We get React Native's Android binaries exclusively through npm,\n // from a local Maven repo inside node_modules/react-native/.\n // (The use of exclusiveContent prevents looking elsewhere like Maven Central\n // and potentially getting a wrong version.)\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n // ...\n }\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534054/" ]
74,325,609
<p>When the user completes the registration process, I want to redirect her to the login page, where I get the following error.</p> <p>Unsafe redirect to URL with protocol 'accounts'</p> <p>What method should I use to solve this error?</p> <pre><code>class RegisterUser(APIView): serializer_class = RegisterSerializer def post(self, request): serializer = self.serializer_class(data=request.POST) serializer.is_valid(raise_exception=True) serializer.save() return HttpResponseRedirect('accounts:login') </code></pre>
[ { "answer_id": 74325655, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 3, "selected": true, "text": "return HttpResponseRedirect('accounts:login')\n" }, { "answer_id": 74325844, "author": "Sunderam Dubey", "author_id": 17562044, "author_profile": "https://Stackoverflow.com/users/17562044", "pm_score": 1, "selected": false, "text": "return redirect('accounts:login')\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14751614/" ]
74,325,613
<p>What would be considered best practice for implementing a persistent shopping cart in an ASP.net Web Forms(*) based application? The only built-in way seems to be involving the Session state, which is not ideal because once you close the browser... it's gone. One way seems to be involving the localStorage via Javascript, but that creates awkward client/server mixups, as the data processing is meant to be done server side.</p> <p>(* please pay attention to that part - MVC or Blazor based solutions will not work for this particular case)</p>
[ { "answer_id": 74325655, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 3, "selected": true, "text": "return HttpResponseRedirect('accounts:login')\n" }, { "answer_id": 74325844, "author": "Sunderam Dubey", "author_id": 17562044, "author_profile": "https://Stackoverflow.com/users/17562044", "pm_score": 1, "selected": false, "text": "return redirect('accounts:login')\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6751492/" ]
74,325,624
<p>Not sure if there is a more elegant way to do what I want to do. Basically, I need to determine the current row's &quot;position&quot; value based on the &quot;factor&quot; value and the previous row's &quot;position&quot; value.</p> <p>I tried to loop through the DataFrame and use some if else statements to update the value, but it is very clumpy and the values didn't get updated.</p> <p>Please kindly help, million thanks!</p> <pre><code> factor position time 2022-05-13 06:00:00 0.489471 0 2022-05-13 07:00:00 0.711030 0 2022-05-13 08:00:00 0.566865 0 2022-05-13 09:00:00 0.489471 0 2022-05-13 10:00:00 0.288419 0 </code></pre> <pre><code>import pandas as pd df = pd.DataFrame({'time': ['2022-05-13 06:00:00', '2022-05-13 07:00:00', '2022-05-13 08:00:00','2022-05-13 09:00:00', '2022-05-13 10:00:00'], 'factor': [0.489471, 0.711030, 0.566865, 0.489471, 0.288419], 'position': [0, 0, 0, 0, 0]}) df['time'] = pd.to_datetime(df['time']) df.set_index('time', inplace=True) threshold_2 = 0.7 threshold_1 = 0.35 for i in range(0, len(df)): # no position if i == 0 or df.iloc[i-1, :]['position'] == 0: if df.iloc[i, :]['factor'] &gt; threshold_2: df.iloc[i, :]['position'] = 1 else: df.iloc[i, :]['position'] = 0 #has position elif df.iloc[i-1, :]['position'] != 0: if df.iloc[i, :]['factor'] &gt; threshold_1: df.iloc[i, :]['position'] = 1 else: df.iloc[i, :]['position'] = 0 </code></pre>
[ { "answer_id": 74325850, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 1, "selected": false, "text": "1 if foo else 0" }, { "answer_id": 74325858, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "threshold_2 = 0.7\nthreshold_1 = 0.35\n\nm1 = df['factor'].gt(threshold_2)\n\ngroup = m1.cumsum()\n\nm2 = df.loc[group>0, 'factor'].gt(threshold_1).groupby(group).cummin()\n\ndf['position'] = (m1|df.index.isin(m2[m2].index)).astype(int)\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15189383/" ]
74,325,669
<p>I'm trying to create a POST call using HttpClient that I have fully working in Postman. Here is the body I'm sending in Postman:</p> <pre><code>{ &quot;searchType&quot;: &quot;games&quot;, &quot;searchTerms&quot;: [ &quot;mario&quot; ], &quot;searchPage&quot;: 1, &quot;size&quot;: 20, &quot;searchOptions&quot;: { &quot;games&quot;: { &quot;userId&quot;: 0, &quot;platform&quot;: &quot;&quot;, &quot;sortCategory&quot;: &quot;popular&quot;, &quot;rangeCategory&quot;: &quot;main&quot;, &quot;rangeTime&quot;: { &quot;min&quot;: 0, &quot;max&quot;: 0 }, &quot;gameplay&quot;: { &quot;perspective&quot;: &quot;&quot;, &quot;flow&quot;: &quot;&quot;, &quot;genre&quot;: &quot;&quot; }, &quot;modifier&quot;: &quot;&quot; }, &quot;users&quot;: { &quot;sortCategory&quot;: &quot;postcount&quot; }, &quot;filter&quot;: &quot;&quot;, &quot;sort&quot;: 0, &quot;randomizer&quot;: 0 } } </code></pre> <p>I have this written as the following in C#:</p> <pre><code>var client = _httpClientFactory.CreateClient(HttpClients.HowLongToBeat.ToString()); var request = new HowLongToBeatRequest { SearchType = &quot;games&quot;, SearchTerms = searchTerm.Trim().Split(&quot; &quot;), SearchPage = 1, Size = 20, SearchOptions = new SearchOptions { Games = new SearchOptionsGames { UserId = 0, Platform = &quot;&quot;, SortCategory = &quot;popular&quot;, RangeCategory = &quot;main&quot;, RangeTime = new SearchOptionsGamesRangeTime { Min = 0, Max = 0 }, Gameplay = new SearchOptionsGamesGameplay { Perspective = &quot;&quot;, Flow = &quot;&quot;, Genre = &quot;&quot; }, Modifier = &quot;&quot; }, Users = new SearchOptionsUsers { SortCategory = &quot;postcount&quot; }, Filter = &quot;&quot;, Sort = 0, Randomizer = 0 } }; //var json = JsonSerializer.Serialize(request); //var content = new StringContent(json, Encoding.UTF8, &quot;application/json&quot;); //var response = await client.PostAsync(&quot;api/search&quot;, content); var response = await client.PostAsJsonAsync(&quot;api/search&quot;, request, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return new HowLongToBeatResponse(); </code></pre> <p>I have this set up as</p> <p>The url I'm hitting is: <code>https://www.howlongtobeat.com/api/search</code> and I'm setting it up like so in my Startup.cs</p> <pre><code>services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =&gt; { config.BaseAddress = new Uri(&quot;https://www.howlongtobeat.com/&quot;); config.DefaultRequestHeaders.Add(&quot;Referer&quot;, &quot;https://www.howlongtobeat.com/&quot;); }); </code></pre> <p>I am passing this Referer header in my Postman collection as well.</p> <p>Basically, I can't figure out why this code gets a 403 in C# but the Postman that I think is exactly the same is getting a successful response. Am I missing something?</p> <p>Let me know if there's any missing info I can provide.</p>
[ { "answer_id": 74325850, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 1, "selected": false, "text": "1 if foo else 0" }, { "answer_id": 74325858, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "threshold_2 = 0.7\nthreshold_1 = 0.35\n\nm1 = df['factor'].gt(threshold_2)\n\ngroup = m1.cumsum()\n\nm2 = df.loc[group>0, 'factor'].gt(threshold_1).groupby(group).cummin()\n\ndf['position'] = (m1|df.index.isin(m2[m2].index)).astype(int)\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/386869/" ]
74,325,676
<p>I want to the update the object of id 21, make reply to false.</p> <pre><code>const arr = [ {id: 1, comment:'parent 01', parentId:null, reply:true, children:[{id: 11, comment:'child', reply:true, parentId:1, children:[{id: 21, comment:'super child ', reply:true,parentId:11 }] }] }, {id: 2, comment:'parent 02', reply:true, parentId:null } ] </code></pre> <p>result should be:</p> <pre><code>const arr = [ {id: 1, comment:'parent 01', parentId:null, reply:true, children:[{id: 11, comment:'child', reply:true, parentId:1, children:[{id: 21, comment:'super child ', reply:false,parentId:11 }] }] }, {id: 2, comment:'parent 02', reply:true, parentId:null } ] </code></pre> <pre><code>[ {id: 1, comment:'parent 01', reply:true,parentId:null}, {id: 11, comment:'child', reply:true, parentId:1}, {id: 21, comment:'super child', reply:true, parentId:11}, {id: 2, comment:'parent 02', reply:true, parentId:null}, ] </code></pre> <p>function to make this nested array:</p> <pre><code>function nestComments(commentList) { const commentMap = {}; // move all the comments into a map of id =&gt; comment commentList.forEach(comment =&gt; commentMap[comment.id] = comment); // iterate over the comments again and correctly nest the children commentList.forEach(comment =&gt; { if(comment.parentId !== null) { const parent = commentMap[comment.parentId]; (parent.children = parent.children || []).push(comment); } }); // filter the list to return a list of correctly nested comments return commentList.filter(comment =&gt; { return comment.parentId === null; }); } </code></pre>
[ { "answer_id": 74325755, "author": "Pankti Shah", "author_id": 12364626, "author_profile": "https://Stackoverflow.com/users/12364626", "pm_score": 2, "selected": false, "text": " function changeData(arr,id){\n arr.forEach((ar)=>{\n if(ar.id==id){\n ar.reply=false;\n }\n if(ar && ar.children && ar.children.length>0){\n changeData(ar.children,id);\n }\n })\n return arr;\n }\n" }, { "answer_id": 74325954, "author": "Dmitriy Zhiganov", "author_id": 13730174, "author_profile": "https://Stackoverflow.com/users/13730174", "pm_score": 1, "selected": false, "text": "const update = (arr, id, key, value) => {\n let i = 0;\n let stack = [arr[i]];\n\n while (stack.length && stack[0]) {\n let current = stack.pop();\n\n if (current.id === id) {\n current[key] = value;\n break;\n } else {\n if (current.children && current.children.length) {\n stack = [...stack, ...current.children];\n } else {\n stack.push(arr[i++]);\n }\n }\n }\n};\n\nupdate(arr, 21, \"reply\", \"NEW VALUE\");\n\n" }, { "answer_id": 74326067, "author": "Weam Adel", "author_id": 14749084, "author_profile": "https://Stackoverflow.com/users/14749084", "pm_score": 1, "selected": false, "text": "/**\n * @description Recursively finds and updates reply state of the passed comment id.\n * @typedef {{\n * id: number,\n * parentId: number | null,\n * reply: boolen,\n * comment: string,\n * children?: Comment[]\n * }} Comment\n * @param {Comment[] | undefined} comments\n * @param {number} id\n * @param {boolean} state\n * @return {Comment | undefined}\n */\n function updateCommentReplyState(comments, id, state) {\n if (!comments) {\n return;\n }\n\n for (let comment of comments) {\n if (comment.id === id) {\n // We've found the id, then update its reply state then\n // return the comment, and do not search the children.\n comment.reply = state;\n return comment;\n }\n\n // Recursively search each child\n return updateCommentReplyState(comment.children, id, state);\n }\n }\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7482821/" ]
74,325,685
<p>It will take two keys as input key1 and key2 and finds the node with key1, then changes it to key2. This may disturb the BST property (of having smaller things to the left and bigger to the right); this function should make appropriate changes in tree so that it becomes BST again.</p> <p>I tried making links of the new data with links of the older node to be replaced with ,but I can organize my tree precisely.</p>
[ { "answer_id": 74325755, "author": "Pankti Shah", "author_id": 12364626, "author_profile": "https://Stackoverflow.com/users/12364626", "pm_score": 2, "selected": false, "text": " function changeData(arr,id){\n arr.forEach((ar)=>{\n if(ar.id==id){\n ar.reply=false;\n }\n if(ar && ar.children && ar.children.length>0){\n changeData(ar.children,id);\n }\n })\n return arr;\n }\n" }, { "answer_id": 74325954, "author": "Dmitriy Zhiganov", "author_id": 13730174, "author_profile": "https://Stackoverflow.com/users/13730174", "pm_score": 1, "selected": false, "text": "const update = (arr, id, key, value) => {\n let i = 0;\n let stack = [arr[i]];\n\n while (stack.length && stack[0]) {\n let current = stack.pop();\n\n if (current.id === id) {\n current[key] = value;\n break;\n } else {\n if (current.children && current.children.length) {\n stack = [...stack, ...current.children];\n } else {\n stack.push(arr[i++]);\n }\n }\n }\n};\n\nupdate(arr, 21, \"reply\", \"NEW VALUE\");\n\n" }, { "answer_id": 74326067, "author": "Weam Adel", "author_id": 14749084, "author_profile": "https://Stackoverflow.com/users/14749084", "pm_score": 1, "selected": false, "text": "/**\n * @description Recursively finds and updates reply state of the passed comment id.\n * @typedef {{\n * id: number,\n * parentId: number | null,\n * reply: boolen,\n * comment: string,\n * children?: Comment[]\n * }} Comment\n * @param {Comment[] | undefined} comments\n * @param {number} id\n * @param {boolean} state\n * @return {Comment | undefined}\n */\n function updateCommentReplyState(comments, id, state) {\n if (!comments) {\n return;\n }\n\n for (let comment of comments) {\n if (comment.id === id) {\n // We've found the id, then update its reply state then\n // return the comment, and do not search the children.\n comment.reply = state;\n return comment;\n }\n\n // Recursively search each child\n return updateCommentReplyState(comment.children, id, state);\n }\n }\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19856463/" ]
74,325,702
<p>Let's say I have a a <code>vector&lt;vector&lt;int&gt;&gt;</code>. I want to use <code>ranges::transform</code> in such a way that I get</p> <pre class="lang-cpp prettyprint-override"><code>vector&lt;vector&lt;int&gt;&gt; original_vectors; using T = decltype(ranges::views::transform(original_vectors[0], [&amp;](int x){ return x; })); vector&lt;int&gt; transformation_coeff; vector&lt;T&gt; transformed_vectors; for(int i=0;i&lt;n;i++){ transformed_vectors.push_back(ranges::views::transform(original_vectors[i], [&amp;](int x){ return x * transformation_coeff[i]; })); } </code></pre> <p>Is such a transformation, or something similar, currently possible in C++?</p> <p>I know its possible to simply store the <code>transformation_coeff</code>, but it's inconvenient to apply it at every step. (This will be repeated multiple times so it needs to be done in <code>O(log n)</code>, therefore I can't explicitly apply the transformation).</p>
[ { "answer_id": 74325842, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 3, "selected": false, "text": "T" }, { "answer_id": 74331910, "author": "joergbrech", "author_id": 12173376, "author_profile": "https://Stackoverflow.com/users/12173376", "pm_score": 2, "selected": true, "text": "std::vector" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790812/" ]
74,325,748
<p>In my code, I am showing an image to the user by changing the src to</p> <pre><code> </code></pre> <pre><code> $(&quot;#&quot; + img_tag_id).attr('src', image.toDataURL()); </code></pre> <pre><code> </code></pre> <p>how can I take the value of this file to input tag below:</p> <p>HTML code:</p> <pre><code> &lt;input type=&quot;file&quot; name=&quot;uploadNewImage&quot;&gt; </code></pre> <p>I am using finecrop plugin</p>
[ { "answer_id": 74325842, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 3, "selected": false, "text": "T" }, { "answer_id": 74331910, "author": "joergbrech", "author_id": 12173376, "author_profile": "https://Stackoverflow.com/users/12173376", "pm_score": 2, "selected": true, "text": "std::vector" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20173402/" ]
74,325,767
<p>I am trying to build an ASP.NET Core hosted Blazor web app. I have two entities with a one-to-many relationship.</p> <p>There is one portfolio that has many securities.</p> <p>Portfolio entity</p> <pre><code>public class Portfolio { [Key] public int PortfolioId { get; set; } [Required] public string NameOfPortfolio { get; set; } public string Description { get; set; } = string.Empty; public DateTime DateTimeCreated { get; set; } = DateTime.UtcNow; public virtual ICollection&lt;Security&gt;? Securities { get; set; } } </code></pre> <p>Security entity</p> <pre><code>public class Security { [Key] public int Id { get; set; } [Required] public string SecurityName { get; set; } = string.Empty; [Required] public float Price { get; set; } [Required] public int StockesOwned { get; set; } = 0; [Required] public float StocksValue { get; set; } public DateTime DateTimeObtained { get; set; } = DateTime.UtcNow; public string? Description { get; set; } = string.Empty; public Portfolio Portfolio { get; set; } } </code></pre> <p>The <code>Security</code> must have a <code>Portfolio</code>, but a portfolio may not have a security.</p> <p>I am trying whenever I want to add a security I must specify the portfolio that contains that security. I am trying to bind the <code>security.Portfolio</code> to a <code>Portfolio</code> and I can not implement it correctly.</p> <p>Whenever I try to bind it that way</p> <pre><code>&lt;div class=&quot;row w-100&quot;&gt; &lt;div class=&quot;col-6&quot;&gt; Portfolio &lt;/div&gt; &lt;div class=&quot;col-md-4&quot;&gt; &lt;select class=&quot;form-control&quot; &gt; &lt;option value=&quot;&quot; bind=@Security.Portfolio&gt;Select Portfolio&lt;/option&gt; @foreach (var portfolio in Portfolios) { &lt;option value=&quot;@portfolio.PortfolioId&quot;&gt;@portfolio.NameOfPortfolio&lt;/option&gt; } &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>It returns an error 400 and it mentions that the portfolio is required</p> <p>Also here is the service in the client</p> <pre><code>public async Task CreateSecurity(Security security) { var response = await _http.PostAsJsonAsync(&quot;api/security&quot;, security); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadFromJsonAsync&lt;ServiceResponse&lt;int&gt;&gt;(); if (!(result?.Success ?? false)) { } } } </code></pre> <p>The controller</p> <pre><code>[HttpPost] public async Task&lt;ActionResult&lt;ServiceResponse&lt;int&gt;&gt;&gt; CreateSecurity(Security security) { var result = await _securityService.CreateSecurityAsync(security); return Ok(result); } </code></pre> <p>The service in the server</p> <pre><code>public async Task&lt;ServiceResponse&lt;int&gt;&gt; CreateSecurityAsync(Security security) { _context.Securities.Add(security); int result = await _context.SaveChangesAsync(); return new ServiceResponse&lt;int&gt; { Data = result, Success = result &gt; 0, Message = &quot;The&quot; + security.SecurityName + &quot;has been saved!&quot; }; } </code></pre> <p>Sorry if I misspelled something or did something wrong. I am new to this. Thanks in advance.</p>
[ { "answer_id": 74338347, "author": "Marius", "author_id": 2286743, "author_profile": "https://Stackoverflow.com/users/2286743", "pm_score": 2, "selected": false, "text": "option" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15066198/" ]
74,325,777
<p>Hi there I am trying to find out if any key value is true of an object.</p> <p>The following works only for objects without having nested objects.</p> <p>I am trying to check if any key in the objects no matter parent or child has got true value</p> <pre><code>const odb = { &quot;all&quot;: true, &quot;allA&quot;: false, &quot;allB&quot;: false, &quot;allC&quot;: { &quot;allD&quot;: false, &quot;allE&quot;: false, } } const isAnyKeyValueTrue = o =&gt; !Object.keys(o).find(k =&gt; !o[k]); console.log(isAnyKeyValueTrue(odb)); </code></pre>
[ { "answer_id": 74325830, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 4, "selected": true, "text": "isAnyKeyValueTrue" }, { "answer_id": 74325868, "author": "Ibrahim Hammed", "author_id": 9077347, "author_profile": "https://Stackoverflow.com/users/9077347", "pm_score": 0, "selected": false, "text": "const odb = {\n \"all\": false,\n \"allA\": false,\n \"allB\": false,\n \"allC\": {\n \"allD\": false,\n \"allE\": { \"allF\": true },\n }\n}\n\nconst isTrue = (obj) => {\n let result = false;\n for (let key in obj) {\n if (obj[key] === true) {\n result = true;\n break;\n } else if (typeof obj[key] === 'object') {\n result = isTrue(obj[key]);\n }\n }\n return result;\n}\n console.log(isTrue(odb));\n" }, { "answer_id": 74325876, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "||" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20319015/" ]
74,325,781
<p>When I use</p> <pre><code> LaunchedEffect(Dispatchers.IO) </code></pre> <p>I get,</p> <blockquote> <p>NetworkOnMainThreadException</p> </blockquote> <p>How should I use this function to run on background thread?</p> <p>this is my code:</p> <pre><code>LaunchedEffect(Dispatchers.IO) { val input = URL(&quot;https://rezaapp.downloadseriesmovie.ir/maintxt.php&quot;).readText() println(input) } </code></pre> <p>I'm using it inside my jetpack compose project</p>
[ { "answer_id": 74326747, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 2, "selected": false, "text": "LaunchedEffect" }, { "answer_id": 74628439, "author": "rahat", "author_id": 9701793, "author_profile": "https://Stackoverflow.com/users/9701793", "pm_score": 0, "selected": false, "text": "lifecyclescope" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18775967/" ]
74,325,797
<p>Hi I am trying to taking input in this fashion:</p> <pre><code>itemPrices: [{regionId: &quot;A&quot;, price: &quot;200&quot;},{regionId: &quot;B&quot;, price: &quot;100&quot;}] </code></pre> <p>As the user presses add button new input fields get added. <br> For this I have taken an empty array=&gt; <code>itemPrices: [],</code> inside vue app data. <br>Now Inside table element I have this code:<br></p> <pre><code>&lt;vs-tr v-for=&quot;n in num&quot; v-bind:key=&quot;n&quot;&gt; &lt;vs-td &gt;&lt;vs-input v-model=&quot;itemPrices[n].regionId&quot; placeholder=&quot;Region Name&quot; /&gt;&lt;/vs-td&gt; &lt;vs-td&gt; &lt;vs-input placeholder=&quot;price&quot; v-model=&quot;itemPrices[n].price&quot; /&gt; &lt;/vs-td&gt; &lt;/vs-tr&gt; </code></pre> <p>Here 'num' is just an integer which decides how many rows should be there. But this is not working... What is a possible solution for this task?</p>
[ { "answer_id": 74325892, "author": "Timon Hueting", "author_id": 18505615, "author_profile": "https://Stackoverflow.com/users/18505615", "pm_score": 0, "selected": false, "text": "<vs-tr v-for=\"n in num\" v-bind:key=\"n\">\n <vs-td\n ><vs-input\n v-model=\"n.regionId\"\n placeholder=\"Region Name\"\n /></vs-td>\n <vs-td>\n <vs-input\n placeholder=\"price\"\n v-model=\"n.price\"\n />\n </vs-td>\n </vs-tr>\n" }, { "answer_id": 74326628, "author": "Nikola Pavicevic", "author_id": 11989189, "author_profile": "https://Stackoverflow.com/users/11989189", "pm_score": 2, "selected": true, "text": "num" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11821885/" ]
74,325,837
<p>I have a vectorimageSlices and a 3D :</p> <pre><code>cv::Mat RTstruct3D(3,DImensions3D, CV_8U, Scalar(0)) </code></pre> <p>I want to put my vector into the specific index of 3D cv::Mat.</p> <pre><code> //Make a 3D Organ int programCounter = 0; vector&lt;Mat&gt;imageSlices; for (size_t k = 0; k &lt; Npoint_Z.size(); k++) { Mat finalSliceImage = Mat :: zeros(DImensions3D[0], DImensions3D[1],CV_8U); vector&lt;vector&lt;int&gt;&gt; polies; for (size_t h = 0; h &lt; Npoint_Z[k][0]; h++) { vector&lt;int&gt;x_y; x_y.push_back(ContourData[programCounter][0]); //x x_y.push_back(ContourData[programCounter][1]); //y polies.push_back(x_y); programCounter++; } fillPoly(finalSliceImage, polies, Scalar(0, 255, 0)); imageSlices.push_back(finalSliceImage); } //Add Organ to RTSTRUCT 3D Mat RTstruct3D(3,DImensions3D, CV_8U, Scalar(0)); </code></pre> <p>Something like this image: <a href="https://i.stack.imgur.com/rWqfK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rWqfK.png" alt="enter image description here" /></a></p> <p>Please help me! Thanks.</p>
[ { "answer_id": 74325892, "author": "Timon Hueting", "author_id": 18505615, "author_profile": "https://Stackoverflow.com/users/18505615", "pm_score": 0, "selected": false, "text": "<vs-tr v-for=\"n in num\" v-bind:key=\"n\">\n <vs-td\n ><vs-input\n v-model=\"n.regionId\"\n placeholder=\"Region Name\"\n /></vs-td>\n <vs-td>\n <vs-input\n placeholder=\"price\"\n v-model=\"n.price\"\n />\n </vs-td>\n </vs-tr>\n" }, { "answer_id": 74326628, "author": "Nikola Pavicevic", "author_id": 11989189, "author_profile": "https://Stackoverflow.com/users/11989189", "pm_score": 2, "selected": true, "text": "num" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19190785/" ]
74,325,912
<p>I have a list of Mono to run, but for memory consumption concern I'd like them to run one after another:</p> <pre class="lang-java prettyprint-override"><code>var monos = [m1, m2, m3]; Mono.zip(monos, (results) -&gt; { // handle result }); </code></pre> <p>The code above would execute m1 m2 m3 in parallel, how to control them in sequence and collect results?</p>
[ { "answer_id": 74326222, "author": "PeiSong", "author_id": 8310382, "author_profile": "https://Stackoverflow.com/users/8310382", "pm_score": 0, "selected": false, "text": "Flux([1, 2, 3]).concatMap(...)" }, { "answer_id": 74326390, "author": "Patrick Hooijer", "author_id": 10468291, "author_profile": "https://Stackoverflow.com/users/10468291", "pm_score": 1, "selected": false, "text": "Flux.concatMap" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8310382/" ]
74,325,916
<p>I do get a warning whenever I throw an exception in my code without explicitly stating it in the docblocs: <a href="https://i.stack.imgur.com/I4Kse.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I4Kse.png" alt="enter image description here" /></a></p> <p>I know this can be fixed by adding <code>@throw</code> tags, but the warning is actually not 100% true, as I do handle the exception in <code>/app/Exceptions/Handler.php</code>. I would like to disable the warning for this single exception. Is this possible in PHPStan? I have not found anything in the docs, but in this blog post <a href="https://phpstan.org/blog/bring-your-exceptions-under-control" rel="nofollow noreferrer">https://phpstan.org/blog/bring-your-exceptions-under-control</a> it seems that one can have unchecked &amp; checked exceptions, and I believe unchecked exceptions do not need to be declared. However, marking my exception unchecked in <code>phpstan.neon</code> does not get rid of the error:</p> <pre><code> exceptions: uncheckedExceptionClasses: - 'app\Exceptions\AuthenticationException' </code></pre> <p>I also noticed that the <code>Symfony\Component\HttpKernel\Exception\NotFoundHttpException</code> exception does not trigger the warning. I am not sure why, but it seems there is already a set of exceptions where no <code>@throw</code> is needed.</p> <p><a href="https://i.stack.imgur.com/xDJI5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDJI5.png" alt="enter image description here" /></a></p> <p>How can I suppress the warning for my exception?</p>
[ { "answer_id": 74326222, "author": "PeiSong", "author_id": 8310382, "author_profile": "https://Stackoverflow.com/users/8310382", "pm_score": 0, "selected": false, "text": "Flux([1, 2, 3]).concatMap(...)" }, { "answer_id": 74326390, "author": "Patrick Hooijer", "author_id": 10468291, "author_profile": "https://Stackoverflow.com/users/10468291", "pm_score": 1, "selected": false, "text": "Flux.concatMap" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2311074/" ]
74,325,929
<p>When I try to specify the parameter names when calling a function from inside a JavaScript class constructor, I get a <code>ReferenceError</code>.</p> <p>I will show the problem based on a simplified example:</p> <p>Suppose I have an object and methods like so:</p> <pre><code>class Person { constructor(name, age) { this.name = name, this.age = age } addYear() { this.age++; } changeName(newName) { this.name = newName; } changeAge(newAge) { this.age = newAge; } changeAgeAndName(newName, newAge) { this.changeName(newName=newName); this.changeAge(newAge=newAge); } } </code></pre> <p>All works fine if I instanciate it, and if mingle with it a bit this is the code and output:</p> <pre><code>let p1 = new Person('George', 20); console.log(p1); p1.changeName(newName='Robert'); console.log(p1); p1.changeAgeAndName(newName='Joe', newAge=23); console.log(p1); </code></pre> <pre><code>Person { name: 'George', age: 20 } Person { name: 'Robert', age: 20 } Person { name: 'Joe', age: 23 } </code></pre> <p>Now, let's say I want to use changeAgeAndName inside the constructor like so (specifying the parameter names for the variables):</p> <pre><code> constructor(name, age) { this.changeAgeAndName(newName=name, newAge=age); } </code></pre> <p>I get an error:</p> <pre><code>this.changeAgeAndName(newName=name, newAge=age); </code></pre> <pre><code>ReferenceError: newName is not defined </code></pre> <p>But if I don't specify the parameter names, all is fine:</p> <pre><code> constructor(name, age) { this.changeAgeAndName(name, age); } </code></pre> <p>Eventual Output:</p> <pre><code>Person2 { name: 'Mike', age: 40 } </code></pre> <p>If I specify the parameter names outside the constructor, all is fine as well. I like to be as explicit as possible when coding, so I was wondering what I may be doing wrong. Also, I was curious about perhaps yet another example of peculiar JS behavior. Thank you!</p>
[ { "answer_id": 74325953, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "p1.changeAgeAndName(newName='Joe', newAge=23);\n" }, { "answer_id": 74325998, "author": "Dat co", "author_id": 19609335, "author_profile": "https://Stackoverflow.com/users/19609335", "pm_score": -1, "selected": false, "text": "p1.changeAgeAndName(newName,newAge)\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11814273/" ]
74,325,938
<p>My script to find where a value in Array <code>$c[]</code> is in Array <code>$a[]</code> works, but nested <code>If</code> statements are too long. Can this be shortened using a <code>For</code> statement using a variable for array <code>$c[]</code> with the following rules?</p> <pre><code>#include &lt;Array.au3&gt; #include &lt;MsgBoxConstants.au3&gt; Local $a[]=[33,5,3,4,4,'a4',2,22,66,234,'a4',234,31,34,55,'a4',22,44,55,66] Local $c[]=['a4',22,44,55,66] For $b=0 To 19 If $c[0] == $a[$b] Then If $c[1] == $a[$b+1] Then If $c[2] == $a[$b+2] Then $k=$b EndIf EndIf EndIf Next </code></pre> <pre><code>#include &lt;Array.au3&gt; #include &lt;MsgBoxConstants.au3&gt; Local $a[]=[33,5,3,4,4,'a4',2,22,66,234,'a4',234,31,34,55,'a4',22,44,55,66] Local $c[]=['a4',22,44,55,66] Local $k[] $e=0 For $b=0 To 19 If $c[$e] == $a[$b] Then $k[$e]=$b $e+=1 EndIf Next _ArrayDisplay($k,&quot;dispay&quot;) MsgBox($MB_SYSTEMMODAL, &quot;&quot;, $k &amp;&quot;th value&quot; ) </code></pre> <p>I tried <em>one</em> nested <code>If</code> statement using the <code>For</code> statement, but it doesn't work.</p>
[ { "answer_id": 74325953, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "p1.changeAgeAndName(newName='Joe', newAge=23);\n" }, { "answer_id": 74325998, "author": "Dat co", "author_id": 19609335, "author_profile": "https://Stackoverflow.com/users/19609335", "pm_score": -1, "selected": false, "text": "p1.changeAgeAndName(newName,newAge)\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6275426/" ]
74,325,947
<p>Hi StackOverFlow community, that's my first question here and I'm glad to be part of this community as it already helped me in plenty of things. I looked on this topic and didn't manage to find anything. I would like to redirect the DefaultTabController to the new tab created after waiting that it's loaded and built. I managed to find a workaround with the awaiting a Future.delayed wrapping setState but I don't think it's the best solution out there. When not using this FutureDelayed I get an error due to the fact that the button function is trying to redirect to a tab not yet crated as the DefaultTabController has not been yet rebuilt.</p> <p>Function for adding a new tab inside a bottomSheet</p> <pre><code>Future&lt;int&gt; _addNewTab() async { await showModalBottomSheet( ... ... IconButton( onPressed: () { final isValid = _formKey.currentState!.validate(); if (!isValid) { return; } Navigator.pop(context); setState(() { _tabs .add(_newTab.text); }); } return _tabs.lenght-1; </code></pre> <p>Widget inside which I call the function</p> <pre><code>return DefaultTabController( ... ... floatingActionButton: Padding( //button to add a new tab padding: const EdgeInsets.only(bottom: 25.0), child: IconButton( icon: Icon( Icons.add_circle, size: 55, ), onPressed: () async { var page = await _addNewTab(); //awaiting this future delayed because we can't show a page which is not built yet await Future.delayed(const Duration(milliseconds: 10), () { setState(() {}); }); //moving to the new tab built after awaiting it if (mounted) { //checking that context is still alive and usable DefaultTabController.of(context)!.animateTo(page); } }, </code></pre> <p>Thanks a lot for your help in advance :)</p>
[ { "answer_id": 74328890, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "scheduler" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423723/" ]
74,325,983
<p>I am trying to understand how first class functions work in R. I had understood that functions were first class in R, but was sorely disappointed when applying that understanding. When a function is saved to a list, whether that be as an ordinary list, a vector or a dictionary style list or vector, it is no longer callable, leading to the following error:</p> <pre><code>Error: attempt to apply non-function </code></pre> <p>e.g.</p> <pre><code>print_func &lt;- function() { print('hi') } print_func() [1] &quot;hi&quot; my_list = list(print_func) my_list[0]() Error: attempt to apply non-function my_vector = c(print_func) my_vector[0]() Error: attempt to apply non-function my_map &lt;- c(&quot;a&quot; = print_func) my_map[&quot;a&quot;]() Error: attempt to apply non-function </code></pre> <p>So why is this? Does R not actually treat functions as first class members in all cases, or is there another reason why this occurs?</p> <p>I see that R vectors also do unexpected things (for me - perhaps not for experienced R users) to nested arrays:</p> <pre><code>nested_vector &lt;- c(&quot;a&quot; = c(&quot;b&quot; = 1)) nested_vector[&quot;a&quot;] &lt;NA&gt; NA nested_vector[&quot;a.b&quot;] a.b 1 </code></pre> <p>Here it makes sense to me that &quot;a.b&quot; might reference the sub-member of the key &quot;b&quot; under the key &quot;a&quot;. But apparently that logic goes out the window when trying to call the upper level key &quot;a&quot;.</p>
[ { "answer_id": 74326316, "author": "B. Christian Kamgang", "author_id": 10848898, "author_profile": "https://Stackoverflow.com/users/10848898", "pm_score": 2, "selected": true, "text": "[]" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74325983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/724403/" ]
74,326,004
<p>How to use apache gremlin <code>constant</code> in AWS Neptune database?</p> <pre><code>g.V().hasLabel('user').has('name', 'Thirumal1').coalesce(id(), constant(&quot;1&quot;)); </code></pre> <p>Not getting constant value in the output. The document says, need to use it with <code>sack</code> <a href="https://docs.aws.amazon.com/neptune/latest/userguide/gremlin-step-support.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/neptune/latest/userguide/gremlin-step-support.html</a>. How to use constant in AWS Neptune.</p>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391490/" ]
74,326,008
<p>i try to create linear function in an interval and the other interval is 0. and add it to an array</p> <p>so i tried this code</p> <pre><code>import numpy as np import sympy as sp import matplotlib as plt # This is all the library's i need import mpmath x = sp.symbols('x') n = 10 xx = (np.array([np.linspace(0, 1, n+1)])) i = 0 N = [] N[0] = sp.Piecewise( ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), xx[0, i] &lt;= x), ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), x &lt;= xx[0, i + 1]), (0, True) ) </code></pre> <p>and it always returns</p> <pre><code> line 511, in __bool__ raise TypeError(&quot;cannot determine truth value of Relational&quot;) TypeError: cannot determine truth value of Relational </code></pre> <p>EDIT: after i add x is positive to symbol i try to make a vector of linear function in the intervals in a loop and i don't know why it refuses to determine the the truth value even tough in the line above it succeed:</p> <pre><code>import sympy as sp import matplotlib as plt # This is all the library's i need import mpmath x = sp.symbols('x', positive=True) n = 10 xx = (np.array([np.linspace(0, 1, n+1)])) i = 0 N = [] a = sp.Piecewise( ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), (xx[0, i]) &lt;= x), ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), (x &lt;= (xx[0, i + 1]))), (0, True) ) N.append(a) for i in range(1, n): a = sp.Piecewise( (0, x &lt; xx[0, i - 1]), ((xx[0, i - 1] - x) / (xx[0, i - 1] - xx[0, i]), ((xx[0, i - 1]) &lt;= x)), ((xx[0, i - 1] - x) / (xx[0, i - 1] - xx[0, i]), (x &lt;= (xx[0, i]))), ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), ((xx[0, i]) &lt;= x)), ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), (x &lt;= (xx[0, i + 1]))), (0, True) ) N.append(a) </code></pre> <p>and i get the same Error:</p> <p>File &quot;&quot;, line 23, in File &quot;pythonProjectFEANew\venv\lib\site-packages\sympy\core\relational.py&quot;, line 511, in <strong>bool</strong> raise TypeError(&quot;cannot determine truth value of Relational&quot;) TypeError: cannot determine truth value of Relational</p> <pre><code> </code></pre>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423772/" ]
74,326,049
<p>I have a situation, demo code below:</p> <pre><code> const callFnWithArgs = (callback: (a: string, b: number) =&gt; void) =&gt; async (a: string, b: number): Promise&lt;void&gt; =&gt; { try { await callback(a,b) } catch(e){ console.log(e) } </code></pre> <p>The code works fine, but I have ESLint unused vars property setup in the project. I receive error that a and b are unused-vars in line 1.</p> <p>Any solution for this? Function signature changes are welcome.</p> <p>Note:</p> <ol> <li>I do not wish to disable/bypass the unused vars property globally or here.</li> <li>I do not wish to use 'any'</li> <li>I do not wish to remove the type so that it would infer 'any'</li> </ol>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17632251/" ]
74,326,064
<p>I have 20 iconbuttons in my form. when clickevent is performed i want to change buttons(backcolor,forecolor,Iconcolor) and remaining buttons should revert to it's default color.</p> <pre><code> public void btn1() { foreach (Control c in this.Controls) { if (c is Button) { (c as Button).ForeColor = Color.White; (c as Button).BackColor = Color.FromArgb(46, 51, 73); } } } </code></pre>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19232771/" ]
74,326,065
<p>I was trying to learn c++ i wanted to find marks using the code the issue is that it is not giving me the correct output and i wanted it to loop if the marks are less i wawnted to repeat it . This is the code that i wrote</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; void mygrade(int grades) { if (grades &gt;= 90) { printf(&quot;High distinction&quot;); } else if (grades &gt; 80 &lt; 70) { printf(&quot;Your Grade is Distinciton&quot;); } else if (grades &gt; 60 &lt; 70) { printf(&quot;Credit&quot;); } else if (grades &gt; 50 &lt; 60) { printf(&quot;Pass&quot;); } else if (grades &lt; 50) { printf(&quot;Fail&quot;); } else { printf(&quot;Enter vaild Marks&quot;); } } void main() { int grades; printf(&quot;Enter your score for this unit\n&quot;); scanf(&quot;%d&quot;, &amp;grades); printf(&quot;your grade for this unit is: %d &quot;); } </code></pre> <p><a href="https://i.stack.imgur.com/Pe4DP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pe4DP.png" alt="this is what i expecting to do" /></a></p>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423890/" ]
74,326,096
<p>My panda DF contains huge data and giving filename with '.DAT' extension (client requirement) and using <code>to_csv()</code> to write data.</p> <p>When I open the file in notepad or any other text viewer, I see double quotes at start and end of the file:</p> <pre><code>&quot; col1|Col2|Col3 D1|D2|D3 ... So On D1n|D2n|D3n &quot; </code></pre> <p>How to remove these double quotes while writing the dataframe as CSV file?</p> <p>I tried quote, quoting parameters in to_csv, replace function. Please suggest any parameter combination to eliminate this</p>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423896/" ]
74,326,097
<p>I'm working on an answer site crawler, how should I get the questions text inside this td, instead of including the text in the tag</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border=&quot;0&quot; width=&quot;100%&quot; onclick=&quot;GiveAns(event.srcElement||event.target)&quot; onmouseover=&quot;ChangeColor(event.srcElement||event.target)&quot; &gt; &lt;tbody&gt; &lt;tr&gt; &lt;th class=&quot;w&quot;&gt;Question number&lt;/th&gt; &lt;th class=&quot;w&quot;&gt;key&lt;br /&gt;answer&lt;/th&gt; &lt;th class=&quot;w&quot;&gt;Choose your &lt;br /&gt;own answer&lt;/th&gt; &lt;th class=&quot;w&quot;&gt;Selected Topics&lt;span id=&quot;cdes&quot;&gt;&lt;/span&gt;&lt;/th&gt; &lt;th class=&quot;w&quot;&gt;Error&lt;br /&gt;Notification&lt;/th&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tbody id=&quot;s1234&quot;&gt; &lt;tr id=&quot;d1&quot;&gt; &lt;th&gt;&lt;a name=&quot;P1&quot;&gt;1&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;b&gt;(1)&lt;/b&gt;&lt;/th&gt; &lt;th&gt;&lt;tt&gt; &lt;/tt&gt;&lt;/th&gt; &lt;td&gt; question1 &lt;i&gt; &lt;a&gt;(1)ans1&lt;/a&gt; &lt;/i&gt; &lt;i&gt;(2)ans2&lt;/i&gt; &lt;i&gt;(3)ans3&lt;/i&gt; &lt;i&gt;ans4&lt;/i&gt;。&lt;q&gt;360 02-137&lt;/q&gt; &lt;/td&gt; &lt;th class=&quot;h&quot; onclick=&quot;E(this)&quot;&gt;&lt;img src=&quot;/e.gif&quot; /&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr id=&quot;d2&quot;&gt; &lt;th&gt;&lt;a name=&quot;P2&quot;&gt;2&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;b&gt;(4)&lt;/b&gt;&lt;/th&gt; &lt;th&gt;&lt;tt&gt; &lt;/tt&gt;&lt;/th&gt; &lt;td&gt; question2 &lt;i&gt;(1)ans1&lt;/i&gt; &lt;i&gt;(2)ans2&lt;/i&gt; &lt;i&gt;(3)ans3&lt;/i&gt; &lt;i&gt; &lt;a&gt;(4)ans4&lt;/a&gt; &lt;/i&gt; 。 &lt;q&gt;1149 &lt;/q&gt; &lt;/td&gt; &lt;th class=&quot;h&quot; onclick=&quot;E(this)&quot;&gt;&lt;img src=&quot;/e.gif&quot; /&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This is my table for site</p> <p>I tried these methods</p> <pre><code>document.querySelectorAll('#s1234 tr &gt; td:not(i)').forEach((e)=&gt;{console.log(e)}) document.querySelectorAll('#s1234 tr &gt; td')) </code></pre> <p>But all of these methods contain &lt;i&gt; and &lt;a&gt; tags, so how do I get just the question text?</p> <p><code>The result I need is like this: &quot;question1&quot;</code></p>
[ { "answer_id": 74329436, "author": "Kelvin Lawrence", "author_id": 5442034, "author_profile": "https://Stackoverflow.com/users/5442034", "pm_score": 2, "selected": true, "text": "fold().coalesce()" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649365/" ]
74,326,106
<p>I'm currently working on a code and I'm getting this error. Please explain what am I doing wrong in a simple way...help!</p> <pre><code>s=int(input('input random seed:')) a=print('The first number is',format(random(50,56))) b=print('The second number is',format(random(50,56))) if (a*b)==c: print('Your answer is correct.') </code></pre>
[ { "answer_id": 74326144, "author": "Devam Sanghvi", "author_id": 16921041, "author_profile": "https://Stackoverflow.com/users/16921041", "pm_score": -1, "selected": false, "text": "None" }, { "answer_id": 74326146, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 0, "selected": false, "text": "a = print('The first number is',format(random.randint(1,9)))\nb = print('The second number is',format(random.randint(1,9)))\n" }, { "answer_id": 74326180, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 0, "selected": false, "text": "print" }, { "answer_id": 74326199, "author": "The Myth", "author_id": 15042008, "author_profile": "https://Stackoverflow.com/users/15042008", "pm_score": 0, "selected": false, "text": "python" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423929/" ]
74,326,107
<p>I have this block of dart code here.</p> <pre><code> var response = await http.post(url); var data = response.body; await Future.delayed( const Duration(seconds: 1), ); if (!mounted) return; print(&quot;This is data $data&quot;); if (data == &quot;success&quot;) { print(&quot;if&quot;); } else if (data == &quot;lacking&quot;) { print(&quot;else if&quot;); } else { print(&quot;else&quot;); } </code></pre> <p>Here is the php</p> <pre><code>echo json_encode(&quot;success&quot;); </code></pre> <p>Yes it is just this 1 line of code.</p> <p>for some reason the output would be &quot;else&quot; instead of my expected &quot;if&quot;</p> <p>Here's an image of the output. <a href="https://i.stack.imgur.com/bRcnT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bRcnT.png" alt="enter image description here" /></a></p> <p>I tried putting other words instead of success but it resulted in the same problem. Which is it goes to the else statement.</p> <p><strong>I found the answer</strong></p> <p>data is literally equals to &quot;success&quot; with double quotation on them. To fix it I had to do this.</p> <pre><code>String success = &quot;\&quot;success\&quot;&quot;; </code></pre> <p><a href="https://i.stack.imgur.com/ezA7k.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74326278, "author": "Richard Heap", "author_id": 9597706, "author_profile": "https://Stackoverflow.com/users/9597706", "pm_score": 2, "selected": true, "text": "\"success\"" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20307720/" ]
74,326,124
<pre><code>const SignIn = ({navigation}) =&gt; { const [data, setData] = React.useState({ username: '', password: '', check_textInputChange: false, secureTextEntry: true, isValidUser: true, isValidPassword: true, }); const { colors } = useTheme(); const { signIn } = React.useContext(AuthContext); . . const loginHandle = (userName, password) =&gt; { . . signIn(foundUser); } </code></pre> <p>In the above set of lines of code to implement SignIn in my <strong>react-native app</strong>, facing the error as mentioned in the title above i.e., <strong>TypeError: Cannot read property 'signIn' of undefined</strong></p>
[ { "answer_id": 74326278, "author": "Richard Heap", "author_id": 9597706, "author_profile": "https://Stackoverflow.com/users/9597706", "pm_score": 2, "selected": true, "text": "\"success\"" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13828784/" ]
74,326,136
<pre><code> let i = -1; let total = 0; let numPrompt; do { numPrompt = prompt(&quot;&quot;) total += parseInt(numPrompt) i++; } while (numPrompt != '0'); // do-while loop let avg = total/i; console.log(total) console.log(avg) </code></pre> <p>I want user to input a number each time till they input zero which will output all their previous input, total and average.</p> <p>I declare i = -1 to avoid counting the last input which is the zero.</p> <p>in my code, I only manage to display the total of all my input but what I also want is all my previous inputs (prompt)printed out each row</p>
[ { "answer_id": 74326278, "author": "Richard Heap", "author_id": 9597706, "author_profile": "https://Stackoverflow.com/users/9597706", "pm_score": 2, "selected": true, "text": "\"success\"" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20423412/" ]
74,326,251
<p>Please excuse how utterly &quot;noobish&quot; I am, I'm trying to learn as I go along but I'm <em>very</em> new.</p> <p>I have the below code which I'm trying to use for a Discord bot. For the most part it works, however the @ &quot;ping&quot; simply returns &quot;@undefined&quot; as opposed to the values I've set in the consts.</p> <p>Would anyone be so kind as to point me in the right direction on this?</p> <pre><code> const ping = { roleID: function() { return this.role; } } const John = { role:&quot;abc&quot; } const Mary = { role:&quot;123&quot; } function pingSubbed() { let pingID = message.author.username; if (pingID == &quot;John&quot;) { ping.roleID.call(John); } if (pingID == &quot;Mary&quot;) { ping.roleID.call(Mary); } } yield hook.send(`**${message.author.username}**\n` + &quot; &quot; + messageContents + &quot; &quot; + &quot;@&quot;+pingSubbed()); </code></pre> <p>I'm expecting the function pingSubbed() to determine the username of the person who posts in Discord, for example John, reference the above ping.roleID.call(John) and then take the appropriate role (in this case John = abc) and sending this information as a message itself - @123 - as in the last line &quot;@&quot;+pingSubbed()</p>
[ { "answer_id": 74326329, "author": "Salem_Raouf", "author_id": 12863176, "author_profile": "https://Stackoverflow.com/users/12863176", "pm_score": 0, "selected": false, "text": "function pingSubbed() {\n let pingID = message.author.username;\n if (pingID == \"John\") {\n ping.roleID.call(John);\n }\n if (pingID == \"Mary\") {\n ping.roleID.call(Mary);\n }\n return pingID // add this line \n }\n" }, { "answer_id": 74326356, "author": "dandavis", "author_id": 2317490, "author_profile": "https://Stackoverflow.com/users/2317490", "pm_score": 2, "selected": true, "text": "function pingSubbed() {\n let getId = Function.call.bind(ping.roleID);\n return {\n John: getId(John),\n Mary: getId(Mary),\n }[message.author.username] || (\"Unknown User:\"+message.author.username);\n}\n \n" }, { "answer_id": 74326383, "author": "Siddiqui Affan", "author_id": 14928212, "author_profile": "https://Stackoverflow.com/users/14928212", "pm_score": -1, "selected": false, "text": "this" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17105319/" ]
74,326,353
<p>ive got the below code to print a pattern (attached below). However i'd like to just use one loop</p> <pre class="lang-cpp prettyprint-override"><code>#include&lt;iostream&gt; using namespace std; int main(){ int n; cin&gt;&gt;n; for(int i=1;i&lt;=n;i++){ for(int j=1;j&lt;=i;j++){ cout&lt;&lt;&quot;*&quot;; } for(int j=1;j&lt;=n-i;j++){ if(j%2!=0){ cout&lt;&lt;&quot;_&quot;; }else{ cout&lt;&lt;&quot;.&quot;; } } cout&lt;&lt;endl; } for(int i=1;i&lt;n;i++){ for(int j=1;j&lt;=n-i;j++){ cout&lt;&lt;&quot;*&quot;; } for(int j=1;j&lt;=i;j++){ if(j%2==0){ cout&lt;&lt;&quot;.&quot;; }else{ cout&lt;&lt;&quot;_&quot;; } } cout&lt;&lt;endl; } } </code></pre> <p>when n = 5, heres the output.</p> <pre><code>*_._. **_._ ***_. ****_ ***** ****_ ***_. **_._ *_._. </code></pre> <p>how do i just make this into one single loop</p>
[ { "answer_id": 74326361, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 0, "selected": false, "text": "std::abs" }, { "answer_id": 74326595, "author": "Quiensabe", "author_id": 14906583, "author_profile": "https://Stackoverflow.com/users/14906583", "pm_score": 2, "selected": true, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int n;\n cin >> n;\n for (int i = 1; i <= n*2-1; i++) {\n if (i <= n)\n {\n for (int j = 1; j <= i; j++) {\n cout << \"*\";\n }\n for (int j = 1; j <= n - i; j++) {\n if (j % 2 != 0) {\n cout << \"_\";\n }\n else {\n cout << \".\";\n }\n }\n cout << endl;\n }\n else\n {\n for (int j = 1; j <= n*2 - i; j++) {\n cout << \"*\";\n }\n for (int j = 1; j <= i-n; j++) {\n if (j % 2 == 0) {\n cout << \".\";\n }\n else {\n cout << \"_\";\n }\n }\n cout << endl;\n }\n }\n}\n" }, { "answer_id": 74327148, "author": "Bob__", "author_id": 4944425, "author_profile": "https://Stackoverflow.com/users/4944425", "pm_score": 1, "selected": false, "text": "// Let's start by figuring out some dimensions.\nint n;\nstd::cin >> n; \nint height = 2 * n - 1;\nint area = n * height;\n\n// Now we'll print the \"rectangle\", one piece at a time.\nfor (int i = 0; i < area; ++i)\n{ // ^^^^^^^^\n // Extract the coordinates of the char to be printed.\n int x = i % n;\n int y = i / n;\n \n // Assign a symbol, based on such coordinates.\n if ( x <= y and x <= height - y - 1 )\n { // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals. \n std::cout << '*'; // This prints correctly the triangle on the left...\n }\n else\n {\n std::cout << '_'; // <--- But of course, something else should done here. \n }\n \n // End of row.\n if ( x == n - 1 )\n std::cout << '\\n';\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12399640/" ]
74,326,380
<p>New to programming and looking for help please,</p> <p>i need to the set the value of $b_num based on the value of $egg_type i have tried using an if statement but not having any luck</p> <p>`</p> <pre><code> $egg_type = $row[&quot;egg_type&quot;] ; if ($egg_type == 'M/S Select Farm') { $b_num = '1'; } if ($egg_type = 'Free Range') { $b_num = '1'; } if ($egg_type = 'Barn') { $b_num = '2'; } if ($egg_type =='Intensive') { $b_num = '3'; } if ($egg_type == 'Organic') { $b_num = '0'; } if ($egg_type == 'Brioche') { $b_num = '3'; } </code></pre> <p>`</p> <p>Tried the if statement but the value didnt change,</p>
[ { "answer_id": 74326361, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 0, "selected": false, "text": "std::abs" }, { "answer_id": 74326595, "author": "Quiensabe", "author_id": 14906583, "author_profile": "https://Stackoverflow.com/users/14906583", "pm_score": 2, "selected": true, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int n;\n cin >> n;\n for (int i = 1; i <= n*2-1; i++) {\n if (i <= n)\n {\n for (int j = 1; j <= i; j++) {\n cout << \"*\";\n }\n for (int j = 1; j <= n - i; j++) {\n if (j % 2 != 0) {\n cout << \"_\";\n }\n else {\n cout << \".\";\n }\n }\n cout << endl;\n }\n else\n {\n for (int j = 1; j <= n*2 - i; j++) {\n cout << \"*\";\n }\n for (int j = 1; j <= i-n; j++) {\n if (j % 2 == 0) {\n cout << \".\";\n }\n else {\n cout << \"_\";\n }\n }\n cout << endl;\n }\n }\n}\n" }, { "answer_id": 74327148, "author": "Bob__", "author_id": 4944425, "author_profile": "https://Stackoverflow.com/users/4944425", "pm_score": 1, "selected": false, "text": "// Let's start by figuring out some dimensions.\nint n;\nstd::cin >> n; \nint height = 2 * n - 1;\nint area = n * height;\n\n// Now we'll print the \"rectangle\", one piece at a time.\nfor (int i = 0; i < area; ++i)\n{ // ^^^^^^^^\n // Extract the coordinates of the char to be printed.\n int x = i % n;\n int y = i / n;\n \n // Assign a symbol, based on such coordinates.\n if ( x <= y and x <= height - y - 1 )\n { // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals. \n std::cout << '*'; // This prints correctly the triangle on the left...\n }\n else\n {\n std::cout << '_'; // <--- But of course, something else should done here. \n }\n \n // End of row.\n if ( x == n - 1 )\n std::cout << '\\n';\n}\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6353530/" ]
74,326,407
<pre><code>'Membuat shortcut sheet untuk lebih pendek 'Make shortcut Set po = Sheets(&quot;Print Out&quot;) Dim awal, Akhir As Integer Dim j As Long 'mencantumkan N6 &amp; O6 menjadi value acuan 'Make N6 &amp; O6 as main value print awal = po.Range(&quot;N6&quot;).Value Akhir = po.Range(&quot;O6&quot;).Value j = 0 'menjalankan menu pilih printer 'Show up print dialog and set &quot;normal&quot; print area (w/o) condition Application.ScreenUpdating = False Application.Dialogs(xlDialogPrinterSetup).Show po.PageSetup.PrintArea = &quot;$B$1:$L$57&quot; 'perintah utama 'Main command to apply auto mass print For i = awal To Akhir With po .Range(&quot;M1&quot;).Value = i + 0 + j .Range(&quot;M2&quot;).Value = i + 1 + j .Range(&quot;M3&quot;).Value = i + 2 + j .Range(&quot;M4&quot;).Value = i + 3 + j .PrintPreview j = j + 3 End With 'jika mendeteksi N/A atau sejenisnya perintah akan berhenti 'If found #N/A or #REF or any error loop will stop to prevent loop printing even data already reach limit If IsError(po.Range(&quot;C4&quot;)) Then Exit For If IsError(po.Range(&quot;C18&quot;)) Then po.PageSetup.PrintArea = &quot;$B$1:$L$15&quot; Exit For 'Jika M4 lebih besar dari batas akhir (O6) maka perintah akan terhenti 'If m4 &gt; than O6 then print area will change and stop the loop (THIS IS THE PROBLEM) If po.Range(&quot;M4&quot;) + 2 &gt; po.Range(&quot;O6&quot;) Then po.PageSetup.PrintArea = &quot;$B$1:$L$43&quot; If po.Range(&quot;M3&quot;) + 3 &gt; po.Range(&quot;O6&quot;) Then po.PageSetup.PrintArea = &quot;$B$1:$L$29&quot; If po.Range(&quot;M2&quot;) + 4 &gt; po.Range(&quot;O6&quot;) Then po.PageSetup.PrintArea = &quot;$B$1:$L$15&quot; Next i </code></pre> <p>The macro I created as above, but there is a problem that I cannot overcome.</p> <p>Like the following line:</p> <p><code>If po.Range(&quot;M4&quot;) + 2 &gt; po.Range(&quot;O6&quot;) Then po.PageSetup.PrintArea = &quot;$B$1:$L$43&quot;</code></p> <p>Basically, the code above will adjust the &quot;printarea&quot; if it has crossed the limit I have set, but I want to add an &quot;Exit for&quot; command to stop the loop after the &quot;If-then&quot; criteria is met.`</p> <p>I already tried to make</p> <pre><code>If po.Range(&quot;M4&quot;) + 2 &gt; po.Range(&quot;O6&quot;) Then po.PageSetup.PrintArea = &quot;$B$1:$L$43 Exit for </code></pre> <p>but the &quot;Exit for&quot; code will run along with the printarea change, so my last page has not been printed yet. What I want is for the loop to stop after my last page is printed (where my last page will always be related to the &quot;if then&quot; above).</p>
[ { "answer_id": 74326510, "author": "Svein Arne Hylland", "author_id": 20416519, "author_profile": "https://Stackoverflow.com/users/20416519", "pm_score": 0, "selected": false, "text": "If po.Range(\"M4\") + 2 > po.Range(\"O6\") Then \n po.PageSetup.PrintArea = \"$B$1:$L$4\"\nElse\n Exit for\nEnd if\n" }, { "answer_id": 74327056, "author": "Svein Arne Hylland", "author_id": 20416519, "author_profile": "https://Stackoverflow.com/users/20416519", "pm_score": 0, "selected": false, "text": "If po.Range(\"M4\") + 2 > po.Range(\"O6\") Then \n po.PageSetup.PrintArea = \"$B$1:$L$4\"\nElse\n GOTO ContinueHere \nEnd if\n' Code you want to skip\n\nContinueHere:\n' Continues to code here \n\nNEXT\n" }, { "answer_id": 74327440, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "If...Then" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390194/" ]
74,326,413
<pre><code>#include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/wait.h&gt; int main(){ char buf[10]; pid_t pid = fork(); if (pid &lt; 0){ printf(&quot;error fork\n&quot;); exit(1); } if (pid == 0){ fgets(buf,5,stdin); printf(&quot;Child : %s\n&quot;,buf); } else{ wait(NULL); char* r = fgets(buf,5,stdin); if (r == NULL){ printf(&quot;Parent : eof = %i\n&quot;,feof(stdin)); } else { printf(&quot;Parent : %s\n&quot;,buf); } } return 0; } </code></pre> <p>My program is very simple : a process is forked; the child process reads 4 characters from <em>stdin</em> and when it finishes, the parent process reads 4 characters from <em>stdin</em>.</p> <p>Normally, if I write characters in <em>stdin</em> (before the fork) the child process should read the first 4 characters and then the parent process should read the next 4 characters. It seems quit logical as <em>fork()</em> duplicates the parent process, including the file descriptors and opened files.</p> <p>But, when I execute <code>echo 'aaaaaaaaa' | ./my_program</code> I get <code>Child : aaaa Parent : eof = 1</code></p> <p>It seems that <em>stdin</em> has been emptied by the child process when it finished. I having hard time explaining this behavior.</p> <p>Can you help me ? :)</p>
[ { "answer_id": 74326669, "author": "Janez Kuhar", "author_id": 6367213, "author_profile": "https://Stackoverflow.com/users/6367213", "pm_score": 2, "selected": true, "text": "fork()" }, { "answer_id": 74326713, "author": "Peter Irich", "author_id": 20275388, "author_profile": "https://Stackoverflow.com/users/20275388", "pm_score": -1, "selected": false, "text": "//wait(NULL);\n" } ]
2022/11/05
[ "https://Stackoverflow.com/questions/74326413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19815639/" ]