qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,631,840
<p>Is there a way to have a default value when doing string formatting? For example:</p> <pre><code>s = &quot;Text {0} here, and text {1} there&quot; s.format('foo', 'bar') </code></pre> <p>What I'm looking for is setting a default value for a numbered index, so that it can be skipped in the placeholder, e.g. <em>something</em> like this:</p> <pre><code>s = &quot;Text {0:'default text'} here, and text {1} there&quot; </code></pre> <p>I checked <a href="https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings</a> and didn't find what I need, maybe looking in the wrong place?</p> <p>Thanks.</p>
[ { "answer_id": 74631847, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "$('section li').load(function() {\n $.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n });\n" }, { "answer_id": 74631875, "author": "Kaushik Makwana", "author_id": 5729416, "author_profile": "https://Stackoverflow.com/users/5729416", "pm_score": 0, "selected": false, "text": "document.ready $( document ).ready(function() {\n$.ajax({\n type: 'GET',\n url: 'includes/ext-content/cpu-shop.html',\n dataType: 'html',\n success: function(response) {\n $('.ext-content2').html(response);\n }\n });\n});\n" }, { "answer_id": 74631883, "author": "Twisty", "author_id": 463319, "author_profile": "https://Stackoverflow.com/users/463319", "pm_score": 2, "selected": true, "text": "$(function(){\n $('.ext-content').load('includes/ext-content/' + $('section li').eq(0).data('content') + '.html');\n \n $('section li').click(function() {\n $('.ext-content').load('includes/ext-content/' + $(this).data('content') + '.html');\n });\n});\n .load() .html() .load() LI data" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
74,631,940
<p>A sequence of non-empty strings stringList is given, containing only uppercase letters of the Latin alphabet. For all strings starting with the same letter, determine their total length and obtain a sequence of strings of the form <code>&quot;S-C&quot;</code>, where <code>S</code> is the total length of all strings from stringList that begin with the character <code>C</code>.</p> <pre class="lang-cs prettyprint-override"><code>var stringList = new[] { &quot;YELLOW&quot;, &quot;GREEN&quot;, &quot;YIELD&quot; }; var expected = new[] { &quot;11-Y&quot;, &quot;5-G&quot; }; </code></pre> <p>I tried this:</p> <pre class="lang-cs prettyprint-override"><code>var groups = from word in stringList orderby word ascending group word by word[0] into groupedByFirstLetter orderby groupedByFirstLetter.Key descending select new { key = groupedByFirstLetter.Key, Words = groupedByFirstLetter.Select(x =&gt; x.Length) }; </code></pre> <p>But the output of this query is <code>Y 6 5 G 5</code> instead of <code>Y-11 G-5</code>. What I would like to know is how to sum the lengths if there is more than 1 word in the group, and how to format the result/display it as expected?</p>
[ { "answer_id": 74632043, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 1, "selected": false, "text": "var result = stringList.GroupBy(e => e[0]).Select(e => $\"{e.Sum(o => o.Length)}-{e.Key}\").ToArray();\n" }, { "answer_id": 74632061, "author": "Drunken Code Monkey", "author_id": 3440248, "author_profile": "https://Stackoverflow.com/users/3440248", "pm_score": 3, "selected": true, "text": "var results = stringList.OrderByDescending(x => x[0])\n .ThenBy(x => x)\n .GroupBy(x => x[0])\n .Select(g => $\"{g.Sum(x => x.Length)}-{g.Key}\")\n .ToArray();\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569938/" ]
74,631,945
<p>I would like to set my stop-loss at the low of my entry bar.</p> <p>what is the condition I need to use ?</p> <p>I try</p> <pre><code>if strategy.position_size &lt; 0 strategy.exit(id=&quot;Close Short&quot;, stop=low[1]) </code></pre> <p>but this my stop-loss change everytime</p>
[ { "answer_id": 74632043, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 1, "selected": false, "text": "var result = stringList.GroupBy(e => e[0]).Select(e => $\"{e.Sum(o => o.Length)}-{e.Key}\").ToArray();\n" }, { "answer_id": 74632061, "author": "Drunken Code Monkey", "author_id": 3440248, "author_profile": "https://Stackoverflow.com/users/3440248", "pm_score": 3, "selected": true, "text": "var results = stringList.OrderByDescending(x => x[0])\n .ThenBy(x => x)\n .GroupBy(x => x[0])\n .Select(g => $\"{g.Sum(x => x.Length)}-{g.Key}\")\n .ToArray();\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648245/" ]
74,631,959
<p>I'm having the following error in React:</p> <p><a href="https://i.stack.imgur.com/89oAY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89oAY.png" alt="enter image description here" /></a></p> <p>Here's my code:</p> <pre><code>import React, { useEffect } from 'react' import './Mark.css' import { forEach } from &quot;lodash&quot;; export interface MarkProps { key: string content: string start: number end: number tag: string colors?: Array&lt;string&gt; onClick: (any: any) =&gt; any } export default function Mark(props: MarkProps) { function printProps() { console.log(&quot;The props&quot;) console.log(props) } useEffect(() =&gt; { printProps() }, []) return ( &lt;mark style={{ backgroundColor: 'rgba(0,0,0,0)', display: 'inline-grid', rowGap: '0', padding: '0 4px' }} data-start={props.start} data-end={props.end} onClick={() =&gt; props.onClick({ start: props.start, end: props.end })} &gt; { props.content &amp;&amp; ( &lt;span style={{ textDecoration: 'underline', textDecorationColor: '#84d2ff' }}&gt;{props.content}&lt;/span&gt; ) } { props.colors?.map((col: string) =&gt; { console.log(col); &lt;span className='dot' style={{ backgroundColor: col }}&gt;&lt;/span&gt; }) } &lt;/mark&gt; ) } </code></pre> <p>Error comes from trying to display a span dot for each of the colors within <code>props.colors</code>.</p> <p>The only thing that I've tried that doesn't display an error is:</p> <pre><code> { props.colors?.map((col: string) =&gt; { console.log(col); &lt;span className='dot' style={{ backgroundColor: col }}&gt;&lt;/span&gt; }) &amp;&amp; &lt;&gt;&lt;/&gt; } </code></pre> <p>However, in this way nothing gets displayed.</p> <p>What's the correct way to achieve what I'm trying to do?</p> <p>Thanks.</p>
[ { "answer_id": 74632071, "author": "Ferin Patel", "author_id": 11812450, "author_profile": "https://Stackoverflow.com/users/11812450", "pm_score": 0, "selected": false, "text": "{} \nreturn (\n <mark\n style={{ backgroundColor: 'rgba(0,0,0,0)', display: 'inline-grid', rowGap: '0', padding: '0 4px' }}\n data-start={props.start}\n data-end={props.end}\n onClick={() => props.onClick({ start: props.start, end: props.end })}\n\n >\n {\n props.content && (\n <span style={{ textDecoration: 'underline', textDecorationColor: '#84d2ff' }}>{props.content}</span>\n )\n }\n {\n props.colors?.map((col: string) => {\n console.log(col); \n {/* ---------> added return to next line */}\n return <span className='dot' style={{ backgroundColor: col }}></span> \n })\n }\n\n </mark>\n )\n" }, { "answer_id": 74632151, "author": "Xiduzo", "author_id": 4655177, "author_profile": "https://Stackoverflow.com/users/4655177", "pm_score": 0, "selected": false, "text": "mark Fragment span return (\n <mark\n style={{ backgroundColor: 'rgba(0,0,0,0)', display: 'inline-grid', rowGap: '0', padding: '0 4px' }}\n data-start={props.start}\n data-end={props.end}\n onClick={() => props.onClick({ start: props.start, end: props.end })}\n\n >\n <React.Fragment>\n {\n props.content && (\n <span style={{ textDecoration: 'underline', textDecorationColor: '#84d2ff' }}>{props.content}</span>\n )\n }\n {\n props.colors?.map((col: string) => {\n console.log(col);\n return <span className='dot' style={{ backgroundColor: col }}></span>\n })\n }\n </React.Fragment>\n </mark>\n )\n" }, { "answer_id": 74632165, "author": "Sanay Varghese", "author_id": 20193094, "author_profile": "https://Stackoverflow.com/users/20193094", "pm_score": 2, "selected": true, "text": " {props.colors?.map((col: string, index) => {\n return (\n <span\n className=\"dot\"\n style={{ backgroundColor: col, width: \"10px\", height: \"10px\" }}\n key={index}\n ></span>\n );\n })}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74631959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20303244/" ]
74,632,001
<p>JSON: <a href="https://www.cc.puv.fi/%7Easa/cgi-bin/fetchOrders.py" rel="nofollow noreferrer">https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py</a></p> <p>Im trying to fetch objects and arrays within the object but im only fetching the objects.</p> <p>How do i fetch also &quot;products&quot; arrays?</p> <p>My javascript code:</p> <pre><code>fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py') .then(res =&gt; res.text()) .then(teksti =&gt; tulostus(teksti)) function tulostus(txt) { console.log(txt); let tilaukset = JSON.parse(txt); console.log(tilaukset); let a = &quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;orderid&lt;/th&gt;&lt;th&gt;customerid&lt;/th&gt;&lt;th&gt;customer&lt;/th&gt;&lt;th&gt;invaddr&lt;/th&gt;&lt;th&gt;delivaddr&lt;/th&gt;&lt;th&gt;deliverydate&lt;/th&gt;&lt;th&gt;respsalesperson&lt;/th&gt;&lt;th&gt;comment&lt;/th&gt;&lt;th&gt;totalprice&lt;/th&gt;&lt;/tr&gt;&quot;; for(let i = 0; i &lt; tilaukset.length; i++) { let tilaus = tilaukset[i]; console.log(tilaus) console.log(tilaus.orderid); a += '&lt;tr&gt;&lt;td&gt;' + tilaus.orderid + '&lt;/td&gt;&lt;td&gt;' + tilaus.customerid + '&lt;/td&gt;&lt;td&gt;' + tilaus.customer + '&lt;/td&gt;&lt;td&gt;' + tilaus.invaddr + '&lt;/td&gt;&lt;td&gt;' + tilaus.delivaddr + '&lt;/td&gt;&lt;td&gt;' + tilaus.deliverydate + '&lt;/td&gt;&lt;td&gt;' + tilaus.respsalesperson + '&lt;/td&gt;&lt;td&gt;' + tilaus.comment + '&lt;/td&gt;&lt;td&gt;' + tilaus.totalprice + '&lt;/td&gt;&lt;/tr&gt;' } console.log(a); document.getElementById('info').innerHTML = a+'&lt;/table&gt;'; } </code></pre>
[ { "answer_id": 74632071, "author": "Ferin Patel", "author_id": 11812450, "author_profile": "https://Stackoverflow.com/users/11812450", "pm_score": 0, "selected": false, "text": "{} \nreturn (\n <mark\n style={{ backgroundColor: 'rgba(0,0,0,0)', display: 'inline-grid', rowGap: '0', padding: '0 4px' }}\n data-start={props.start}\n data-end={props.end}\n onClick={() => props.onClick({ start: props.start, end: props.end })}\n\n >\n {\n props.content && (\n <span style={{ textDecoration: 'underline', textDecorationColor: '#84d2ff' }}>{props.content}</span>\n )\n }\n {\n props.colors?.map((col: string) => {\n console.log(col); \n {/* ---------> added return to next line */}\n return <span className='dot' style={{ backgroundColor: col }}></span> \n })\n }\n\n </mark>\n )\n" }, { "answer_id": 74632151, "author": "Xiduzo", "author_id": 4655177, "author_profile": "https://Stackoverflow.com/users/4655177", "pm_score": 0, "selected": false, "text": "mark Fragment span return (\n <mark\n style={{ backgroundColor: 'rgba(0,0,0,0)', display: 'inline-grid', rowGap: '0', padding: '0 4px' }}\n data-start={props.start}\n data-end={props.end}\n onClick={() => props.onClick({ start: props.start, end: props.end })}\n\n >\n <React.Fragment>\n {\n props.content && (\n <span style={{ textDecoration: 'underline', textDecorationColor: '#84d2ff' }}>{props.content}</span>\n )\n }\n {\n props.colors?.map((col: string) => {\n console.log(col);\n return <span className='dot' style={{ backgroundColor: col }}></span>\n })\n }\n </React.Fragment>\n </mark>\n )\n" }, { "answer_id": 74632165, "author": "Sanay Varghese", "author_id": 20193094, "author_profile": "https://Stackoverflow.com/users/20193094", "pm_score": 2, "selected": true, "text": " {props.colors?.map((col: string, index) => {\n return (\n <span\n className=\"dot\"\n style={{ backgroundColor: col, width: \"10px\", height: \"10px\" }}\n key={index}\n ></span>\n );\n })}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645377/" ]
74,632,002
<pre><code>private static IEnumerable&lt;string&gt; getExtrato(string query) { using (var cn = new SqlConnection(&quot;Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;&quot;)) { cn.Open(); using (var cmd = new SqlCommand() { Connection = cn, CommandText = query }) { var reader = cmd.ExecuteReader(); var result = new List&lt;string&gt;(); while (reader.Read() == true &amp;&amp; result.Count &lt;= 9 ) { if (reader.GetString(1) == &quot;0&quot;) { //+ &quot;ficando assim com: &quot; + reader.GetDecimal(3) result.Add(&quot;\n O cartão nº &quot; + reader.GetString(0) + &quot; levantou: &quot; + reader.GetString(2) + &quot; euros, &quot; + &quot; às: &quot; + reader.GetDateTime(3)); } else { result.Add(&quot;\n O cartão nº &quot; + reader.GetString(0) + &quot; depositou: &quot; + reader.GetString(1) + &quot; euros, &quot; + &quot; às: &quot; + reader.GetDateTime(3)); } } return result; } } } private static IEnumerable&lt;string&gt; extratoOperacao(string numeroCartao) { return getExtrato($@&quot;SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'&quot;); } </code></pre> <p>As I have is presenting me only the first 10 lines, but I need the last 10 by normal order, how do I do that? If anyone can help me, I'd be grateful</p>
[ { "answer_id": 74632317, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 2, "selected": true, "text": "private static IEnumerable<string> getExtrato(string query)\n{\n using (var cn = new SqlConnection(\"Data Source=MAD-PC-023\\\\SQLEXPRESS;Database=bank;Trusted_Connection=True;\"))\n {\n cn.Open();\n using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })\n {\n var reader = cmd.ExecuteReader();\n var result = new List<string>();\n\n // Let's remove unused conditions\n while (reader.Read())\n {\n if (reader.GetString(1) == \"0\")\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" levantou: \" + reader.GetString(2) + \" euros, \" + \" às: \" + reader.GetDateTime(3));\n }\n else\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" depositou: \" + reader.GetString(1) + \" euros, \" + \" às: \" + reader.GetDateTime(3));\n }\n }\n\n // HERE IS THE MAGIC\n return result.TakeLast(10);\n }\n }\n}\n" }, { "answer_id": 74632447, "author": "Andrew Morton", "author_id": 1115360, "author_profile": "https://Stackoverflow.com/users/1115360", "pm_score": 0, "selected": false, "text": "return getExtrato($@\"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC\");\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20571251/" ]
74,632,009
<p>I am stuck on this and would love some help</p> <p>Here is my table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Product</th> <th>Type</th> <th>Ranking</th> <th>Number of Columns Needed is 3 which is calculated formula</th> </tr> </thead> <tbody> <tr> <td>Gum</td> <td>Wrigley</td> <td>4</td> <td>3</td> </tr> <tr> <td>Candy</td> <td>Skittles</td> <td>3</td> <td></td> </tr> <tr> <td>Milk</td> <td>Whole</td> <td>2</td> <td></td> </tr> <tr> <td>Bread</td> <td>Wheat</td> <td>1</td> <td></td> </tr> </tbody> </table> </div> <p>I would like to select the top 3 rows (Amount of Rows) based on ranking and only the first two columns:</p> <p>So end result would look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Product</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>Gum</td> <td>Wrigley</td> </tr> <tr> <td>Candy</td> <td>Skittles</td> </tr> <tr> <td>Milk</td> <td>Whole</td> </tr> </tbody> </table> </div> <p>I tried everything to figure this out</p>
[ { "answer_id": 74632317, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 2, "selected": true, "text": "private static IEnumerable<string> getExtrato(string query)\n{\n using (var cn = new SqlConnection(\"Data Source=MAD-PC-023\\\\SQLEXPRESS;Database=bank;Trusted_Connection=True;\"))\n {\n cn.Open();\n using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })\n {\n var reader = cmd.ExecuteReader();\n var result = new List<string>();\n\n // Let's remove unused conditions\n while (reader.Read())\n {\n if (reader.GetString(1) == \"0\")\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" levantou: \" + reader.GetString(2) + \" euros, \" + \" às: \" + reader.GetDateTime(3));\n }\n else\n {\n result.Add(\"\\n O cartão nº \" + reader.GetString(0) + \" depositou: \" + reader.GetString(1) + \" euros, \" + \" às: \" + reader.GetDateTime(3));\n }\n }\n\n // HERE IS THE MAGIC\n return result.TakeLast(10);\n }\n }\n}\n" }, { "answer_id": 74632447, "author": "Andrew Morton", "author_id": 1115360, "author_profile": "https://Stackoverflow.com/users/1115360", "pm_score": 0, "selected": false, "text": "return getExtrato($@\"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC\");\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20160838/" ]
74,632,012
<pre><code>&lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-3 &quot; style=&quot;border: groove;&quot;&gt; &lt;p class=&quot;circle col-xs-1 center-block&quot;&gt;01&lt;/p&gt; &lt;h3&gt;trending courses&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, consectetur?&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-1&quot;&gt;&lt;/div&gt; &lt;div class=&quot;col-lg-3&quot; style=&quot;border: groove;&quot;&gt; &lt;p class=&quot;circle text-center&quot;&gt;02&lt;/p&gt; &lt;h3&gt;books&amp;library&lt;/h3&gt; &lt;p&gt;Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit nostrum voluptates tempore, pariatur nobis tempora repellendus deserunt suscipit, sed ex nihil eum impedit maiores quia modi qui aut velit veritatis quam deleniti? Quasi dolor, asperiores ut cumque laboriosam accusamus eveniet esse. Officiis quidem perferendis qui.&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-1&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-3&quot; style=&quot;border: groove;&quot;&gt; &lt;p class=&quot;circle&quot;&gt;03&lt;/p&gt; &lt;h3&gt;certified teachers&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, consectetur?&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <ol> <li>Used bs-5,bootstrap.bundle.min.css</li> <li>This is the below output for this code <a href="https://i.stack.imgur.com/PVR4Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PVR4Y.png" alt="enter image description here" /></a></li> </ol> <p>3. This is the code of css</p> <pre><code>.circle { border-radius: 50%; width: 60px; height: 60px; padding: 10px; background: purple; border: 3px solid #000; display: flex; color: #fff; text-align: center; font: 28px arial, sans-serif; } </code></pre> <ol start="4"> <li>I tried various ways of flex, it did not work until I change margin</li> </ol> <p>Please help me, why this is not working</p>
[ { "answer_id": 74632287, "author": "Sanay Varghese", "author_id": 20193094, "author_profile": "https://Stackoverflow.com/users/20193094", "pm_score": -1, "selected": false, "text": "margin:auto m-auto .circle {\n margin:auto\n }\n m-auto <p class=\"circle text-center m-auto\">02</p>\n" }, { "answer_id": 74632608, "author": "gaetan-hexadog", "author_id": 20637850, "author_profile": "https://Stackoverflow.com/users/20637850", "pm_score": 2, "selected": true, "text": "text: center .circle display: flex justify-content: center" }, { "answer_id": 74632647, "author": "Sanay Varghese", "author_id": 20193094, "author_profile": "https://Stackoverflow.com/users/20193094", "pm_score": -1, "selected": false, "text": "dop chi <div className=\"col-lg-3 dop\" style={{ border: \"groove\" }}>\n <p className=\"circle text-center chi\">02</p>\n .dop {\n display: flex;\n flex-direction: column;\n}\n.chi {\n align-self: center;\n}\n" }, { "answer_id": 74632669, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "<div class=\"col-lg-3 d-flex flex-column align-items-center justify-content-center\"></div>\n" }, { "answer_id": 74632726, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 1, "selected": false, "text": ".circle {\n border-radius: 50%;\n width: 60px;\n height: 60px;\n padding: 10px;\n background: purple;\n border: 3px solid #000;\n display: flex;\n color: #fff;\n text-align: center;\n font: 28px arial, sans-serif;\n} <!-- Bootstrap CDN -->\n<link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" />\n\n<div class=\"row\">\n <div class=\"col-lg-3 \" style=\"border: groove;\">\n <!-- flexbox wrapper for circle -->\n <div class=\"d-flex justify-content-center\">\n <p class=\"circle col-xs-1 center-block\">01</p>\n </div>\n <h3 class=\"text-center\">trending courses</h3>\n <p class=\"text-center\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, consectetur?</p>\n </div>\n <div class=\"col-lg-1\"></div>\n <div class=\"col-lg-3\" style=\"border: groove;\">\n <!-- flexbox wrapper for circle -->\n <div class=\"d-flex justify-content-center\">\n <p class=\"circle text-center\">02</p>\n </div>\n <h3 class=\"text-center\">books&library</h3>\n <p class=\"text-center\">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit nostrum voluptates tempore, pariatur nobis tempora repellendus deserunt suscipit, sed ex nihil eum impedit maiores quia modi qui aut velit veritatis quam deleniti? Quasi dolor, asperiores\n ut cumque laboriosam accusamus eveniet esse. Officiis quidem perferendis qui.</p>\n </div>\n <div class=\"col-lg-1\">\n\n </div>\n <div class=\"col-lg-3\" style=\"border: groove;\">\n <!-- flexbox wrapper for circle -->\n <div class=\"d-flex justify-content-center\">\n <p class=\"circle\">03</p>\n </div>\n <h3 class=\"text-center\">certified teachers</h3>\n <p class=\"text-center\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, consectetur?</p>\n </div>\n</div> justify-content: center;" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14768620/" ]
74,632,019
<p>I need to extract a sequence of coma separated numbers after specific substring. When the substring is in the beginning of the string it works fine, but not when its in the middle.</p> <p>The regex <code>'Port':\ .([0-9]+)</code> works fine with the example below to get the value <code>2</code>.</p> <p>String example:</p> <pre><code>{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'} </code></pre> <p>But i need to get Field value, I dont care if its '[2,2]' or 2,2 (string or number)</p> <p>I tried various attempts with regex calculator, but couldnt find a solution to return the value after string in middle of the text. Any ideas? Please help. Thanks ahead, Nir</p>
[ { "answer_id": 74632080, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 1, "selected": false, "text": "print() ast.literal_eval() >>> import ast\n>>> d = ast.literal_eval(\"\"\"{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'}\"\"\")\n>>> d\n{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]', 'bar': '[9, 9]'}\n>>> d[\"Array\"]\n'[0, 0]'\n" }, { "answer_id": 74632325, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 3, "selected": true, "text": "import re\n\nstring = \"{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'}\"\n\noutput = re.findall(r\"\\'Field\\'\\: \\'\\[([0-9]+)\\,([0-9]+)\\]\\'\",string)\n\nprint(output)\n [('2', '2')]\n output = str(output).replace('[','').replace(']','').replace('(','').replace(')','').replace(' ','').replace('\\'','')\nprint(output)\n 2,2\n values = []\n\ndef get_values(mdict, values):\n pattern = r\"\\'Field\\'\\: \\'\\[([0-9]+)\\,([0-9]+)\\]\\'\"\n output = re.findall(pattern,mdict)\n output = str(output).replace('[','').replace(']','').replace('(','').replace(')','').replace(' ','').replace('\\'','')\n values.append(output)\n\n# get_values(mdict, values)\n\nfor x in df['param']:\n get_values(str(x), values)\n\ndf_temp = pd.DataFrame(values, columns=['Field'])\n\ndf.append(df_temp)\n" }, { "answer_id": 74634260, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 0, "selected": false, "text": "2,2 Field ' : , ] 'Field':\\s+'\\[([0-9]+,\\s*[0-9]+)]'\n 'Field': \\s+'\\[ [ ( [0-9]+,\\s*[0-9]+ , ) ]' import re\n\npattern = r\"'Field':\\s+'\\[([0-9]+,[0-9]+)]'\"\n\ns = \"{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'}\"\n\nm = re.search(pattern, s)\nif m:\n print(m.group(1))\n 2,2\n ] [ '[^']+':\\s+'(\\[)?([0-9]+(?:,\\s*[0-9]+)*)(?(1)\\])'\n import re\n\npattern = r\"'[^']+':\\s+'(\\[)?([0-9]+(?:,\\s*[0-9]+)*)(?(1)\\])'\"\ns = \"{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'}\"\nmatches = re.finditer(pattern, s)\n\nfor matchNum, match in enumerate(matches, start=1):\n print(match.group(2))\n 2\n0, 0\n2,2\n0, 0\n9, 9\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4342378/" ]
74,632,025
<p>So, I created a minigame bot on telegram. The bot just contains a fishing game, and it's already running. I want if a user fishes and gets a fish, the fish will be stored in a database. So the user can see what he got while fishing. Does this is require SQL?</p> <p>I haven't tried anything, because I don't understand about storing data in python. If there is a tutorial related to this, please share it in the comments. Thank you</p>
[ { "answer_id": 74633072, "author": "Lonami", "author_id": 4759433, "author_profile": "https://Stackoverflow.com/users/4759433", "pm_score": 1, "selected": false, "text": "json DATABASE = 'database.json' # (name or extension don't actually matter)\n\nimport json\n\n# loading\nwith open(DATABASE, 'r', encoding='utf-8') as fd:\n user_data = json.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'w', encoding='utf-8') as fd:\n json.dump(user_data, fd)\n pickle DATABASE = 'database.pickle' # (name or extension don't actually matter)\n\nimport pickle\n\n# loading\nwith open(DATABASE, 'rb') as fd:\n user_data = pickle.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'wb') as fd:\n pickle.dump(user_data, fd)\n sqlite3 sqlite3 sqlite3" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20146680/" ]
74,632,055
<p>I am trying to find the best property for centering elements. I am new so, i want to know from the best.</p> <p>I have asked a question about css and want to know what people think of it.</p>
[ { "answer_id": 74633072, "author": "Lonami", "author_id": 4759433, "author_profile": "https://Stackoverflow.com/users/4759433", "pm_score": 1, "selected": false, "text": "json DATABASE = 'database.json' # (name or extension don't actually matter)\n\nimport json\n\n# loading\nwith open(DATABASE, 'r', encoding='utf-8') as fd:\n user_data = json.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'w', encoding='utf-8') as fd:\n json.dump(user_data, fd)\n pickle DATABASE = 'database.pickle' # (name or extension don't actually matter)\n\nimport pickle\n\n# loading\nwith open(DATABASE, 'rb') as fd:\n user_data = pickle.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'wb') as fd:\n pickle.dump(user_data, fd)\n sqlite3 sqlite3 sqlite3" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645265/" ]
74,632,068
<p>I'm using Bootstrap to make two buttons so that when the screen width decreases, they divide the screen not horizontally, but vertically, something like in the picture <img src="https://i.stack.imgur.com/2PY7M.png"></p> <p>I tried this</p> <p>index.php:</p> <pre><code>&lt;div class=&quot;container-fluid&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md mw-100 bg-danger&quot;&gt;&lt;/div&gt; &lt;div class=&quot;col-md mw-100 bg-success&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>css:</p> <pre><code>[class*='col'] { min-height: 600px; } </code></pre> <p>But it overflows at the bottom when the width is less than 768px and I don't know how to fill the empty space below the buttons when the width is greater than 768px</p> <p>(sorry for the english, I'm using a translator)</p>
[ { "answer_id": 74633072, "author": "Lonami", "author_id": 4759433, "author_profile": "https://Stackoverflow.com/users/4759433", "pm_score": 1, "selected": false, "text": "json DATABASE = 'database.json' # (name or extension don't actually matter)\n\nimport json\n\n# loading\nwith open(DATABASE, 'r', encoding='utf-8') as fd:\n user_data = json.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'w', encoding='utf-8') as fd:\n json.dump(user_data, fd)\n pickle DATABASE = 'database.pickle' # (name or extension don't actually matter)\n\nimport pickle\n\n# loading\nwith open(DATABASE, 'rb') as fd:\n user_data = pickle.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'wb') as fd:\n pickle.dump(user_data, fd)\n sqlite3 sqlite3 sqlite3" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648217/" ]
74,632,086
<p>In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in <code>views.py</code> if the user already exists by checking <code>is_authenticated</code> upfront. If the user does not exist, then the form entries will be processed and the user will be created.</p> <p>The problem: if the user already exists, I would expect the condition <code>request.user.is_authenticated</code> to be True and the browser to be redirected to home. Instead, the evaluation goes on to process the form throwing (of course) the following error:</p> <p>Exception Value: duplicate key value violates unique constraint &quot;auth_user_username_key&quot; DETAIL: Key (username)=(john.doe) already exists.</p> <p>This is a sample of my <code>views.py</code>:</p> <pre><code>def register_user(request): if request.method == &quot;POST&quot;: if request.user.is_authenticated: messages.error(request, ('User already exists.')) return redirect('home') form = UserCreationForm(request.POST) if form.is_valid(): form.save() ... # do more stuff </code></pre> <p>What am I missing?</p>
[ { "answer_id": 74633072, "author": "Lonami", "author_id": 4759433, "author_profile": "https://Stackoverflow.com/users/4759433", "pm_score": 1, "selected": false, "text": "json DATABASE = 'database.json' # (name or extension don't actually matter)\n\nimport json\n\n# loading\nwith open(DATABASE, 'r', encoding='utf-8') as fd:\n user_data = json.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'w', encoding='utf-8') as fd:\n json.dump(user_data, fd)\n pickle DATABASE = 'database.pickle' # (name or extension don't actually matter)\n\nimport pickle\n\n# loading\nwith open(DATABASE, 'rb') as fd:\n user_data = pickle.load(fd)\n\nuser_data[1234] = 5 # pretend user 1234 scored 5 points\n\n# saving\nwith open(DATABASE, 'wb') as fd:\n pickle.dump(user_data, fd)\n sqlite3 sqlite3 sqlite3" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10966677/" ]
74,632,105
<p>I am beginning learning the basics of developing APIs and am following along with a video on YouTube by a developer named Ania Kubow. There are three javascript libraries in use which are ExpressJS, Cheerio &amp; Axios. I have picked up what she is telling us and going well enough. I am however, getting an error when executing the code so far. Below here is the main part of the example API:</p> <p>Note:The &quot;app&quot; variable is referring to Express JS</p> <pre><code>app.get('/news', (req, res) =&gt; { axios.get('https://www.theguardian.com/environment/climate-crisis') .then((response) =&gt; { // Store the html retrieved via the axios http GET request const html = response.data; // Load the retrieved html into the cheerio instance and store to $ cheerio selector const $ = cheerio.load(html); // DEBUG purpose stuff var loopCounter = 0; var climate_A_Elements = $('a:contains(climate)', html).length; console.log('Number of articles found: ' + climate_A_Elements); // // Get all articles that contain 'climate' in the &lt;a /&gt; element var allFoundArticles = $('a:contains(&quot;climate&quot;)', html); // Iterate through all found articles using cheerio forEach loop allFoundArticles.each(function () { // Assign article title and url it is located at to variables var title = $(this).text(); var url = $(this).attr('href'); // Push the previously defined vars to the previously defined array articlesData.push({ title, url, }); // Output the article details to page as response res.json(articlesData); // Add to loop count for debugging purposes and log in console loopCounter += 1; console.log('Loops: ' + loopCounter); }).catch(err =&gt; { console.log(err); }) }) }) </code></pre> <p>After completing one iteration of the Cheerio each loop, the application errors and gives the below error output:</p> <pre><code>node:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:393:5) at ServerResponse.setHeader (node:_http_outgoing:644:11) at ServerResponse.header (C:\Users\etomm\Downloads\Daniel\Dev\Web\climate-change-api\node_modules\express\lib\response.js:794:10) at ServerResponse.json (C:\Users\etomm\Downloads\Daniel\Dev\Web\climate-change-api\node_modules\express\lib\response.js:275:10) at Element.&lt;anonymous&gt; (C:\Users\etomm\Downloads\Daniel\Dev\Web\climate-change-api\index.js:65:21) at LoadedCheerio.each (C:\Users\etomm\Downloads\Daniel\Dev\Web\climate-change-api\node_modules\cheerio\lib\api\traversing.js:519:26) at C:\Users\etomm\Downloads\Daniel\Dev\Web\climate-change-api\index.js:52:30 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { code: 'ERR_HTTP_HEADERS_SENT' } Node.js v18.12.1 [nodemon] app crashed - waiting for file changes before starting... </code></pre> <p>I have of course, left a question as a comment on the video mentioned above, but realistically I don't expect to receive a response, so after trying to find the issue for a while decided to try here for some help and guidance.</p> <p>Any guidance would be greatly appreciated. If you require anything to help further please ask.</p> <p>Thankyou.</p> <p>I tried changing to the version of node installed on the video mentioned to see if it was a version issue, but it didn't solve anything. I tried refactoring the code and stepping through a few times with no results and tried searching the web but couldn't find the answer to this particular issue.</p>
[ { "answer_id": 74632235, "author": "Ailton", "author_id": 16636381, "author_profile": "https://Stackoverflow.com/users/16636381", "pm_score": -1, "selected": false, "text": "res.json(articlesData) app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n }).then(res.json(articlesData))\n .catch(err => {\n console.log(err);\n })\n })\n})\n" }, { "answer_id": 74632886, "author": "Asad Ahmed", "author_id": 10760218, "author_profile": "https://Stackoverflow.com/users/10760218", "pm_score": 1, "selected": false, "text": "app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n // artical data array\n const articlesData = [];\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store \n //to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach \n //loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined \n //array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n\n // Add to loop count for debugging purposes and log in \n //console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n })\n res.json(articlesData);\n }).catch(err => {\n console.log(err);\n })\n})\n" }, { "answer_id": 74633123, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 2, "selected": true, "text": "app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n res.json({message: \"this won't work\"});\n }\n});\n app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n // do whatever you need to in the loop\n }\n\n // respond once after the loop is finished\n res.json({message: \"this works\"});\n});\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n axios\n .get(\"https://www.theguardian.com/environment/climate-crisis\")\n .then((response) => {\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $(\"a:contains(climate)\", html).length;\n console.log(\"Number of articles found: \" + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n ///////////////////////////\n const articlesData = []; // <--------- Added\n ///////////////////////////\n\n allFoundArticles\n .each(function () {\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr(\"href\");\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log(\"Loops: \" + loopCounter);\n })\n\n // Output the article details to page as response\n\n //////////////////////////\n res.json(articlesData); // <--------- Moved down\n //////////////////////////\n });\n});\napp.listen(3000);\n $ curl localhost:3000/news | jq 'length'\n14\n$ curl localhost:3000/news | jq '.[0].title'\n\"Australia news Australia???s banks likely to reduce lending to regions and sectors at risk of climate change impacts, regulator says \"\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n axios.get(url).then(({data}) => {\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n })\n .catch(err => {\n res.status(500).json({message: err.message});\n });\n});\napp.listen(3000);\n async await app.get(\"/news\", async (req, res) => {\n try {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n const {data} = await axios.get(url);\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n }\n catch (err) {\n res.status(500).json({message: err.message});\n }\n});\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10072194/" ]
74,632,106
<ul> <li>I need to see the logs of all the pods in a deployment with N worker pods</li> <li>When I do <code>kubectl logs deployment/name --tail=0 --follow</code> the command syntax makes me assume that it will tail all pods in the deployment</li> <li>However when I go to process I don't see any output as expected until I manually view the logs for all N pods in the deployment</li> </ul> <h3>Does <code>kubectl log deployment/name</code> get all pods or just one pod?</h3>
[ { "answer_id": 74632235, "author": "Ailton", "author_id": 16636381, "author_profile": "https://Stackoverflow.com/users/16636381", "pm_score": -1, "selected": false, "text": "res.json(articlesData) app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n }).then(res.json(articlesData))\n .catch(err => {\n console.log(err);\n })\n })\n})\n" }, { "answer_id": 74632886, "author": "Asad Ahmed", "author_id": 10760218, "author_profile": "https://Stackoverflow.com/users/10760218", "pm_score": 1, "selected": false, "text": "app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n // artical data array\n const articlesData = [];\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store \n //to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach \n //loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined \n //array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n\n // Add to loop count for debugging purposes and log in \n //console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n })\n res.json(articlesData);\n }).catch(err => {\n console.log(err);\n })\n})\n" }, { "answer_id": 74633123, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 2, "selected": true, "text": "app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n res.json({message: \"this won't work\"});\n }\n});\n app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n // do whatever you need to in the loop\n }\n\n // respond once after the loop is finished\n res.json({message: \"this works\"});\n});\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n axios\n .get(\"https://www.theguardian.com/environment/climate-crisis\")\n .then((response) => {\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $(\"a:contains(climate)\", html).length;\n console.log(\"Number of articles found: \" + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n ///////////////////////////\n const articlesData = []; // <--------- Added\n ///////////////////////////\n\n allFoundArticles\n .each(function () {\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr(\"href\");\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log(\"Loops: \" + loopCounter);\n })\n\n // Output the article details to page as response\n\n //////////////////////////\n res.json(articlesData); // <--------- Moved down\n //////////////////////////\n });\n});\napp.listen(3000);\n $ curl localhost:3000/news | jq 'length'\n14\n$ curl localhost:3000/news | jq '.[0].title'\n\"Australia news Australia???s banks likely to reduce lending to regions and sectors at risk of climate change impacts, regulator says \"\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n axios.get(url).then(({data}) => {\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n })\n .catch(err => {\n res.status(500).json({message: err.message});\n });\n});\napp.listen(3000);\n async await app.get(\"/news\", async (req, res) => {\n try {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n const {data} = await axios.get(url);\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n }\n catch (err) {\n res.status(500).json({message: err.message});\n }\n});\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52074/" ]
74,632,110
<p>I'm using Ubuntu 20.04.5 LTS. Output of <code>python3 --version</code> command: <em>Python 3.8.10</em> When I type <code>pip</code> in terminal and press TAB, it responds with the following options: <strong>pip</strong>, <strong>pip3</strong>, <strong>pip3.10</strong> and <strong>pip3.8</strong></p> <p>But, when I use any of then with the <code>--version</code> flag, it all prints the same output, which is: <strong>pip 22.3.1 from /home/myuser/.local/lib/python3.8/site-packages/pip (python 3.8)</strong></p> <p>When I use &quot;pip list&quot; command, I can see the <em>&quot;virtualenv&quot;</em> package version(which is 20.17.0)</p> <p>Then I create my virtual environment using this following command: <code>python3 -m venv .env</code></p> <p>Then I activate it using <code>source .env/bin/activate</code> command</p> <p>Before installing the modules, I update virtual environment's pip, using the following command:</p> <pre><code>.env/bin/python3 -m pip install --upgrade pip </code></pre> <p>Also, I have a file called <em>requirements.txt</em> with the packages names I need in it:</p> <pre><code>wheel numpy matplotlib sklearn seaborn </code></pre> <p>So I install them using the following command:</p> <pre><code>.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517 </code></pre> <p>Finally, I try to run my python program using <em>&quot;.env/bin/python kmeans3.py&quot;</em> command, it prints this error:</p> <pre><code>Traceback (most recent call last): File &quot;kmeans3.py&quot;, line 10, in &lt;module&gt; from sklearn.cluster import KMeans ModuleNotFoundError: No module named 'sklearn' </code></pre> <p>obs: This is the first 12 lines of the file:</p> <pre><code>&quot;&quot;&quot; .env/bin/python3 -m pip install --upgrade pip .env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517 &quot;&quot;&quot; import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score from sklearn.preprocessing import MinMaxScaler </code></pre>
[ { "answer_id": 74632235, "author": "Ailton", "author_id": 16636381, "author_profile": "https://Stackoverflow.com/users/16636381", "pm_score": -1, "selected": false, "text": "res.json(articlesData) app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n }).then(res.json(articlesData))\n .catch(err => {\n console.log(err);\n })\n })\n})\n" }, { "answer_id": 74632886, "author": "Asad Ahmed", "author_id": 10760218, "author_profile": "https://Stackoverflow.com/users/10760218", "pm_score": 1, "selected": false, "text": "app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n // artical data array\n const articlesData = [];\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store \n //to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach \n //loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined \n //array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n\n // Add to loop count for debugging purposes and log in \n //console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n })\n res.json(articlesData);\n }).catch(err => {\n console.log(err);\n })\n})\n" }, { "answer_id": 74633123, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 2, "selected": true, "text": "app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n res.json({message: \"this won't work\"});\n }\n});\n app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n // do whatever you need to in the loop\n }\n\n // respond once after the loop is finished\n res.json({message: \"this works\"});\n});\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n axios\n .get(\"https://www.theguardian.com/environment/climate-crisis\")\n .then((response) => {\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $(\"a:contains(climate)\", html).length;\n console.log(\"Number of articles found: \" + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n ///////////////////////////\n const articlesData = []; // <--------- Added\n ///////////////////////////\n\n allFoundArticles\n .each(function () {\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr(\"href\");\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log(\"Loops: \" + loopCounter);\n })\n\n // Output the article details to page as response\n\n //////////////////////////\n res.json(articlesData); // <--------- Moved down\n //////////////////////////\n });\n});\napp.listen(3000);\n $ curl localhost:3000/news | jq 'length'\n14\n$ curl localhost:3000/news | jq '.[0].title'\n\"Australia news Australia???s banks likely to reduce lending to regions and sectors at risk of climate change impacts, regulator says \"\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n axios.get(url).then(({data}) => {\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n })\n .catch(err => {\n res.status(500).json({message: err.message});\n });\n});\napp.listen(3000);\n async await app.get(\"/news\", async (req, res) => {\n try {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n const {data} = await axios.get(url);\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n }\n catch (err) {\n res.status(500).json({message: err.message});\n }\n});\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15824843/" ]
74,632,112
<p>I want to create a trigger, but I'm getting an error.</p> <p>I have 2 tables STOK and STOK_HAREKET:</p> <ul> <li>STOK = (ID,URUN,FIYAT,MINIMUM,MAXIMUM)\</li> <li>STOK_HAREKET = (STOK_ID,FİYAT,GIRIS,CIKIS)\</li> </ul> <p>I want to build a trigger to STOK_HAREKET. On insert and update, the GIRIS and CIKIS ın STOK_HAREKET table is collected and submitted from the output and save this value to the MAXIMUM value ın the STOK table.</p> <pre class="lang-sql prettyprint-override"><code>CREATE TRIGGER T_STOK_BIU FOR STOK_HAREKET BEFORE INSERT OR UPDATE AS begin Set @gsum = ( SELECT SUM(GIRIS) FROM STOK_HAREKET WHERE STOK_ID = new.STOK_ID ); Set @csum = ( SELECT SUM(CIKIS) FROM STOK_HAREKET WHERE STOK_ID = new.STOK_ID ); Set @toplm = (@gsum-@csum) update STOK set MAKSIMUM = @toplm where ID = new.STOK_ID end </code></pre> <p>This code gives an error:</p> <pre class="lang-none prettyprint-override"><code>org.jkiss.dbeaver.model.sql.DBSQLException: SQL Error [335544634] [42000]: Dynamic SQL Error; SQL error code = -104; Token unknown - line 4, column 2; SET [SQLState:42000, ISC error code:335544634] at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:133) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:578) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$1(SQLQueryJob.java:487) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:173) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:494) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:913) at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:3760) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:123) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:173) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:121) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$ResultSetDataPumpJob.run(ResultSetViewer.java:5033) at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Caused by: java.sql.SQLSyntaxErrorException: Dynamic SQL Error; SQL error code = -104; Token unknown - line 4, column 2; SET [SQLState:42000, ISC error code:335544634] at org.firebirdsql.gds.ng.FbExceptionBuilder$Type$1.createSQLException(FbExceptionBuilder.java:534) at org.firebirdsql.gds.ng.FbExceptionBuilder.toFlatSQLException(FbExceptionBuilder.java:304) at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readStatusVector(AbstractWireOperations.java:140) at org.firebirdsql.gds.ng.wire.AbstractWireOperations.processOperation(AbstractWireOperations.java:204) at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readSingleResponse(AbstractWireOperations.java:171) at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readResponse(AbstractWireOperations.java:155) at org.firebirdsql.gds.ng.wire.AbstractWireOperations.readGenericResponse(AbstractWireOperations.java:257) at org.firebirdsql.gds.ng.wire.AbstractFbWireDatabase.readGenericResponse(AbstractFbWireDatabase.java:201) at org.firebirdsql.gds.ng.wire.version11.V11Statement.prepare(V11Statement.java:89) at org.firebirdsql.jdbc.FBStatement.prepareFixedStatement(FBStatement.java:881) at org.firebirdsql.jdbc.FBStatement.internalExecute(FBStatement.java:868) at org.firebirdsql.jdbc.FBStatement.executeImpl(FBStatement.java:496) at org.firebirdsql.jdbc.FBStatement.execute(FBStatement.java:482) at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.execute(JDBCStatementImpl.java:329) at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.lambda$0(JDBCStatementImpl.java:131) at org.jkiss.dbeaver.utils.SecurityManagerUtils.wrapDriverActions(SecurityManagerUtils.java:96) at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:131) ... 12 more Caused by: org.firebirdsql.jdbc.FBSQLExceptionInfo: Dynamic SQL Error </code></pre>
[ { "answer_id": 74632235, "author": "Ailton", "author_id": 16636381, "author_profile": "https://Stackoverflow.com/users/16636381", "pm_score": -1, "selected": false, "text": "res.json(articlesData) app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n }).then(res.json(articlesData))\n .catch(err => {\n console.log(err);\n })\n })\n})\n" }, { "answer_id": 74632886, "author": "Asad Ahmed", "author_id": 10760218, "author_profile": "https://Stackoverflow.com/users/10760218", "pm_score": 1, "selected": false, "text": "app.get('/news', (req, res) => {\n axios.get('https://www.theguardian.com/environment/climate-crisis')\n .then((response) => {\n // artical data array\n const articlesData = [];\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store \n //to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $('a:contains(climate)', html).length;\n console.log('Number of articles found: ' + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach \n //loop\n allFoundArticles.each(function () {\n\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr('href');\n\n // Push the previously defined vars to the previously defined \n //array\n articlesData.push({\n title,\n url,\n });\n\n // Output the article details to page as response\n\n\n // Add to loop count for debugging purposes and log in \n //console\n loopCounter += 1;\n console.log('Loops: ' + loopCounter);\n\n })\n res.json(articlesData);\n }).catch(err => {\n console.log(err);\n })\n})\n" }, { "answer_id": 74633123, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 2, "selected": true, "text": "app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n res.json({message: \"this won't work\"});\n }\n});\n app.get(\"/news\", (req, res) => {\n for (let i = 0; i < 2; i++) {\n // do whatever you need to in the loop\n }\n\n // respond once after the loop is finished\n res.json({message: \"this works\"});\n});\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n axios\n .get(\"https://www.theguardian.com/environment/climate-crisis\")\n .then((response) => {\n // Store the html retrieved via the axios http GET request\n const html = response.data;\n\n // Load the retrieved html into the cheerio instance and store to $ cheerio selector\n const $ = cheerio.load(html);\n\n // DEBUG purpose stuff\n var loopCounter = 0;\n var climate_A_Elements = $(\"a:contains(climate)\", html).length;\n console.log(\"Number of articles found: \" + climate_A_Elements);\n //\n\n // Get all articles that contain 'climate' in the <a /> element\n var allFoundArticles = $('a:contains(\"climate\")', html);\n\n // Iterate through all found articles using cheerio forEach loop\n ///////////////////////////\n const articlesData = []; // <--------- Added\n ///////////////////////////\n\n allFoundArticles\n .each(function () {\n // Assign article title and url it is located at to variables\n var title = $(this).text();\n var url = $(this).attr(\"href\");\n\n // Push the previously defined vars to the previously defined array\n articlesData.push({\n title,\n url,\n });\n\n // Add to loop count for debugging purposes and log in console\n loopCounter += 1;\n console.log(\"Loops: \" + loopCounter);\n })\n\n // Output the article details to page as response\n\n //////////////////////////\n res.json(articlesData); // <--------- Moved down\n //////////////////////////\n });\n});\napp.listen(3000);\n $ curl localhost:3000/news | jq 'length'\n14\n$ curl localhost:3000/news | jq '.[0].title'\n\"Australia news Australia???s banks likely to reduce lending to regions and sectors at risk of climate change impacts, regulator says \"\n const app = require(\"express\")();\nconst axios = require(\"axios\");\nconst cheerio = require(\"cheerio\");\n\napp.get(\"/news\", (req, res) => {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n axios.get(url).then(({data}) => {\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n })\n .catch(err => {\n res.status(500).json({message: err.message});\n });\n});\napp.listen(3000);\n async await app.get(\"/news\", async (req, res) => {\n try {\n const url = \"https://www.theguardian.com/environment/climate-crisis\";\n const {data} = await axios.get(url);\n const $ = cheerio.load(data);\n const articles = [...$('a:contains(\"climate\")')].map(e => ({\n title: $(e).text().trim(),\n url: $(e).attr(\"href\"),\n }));\n res.json(articles);\n }\n catch (err) {\n res.status(500).json({message: err.message});\n }\n});\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19864538/" ]
74,632,122
<pre><code>const names = [&quot;Daniel&quot;, &quot;Lucas&quot;, &quot;Gwen&quot;, &quot;Henry&quot;, &quot;Jasper&quot;]; </code></pre> <pre><code>const random = [&quot;hi&quot;, &quot;Lucas&quot;, &quot;apple&quot;, &quot;banana&quot;, &quot;Jasper&quot;, &quot;hello&quot;, &quot;meow&quot;]; </code></pre> <p>What I want here is to compare <code>names</code> and <code>random</code>, if there are any duplicates in random, remove them and have an outcome like this.</p> <pre><code>const newArr = [&quot;hi&quot;, &quot;apple&quot;, &quot;banana&quot;, &quot;hello&quot;, &quot;meow&quot;] </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74632164, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "const names = [\"Daniel\", \"Lucas\", \"Gwen\", \"Henry\", \"Jasper\"];\nconst random = [\"hi\", \"Lucas\", \"apple\", \"banana\", \"Jasper\", \"hello\", \"meow\"];\nconst result = random.filter(name => !names.includes(name))\nconsole.log(result)" }, { "answer_id": 74632175, "author": "LiquiD.S1nn3r", "author_id": 15175112, "author_profile": "https://Stackoverflow.com/users/15175112", "pm_score": 1, "selected": false, "text": "const newArr = random.filter(elem => !names.includes(elem))\n" }, { "answer_id": 74632330, "author": "KernelDeimos", "author_id": 4933274, "author_profile": "https://Stackoverflow.com/users/4933274", "pm_score": 1, "selected": false, "text": "const newArr = random.filter(name => ! names.includes(name));\n random names includes Map const names = [\"Daniel\", \"Lucas\", \"Gwen\", \"Henry\", \"Jasper\"];\nconst random = [\"hi\", \"Lucas\", \"apple\", \"banana\", \"Jasper\", \"hello\", \"meow\"];\n\nconst namesMap = new Map();\nfor ( const name of names ) namesMap.set(name, true);\n\nconst newArr = [];\nfor ( const rand of random ) {\n if ( namesMap.has(rand) ) continue;\n newArr.push(rand);\n}\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14489531/" ]
74,632,146
<p>Is there a way to kill several processes faster?</p> <pre><code>TASKKILL /F /IM process1.exe TASKKILL /F /IM process2.exe TASKKILL /F /IM process3.exe TASKKILL /F /IM process4.exe TASKKILL /F /IM process5.exe </code></pre> <p>Instead of waiting for the previous process to finish, finish them at the same time, or is it not possible in this way? I tried using a single line with &quot;&amp;&quot; but it is the same, sequential.</p>
[ { "answer_id": 74632164, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "const names = [\"Daniel\", \"Lucas\", \"Gwen\", \"Henry\", \"Jasper\"];\nconst random = [\"hi\", \"Lucas\", \"apple\", \"banana\", \"Jasper\", \"hello\", \"meow\"];\nconst result = random.filter(name => !names.includes(name))\nconsole.log(result)" }, { "answer_id": 74632175, "author": "LiquiD.S1nn3r", "author_id": 15175112, "author_profile": "https://Stackoverflow.com/users/15175112", "pm_score": 1, "selected": false, "text": "const newArr = random.filter(elem => !names.includes(elem))\n" }, { "answer_id": 74632330, "author": "KernelDeimos", "author_id": 4933274, "author_profile": "https://Stackoverflow.com/users/4933274", "pm_score": 1, "selected": false, "text": "const newArr = random.filter(name => ! names.includes(name));\n random names includes Map const names = [\"Daniel\", \"Lucas\", \"Gwen\", \"Henry\", \"Jasper\"];\nconst random = [\"hi\", \"Lucas\", \"apple\", \"banana\", \"Jasper\", \"hello\", \"meow\"];\n\nconst namesMap = new Map();\nfor ( const name of names ) namesMap.set(name, true);\n\nconst newArr = [];\nfor ( const rand of random ) {\n if ( namesMap.has(rand) ) continue;\n newArr.push(rand);\n}\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17038199/" ]
74,632,153
<p>I'm running into a few problems defining a surjective predicate for maps and functions.</p> <pre><code>predicate isTotal&lt;G(!new), B(!new)&gt;(f:G -&gt; B) reads f.reads; { forall g:G :: f.requires(g) } predicate Surjective&lt;A(!new), B(!new)&gt;(f: A -&gt; B) requires isTotal(f) { forall b: B :: exists a: A :: f(a) == b } predicate isTotalMap&lt;G(!new), B(!new)&gt;(m:map&lt;G,B&gt;) { forall g:G :: g in m } predicate mapSurjective&lt;U(!new), V(!new)&gt;(m: map&lt;U,V&gt;) requires forall u: U :: u in m.Keys { forall x: V :: exists a: U :: m[a] == x } </code></pre> <p>These definitions seems to work somewhat. However, they fail to verify the following setups.</p> <pre><code>datatype Color = Blue | Yellow | Green | Red function toRed(x: Color): Color { Red } function shiftColor(x: Color): Color { match x { case Red =&gt; Blue case Blue =&gt; Yellow case Yellow =&gt; Green case Green =&gt; Red } } lemma TestSurjective() { assert isTotal(toRed); assert isTotal(shiftColor); var toRedm := map[Red := Red, Blue := Red, Yellow := Red, Green := Red]; var toShiftm := map[Red := Blue, Blue := Yellow, Yellow := Green, Green := Red]; // assert Surjective(toRed); //should fail // assert Surjective(shiftColor); //should succeed // assert mapSurjective(toRedm); //should fail // assert forall u: Color :: u in toShiftm.Keys; assert isTotalMap(toShiftm); //also fails assume forall u: Color :: u in toShiftm.Keys; assert mapSurjective(toShiftm); // should succeed } </code></pre> <ol> <li><p>I assume the reason the maps fail the totality requirement defined in mapSurjective is because that the maps are potentially heap objects and Dafny isn't bothering to keep track of what is in them? Even if I assume the precondition the predicate still fails even though it should pass.</p> </li> <li><p>For the function case <code>assert Surjective(shiftColor)</code> also fails. For types with infinite cardinality I could understand it failing, but I feel like it should be possible to evaluate for finite types.</p> </li> </ol>
[ { "answer_id": 74633567, "author": "Hath995", "author_id": 821989, "author_profile": "https://Stackoverflow.com/users/821989", "pm_score": 0, "selected": false, "text": "lemma TotalColorMapIsTotal<B>(m: map<Color, B>) \n requires m.Keys == {Red, Blue, Green, Yellow}\n // ensures forall u: Color :: u in m\n ensures isTotalMap(m)\n{\n forall u: Color | true\n ensures u in m\n {\n if u.Red? {\n assert u in m;\n }\n }\n}\n\nlemma ColorMapIsOnto<A>(m: map<A, Color>) \n requires m.Values == {Red, Blue, Green, Yellow}\n ensures forall u: Color :: u in m.Values\n{\n\n forall u: Color | true\n ensures u in m.Values\n {\n if u.Red? {\n assert u in m.Values;\n }\n }\n}\n assert toShiftm[Red] == Blue;\n assert toShiftm[Blue] == Yellow;\n assert toShiftm[Yellow] == Green;\n assert toShiftm[Green] == Red;\n\n TotalColorMapIsTotal(toShiftm);\n ColorMapIsOnto(toShiftm);\n assert mapSurjective(toShiftm);\n assert shiftColor(Green) == Red;\n assert shiftColor(Red) == Blue;\n assert shiftColor(Blue) == Yellow;\n assert shiftColor(Yellow) == Green;\n assert Surjective(shiftColor); //should succeed\n" }, { "answer_id": 74661338, "author": "Mikaël Mayer", "author_id": 1287856, "author_profile": "https://Stackoverflow.com/users/1287856", "pm_score": 2, "selected": true, "text": "\n// Note: to be useful, the function's type should be --> (a broken arrow)\n// indicating the function CAN have preconditions.\n// Otherwise, -> is already a subset type of --> whose constraint is exactly your predicate\n// so it would be a typing issue to provide a non-total function.\n// See https://dafny.org/latest/DafnyRef/DafnyRef#sec-arrow-subset-types\npredicate isTotal<G(!new), B(!new)>(f:G --> B)\n// reads f.reads // You don't need this, because f is not declared as being able to read a function\n{\n forall g:G :: f.requires(g)\n}\n\n// Passthrough identity function used for triggers\nfunction Id<T>(t: T): T { t }\n\npredicate Surjective<A(!new), B(!new)>(f: A -> B) \n{\n // If not using Id(b), the first forall does not have a trigger\n // and get hard to prove. Not impossible, but extremely lengthy\n forall b: B :: exists a: A :: f(a) == Id(b)\n}\n\npredicate isTotalMap<G(!new), B(!new)>(m:map<G,B>)\n{\n forall g: G :: g in m\n}\n\npredicate mapSurjective<U(!new), V(!new)>(m: map<U,V>)\n requires forall u: U :: u in m.Keys\n{\n // If not using Id(b), the first forall does not have a trigger\n // and get hard to prove. Not impossible, but extremely lengthy\n forall x: V :: exists a: U :: m[a] == Id(x)\n}\n\ndatatype Color = Blue | Yellow | Green | Red\n\nfunction toRed(x: Color): Color {\n Red\n}\n\nfunction shiftColor(x: Color): Color {\n match x {\n case Red => Blue\n case Blue => Yellow\n case Yellow => Green\n case Green => Red\n }\n}\nfunction partialFunction(x: Color): Color\n requires x.Red? {\n x\n}\n\nlemma TestWrong() {\n // When trying to prove an assertion with a proof, use assert ... by like this:\n assert !isTotal(partialFunction) by {\n // If we were using ->, we would get \"Value does not satisfies Color -> Color\"*\n // But here we can just exhibit a counter-example that disproves the forall \n assert !partialFunction.requires(Blue);\n\n // A longer proof could be done by contradiction like this:\n if(isTotal(partialFunction)) {\n assert forall c: Color :: partialFunction.requires(c);\n assert partialFunction.requires(Blue); // it can instantiate the forall above.\n assert false; // We get a contradiction\n }\n assert !isTotal(partialFunction);// A ==> false means !A\n }\n}\n\nlemma TestSurjective() {\n assert isTotal(toRed);\n assert isTotal(shiftColor);\n var toRedm := map[Red := Red, Blue := Red, Yellow := Red, Green := Red];\n var toShiftm := map[Red := Blue, Blue := Yellow, Yellow := Green, Green := Red];\n assert !Surjective(toRed) by {\n if(Surjective(toRed)) {\n var _ := Id(Blue);\n }\n }\n assert Surjective(shiftColor) by {\n if(!Surjective(shiftColor)) {\n var _ := Id(Blue); // We need to trigger the condition of surjective so that Dafny is happy with the below:\n assert !forall b: Color :: exists a: Color :: shiftColor(a) == Id(b);\n assert exists b: Color :: forall a: Color :: shiftColor(a) != Id(b);\n var b : Color :| forall a: Color :: shiftColor(a) != Id(b);\n assert shiftColor(shiftColor(shiftColor(shiftColor(b)))) == Id(b);\n assert false;\n }\n }\n assert forall c: Color :: c in toRedm by {\n if(!forall c :: c in toRedm) {\n assert exists c :: c !in toRedm;\n var c :| c !in toRedm;\n assert c != Red;// Dafny picks up from here\n assert false;\n }\n }\n assert !mapSurjective(toRedm) by {\n if(mapSurjective(toRedm)) {\n assert forall x :: exists a :: toRedm[a] == Id(x);\n var _ := Id(Blue); // Will instantiate the axiom above with x == Blue\n assert exists a :: toRedm[a] == Id(Blue); // Not needed, but Dafny can prove this.\n assert false;\n }\n }\n assert forall u: Color :: u in toShiftm.Keys by {\n if(!forall u: Color :: u in toShiftm.Keys) {\n assert exists u :: u !in toShiftm.Keys;\n var u :| u !in toShiftm.Keys;\n assert u != Red; // Dafny can pick up from here\n assert false;\n }\n }\n assert isTotalMap(toShiftm); //also fails\n assert forall u: Color :: u in toShiftm.Keys;\n assert mapSurjective(toShiftm) by {\n if(!mapSurjective(toShiftm)) {\n var _ := Id(Red); // Necessary so that Dafny understands that the next forall is equivalent\n assert !forall x :: exists a :: toShiftm[a] == Id(x);\n assert exists x :: forall a :: toShiftm[a] != Id(x);\n var x :| forall a :: toShiftm[a] != Id(x);\n assert forall b :: exists a :: toShiftm[a] == Id(b) by {\n forall b: Color ensures exists a :: toShiftm[a] == Id(b) {\n var a := toShiftm[toShiftm[toShiftm[b]]];\n assert toShiftm[toShiftm[toShiftm[toShiftm[b]]]] == Id(b);\n }\n }\n assert exists a :: toShiftm[a] == Id(x);\n var b :| toShiftm[b] == Id(x);\n assert false;\n }\n }\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821989/" ]
74,632,174
<p>I'm following this <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-dynamo-db.html" rel="nofollow noreferrer">AWS Tutorial</a> to access a DynamoDB using https requests. Using the provided JavaScript example does work, so the API Gateway configuration seems to work. I can send requests using curl and get the items of the table: <code>curl -v https://xxxxxxxx.execute-api.us-west-2.amazonaws.com/items</code>.</p> <p>However, I'm struggling to build the lambda in rust. This is my not working example:</p> <pre class="lang-rust prettyprint-override"><code>use lambda_runtime::{service_fn, Error, LambdaEvent}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = &quot;camelCase&quot;)] pub struct Event { pub request_context: RequestContext, } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = &quot;camelCase&quot;)] pub struct RequestContext { pub event_type: EventType, pub route_key: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = &quot;UPPERCASE&quot;)] pub enum EventType { Connect, Disconnect, } #[derive(Serialize)] struct Response { req_id: String, msg: String, } pub(crate) async fn my_handler(event: LambdaEvent&lt;Event&gt;) -&gt; Result&lt;Response, Error&gt; { let result = event.payload.request_context.route_key; let resp = Response { req_id: event.context.request_id, msg: format!(&quot;{}&quot;, result), }; Ok(resp) } #[tokio::main] async fn main() -&gt; Result&lt;(), Error&gt; { let func = service_fn(my_handler); lambda_runtime::run(func).await?; Ok(()) } </code></pre> <p>The error I got is <code>{&quot;message&quot;:&quot;Internal Server Error&quot;}</code>. I need to access the <code>routeKey</code>, as they do in the provided JavaScript example:</p> <pre><code>exports.handler = async (event, context) =&gt; { let body; let statusCode = 200; const headers = { &quot;Content-Type&quot;: &quot;application/json&quot; }; try { switch (event.routeKey) { case &quot;DELETE /items/{id}&quot;: break; /// do something default: break; } //... } </code></pre> <p>I suggest the error is based on the struct, which can not be serialized?</p> <p>Edit: The actual payload, using <code>println!(&quot;payload: {}&quot;, event.payload)</code>with an <code>LambdaEvent&lt;Event&gt;</code>.</p> <pre class="lang-json prettyprint-override"><code>payload: { &quot;headers&quot;: { &quot;accept&quot;: &quot;*/*&quot;, &quot;content-length&quot;: &quot;0&quot;, &quot;host&quot;: &quot;xxxxxx.execute-api.us-west-2.amazonaws.com&quot;, &quot;user-agent&quot;: &quot;curl/7.81.0&quot;, &quot;x-amzn-trace-id&quot;: &quot;Root=x-xxxxxxx-xxxxxxxx&quot;, &quot;x-forwarded-for&quot;: &quot;xx.xxx.xxxx.xxx&quot;, &quot;x-forwarded-port&quot;: &quot;443&quot;, &quot;x-forwarded-proto&quot;: &quot;https&quot; }, &quot;isBase64Encoded&quot;: false, &quot;rawPath&quot;: &quot;/items&quot;, &quot;rawQueryString&quot;: &quot;&quot;, &quot;requestContext&quot;: { &quot;accountId&quot;: &quot;xxxxxxxxxx&quot;, &quot;apiId&quot;: &quot;xxxxxxxxxx&quot;, &quot;domainName&quot;: &quot;xxxxxxxxx.execute-api.us-west-2.amazonaws.com&quot;, &quot;domainPrefix&quot;: &quot;xxxxxxxx&quot;, &quot;http&quot;: { &quot;method&quot;: &quot;GET&quot;, &quot;path&quot;: &quot;/items&quot;, &quot;protocol&quot;: &quot;HTTP/1.1&quot;, &quot;sourceIp&quot;: &quot;xx.xxxx.xxx.xx&quot;, &quot;userAgent&quot;: &quot;curl/7.81.0&quot; }, &quot;requestId&quot;: &quot;xxxxxxxxxxx&quot;, &quot;routeKey&quot;: &quot;GET /items&quot;, &quot;stage&quot;: &quot;$default&quot;, &quot;time&quot;: &quot;01/Dec/2022:08:07:39 +0000&quot;, &quot;timeEpoch&quot;: 1669882059705 }, &quot;routeKey&quot;: &quot;GET /items&quot;, &quot;version&quot;: &quot;2.0&quot; } </code></pre>
[ { "answer_id": 74633261, "author": "bddap", "author_id": 4225678, "author_profile": "https://Stackoverflow.com/users/4225678", "pm_score": 0, "selected": false, "text": "{\n \"eventType\": ...,\n \"routeKey\": ...\n}\n {\n \"requestContext\": {\n \"eventType\": ...,\n \"routeKey\": ...\n }\n}\n use lambda_runtime::{service_fn, Error, LambdaEvent};\nuse serde::{Deserialize, Serialize};\n\n#[derive(Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Event {\n pub event_type: EventType,\n pub route_key: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum EventType {\n Connect,\n Disconnect,\n}\n\n#[derive(Serialize)]\nstruct Response {\n req_id: String,\n msg: String,\n}\n\npub(crate) async fn my_handler(event: LambdaEvent<Event>) -> Result<Response, Error> {\n let result = event.payload.route_key;\n let resp = Response {\n req_id: event.context.request_id,\n msg: format!(\"{}\", result),\n };\n Ok(resp)\n}\n\n#[tokio::main]\nasync fn main() -> Result<(), Error> {\n let func = service_fn(my_handler);\n lambda_runtime::run(func).await?;\n Ok(())\n}\n async fn my_handler(event: LambdaEvent<serde_json::Value>) -> Result<Response, Error> {\n eprintln!(\"{}\", serde_json::to_string_pretty(&event.payload).unwrap());\n panic!()\n}\n" }, { "answer_id": 74646091, "author": "bddap", "author_id": 4225678, "author_profile": "https://Stackoverflow.com/users/4225678", "pm_score": 2, "selected": true, "text": "eventType" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12072774/" ]
74,632,179
<p>I am trying to create an array to object, it's working fine now. But, there is a dependency in to the object <strong>{ ids: [], items: {} }</strong> Before I have declared the object with the required properties. I am trying to achieve the same thing without the object dependency at the beginning, initially it will be the <strong>{}</strong> not <strong>{ ids: [], items: {} }</strong></p> <pre><code>import { v4 as id } from &quot;uuid&quot;; export const createItem = (name) =&gt; { return { id: id(), name, packed: false }; }; let items = [&quot;Backpack&quot;, &quot;Vitamins&quot;, &quot;Kindle&quot;].map((x) =&gt; createItem(x)); console.log(items); const converter = items.reduce( (obj, item) =&gt; { obj.ids.push(item.id); obj.items[item.id] = item; return obj; }, { ids: [], items: {} } ); console.log(converter); </code></pre>
[ { "answer_id": 74632335, "author": "James", "author_id": 535480, "author_profile": "https://Stackoverflow.com/users/535480", "pm_score": 0, "selected": false, "text": "const thing = Object.fromEntries(\n items.map(i => [i.id, i])\n);\nconst converter = {ids: Object.keys(thing), items: thing};\n" }, { "answer_id": 74632344, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "??= ids items undefined Crypto.randomUUID() // import { v4 as id } from \"uuid\";\n// UUIDv4 in the browser:\nconst id = crypto.randomUUID.bind(crypto);\n\nconst createItem = (name) => ({\n id: id(),\n name,\n packed: false,\n});\n\nconst items = [\"Backpack\", \"Vitamins\", \"Kindle\"].map(createItem);\n\nconst result = items.reduce(\n (obj, item) => {\n (obj.ids ??= []).push(item.id);\n (obj.items ??= {})[item.id] = item;\n return obj;\n },\n {},\n);\n\nconsole.log(result);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7940824/" ]
74,632,184
<p>I have an array <code>a</code> with shape <code>(43,9)</code>. I want to plot all rows of this array in one diagram. for this I used the following code:</p> <pre><code>plt.plot(a) </code></pre> <p>it produces this diagram but I think it is wrong: <a href="https://i.stack.imgur.com/ILmJ1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ILmJ1.png" alt="enter image description here" /></a></p> <p>I put part of <code>a</code> here:</p> <pre><code>30.2682 30.4287 30.4531 30.4675 30.4784 30.4893 30.5002 30.511 30.5219 28.3204 29.4246 30.5289 31.5486 31.8152 31.9301 32.0395 32.1488 32.2582 29.884 30.4592 31.0343 31.4055 31.4843 31.5157 31.549 31.5823 31.6157 29.5203 30.0669 30.6135 30.9845 31.0889 31.1244 31.1599 31.1954 31.2309 30.2158 30.6971 31.1784 31.4935 31.5697 31.6017 31.6336 31.6655 31.6974 </code></pre> <p>how can I show all rows of <code>a</code> as a curve in one plot in python?</p>
[ { "answer_id": 74632335, "author": "James", "author_id": 535480, "author_profile": "https://Stackoverflow.com/users/535480", "pm_score": 0, "selected": false, "text": "const thing = Object.fromEntries(\n items.map(i => [i.id, i])\n);\nconst converter = {ids: Object.keys(thing), items: thing};\n" }, { "answer_id": 74632344, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "??= ids items undefined Crypto.randomUUID() // import { v4 as id } from \"uuid\";\n// UUIDv4 in the browser:\nconst id = crypto.randomUUID.bind(crypto);\n\nconst createItem = (name) => ({\n id: id(),\n name,\n packed: false,\n});\n\nconst items = [\"Backpack\", \"Vitamins\", \"Kindle\"].map(createItem);\n\nconst result = items.reduce(\n (obj, item) => {\n (obj.ids ??= []).push(item.id);\n (obj.items ??= {})[item.id] = item;\n return obj;\n },\n {},\n);\n\nconsole.log(result);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11013499/" ]
74,632,214
<p>I have a problem, I am programming in C and it turns out that I am copying some characters from one string to another but I do it manually, you know with a function that it creates, but I want to know if there is any standard C function that allows me to do that, I will put An example so you can understand what I'm trying to say:</p> <pre><code>char str1[] = &quot;123copy321&quot;; char str2[5]; theFunctionINeed(str1, str2, 3, 6); //Copy from str1[3] to str1[6] printf(&quot;%s\n&quot;, str1); printf(&quot;%s\n&quot;, str2); </code></pre> <p>and the result would be:</p> <pre class="lang-none prettyprint-override"><code>123copy321 copy </code></pre> <p>I hope you can help me, thank you</p>
[ { "answer_id": 74632335, "author": "James", "author_id": 535480, "author_profile": "https://Stackoverflow.com/users/535480", "pm_score": 0, "selected": false, "text": "const thing = Object.fromEntries(\n items.map(i => [i.id, i])\n);\nconst converter = {ids: Object.keys(thing), items: thing};\n" }, { "answer_id": 74632344, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "??= ids items undefined Crypto.randomUUID() // import { v4 as id } from \"uuid\";\n// UUIDv4 in the browser:\nconst id = crypto.randomUUID.bind(crypto);\n\nconst createItem = (name) => ({\n id: id(),\n name,\n packed: false,\n});\n\nconst items = [\"Backpack\", \"Vitamins\", \"Kindle\"].map(createItem);\n\nconst result = items.reduce(\n (obj, item) => {\n (obj.ids ??= []).push(item.id);\n (obj.items ??= {})[item.id] = item;\n return obj;\n },\n {},\n);\n\nconsole.log(result);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646496/" ]
74,632,245
<p>I am using a flexbox on my site to display post previews as tiles. Each one is a fixed size (384*384px) and displays as a grid that fits as many tiles in each row as it can horizontally and it rearranges itself dynamically as the page is resized. This is the current CSS for this:</p> <pre class="lang-css prettyprint-override"><code>.post-list { display: flex; flex-wrap: wrap; } .post-tile { flex: 0 0 384px; width: 384px; height: 384px; margin: 10px; padding: 30px; box-sizing: border-box; overflow: hidden; border-radius: 32px; } </code></pre> <p>I would like it to do one extra thing though if possible: If the window is narrower than the width of one of the tiles I would like it to resize the tiles down to fit in the screen while also keeping the height and width the same, but I don't know how to accomplish this.</p> <p><a href="https://jsfiddle.net/r1fqdxuo/2/" rel="nofollow noreferrer">Here is a JS Fiddle</a> with this CSS filled out with a few basic tiles.</p>
[ { "answer_id": 74632335, "author": "James", "author_id": 535480, "author_profile": "https://Stackoverflow.com/users/535480", "pm_score": 0, "selected": false, "text": "const thing = Object.fromEntries(\n items.map(i => [i.id, i])\n);\nconst converter = {ids: Object.keys(thing), items: thing};\n" }, { "answer_id": 74632344, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "??= ids items undefined Crypto.randomUUID() // import { v4 as id } from \"uuid\";\n// UUIDv4 in the browser:\nconst id = crypto.randomUUID.bind(crypto);\n\nconst createItem = (name) => ({\n id: id(),\n name,\n packed: false,\n});\n\nconst items = [\"Backpack\", \"Vitamins\", \"Kindle\"].map(createItem);\n\nconst result = items.reduce(\n (obj, item) => {\n (obj.ids ??= []).push(item.id);\n (obj.items ??= {})[item.id] = item;\n return obj;\n },\n {},\n);\n\nconsole.log(result);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20141464/" ]
74,632,313
<p>Can I somehow delete a value from a dictionary using its key? The function <code>del_contact</code> is supposed to delete a <code>contact</code> using only the name of the contact, but unfortunately I have the dictionary and the value, but not the key. How can this be solved?</p> <pre class="lang-py prettyprint-override"><code>my_contacts = { 1: { &quot;Name&quot;: &quot;Tom Jones&quot;, &quot;Number&quot;: &quot;911&quot;, &quot;Birthday&quot;: &quot;22.10.1995&quot;, &quot;Address&quot;: &quot;212 street&quot; }, 2: { &quot;Name&quot;: &quot;Bob Marley&quot;, &quot;Number&quot;: &quot;0800838383&quot;, &quot;Birthday&quot;: &quot;22.10.1991&quot;, &quot;Address&quot;: &quot;31 street&quot; } } def add_contact(): user_input = int(input(&quot;please enter how many contacts you wanna add: &quot;)) index = len(my_contacts) + 1 for _ in range(user_input): details = {} name = input(&quot;Enter the name: &quot;) number = input(&quot;Enter the number: &quot;) birthday = input(&quot;Enter the birthday&quot;) address = input(&quot;Enter the address&quot;) details[&quot;Name&quot;] = name details[&quot;Number&quot;] = number details[&quot;Birthday&quot;] = birthday details[&quot;Address&quot;] = address my_contacts[index] = details index += 1 print(my_contacts) def del_contact(): user_input = input(&quot;Please enter the name of the contact you want to delete: &quot;) my_contacts.pop(user_input) add_contact() print(my_contacts) </code></pre> <p>The problem is that my key of the dictionary is <code>1</code> or <code>Name</code>, and I want to be able to remove the contact using only the value of <code>Name</code>.</p>
[ { "answer_id": 74632391, "author": "Nimrod Shanny", "author_id": 20631164, "author_profile": "https://Stackoverflow.com/users/20631164", "pm_score": 2, "selected": true, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\nuser_input = \"Tom Jones\"\n\nmy_contacts = {key: value for key, value in my_contacts.items() if value[\"Name\"] != user_input}\n" }, { "answer_id": 74632460, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 0, "selected": false, "text": "def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for k, v in my_contacts.items(): # Need both key and value, we test key, delete by value\n if v[\"Name\"] == user_input:\n del my_contacts[k]\n break # Deleted one item, stop now (we'd RuntimeError if iteration continued)\n else:\n # Optionally raise exception or print error indicating name wasn't found\n dict def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n to_delete = [k for k, v in my_contacts.items() if v[\"Name\"] == user_input]\n if not to_delete:\n # Optionally raise exception or print error indicating name wasn't found\n for k in to_delete:\n del my_contacts[k]\n dict def del_contact():\n global my_contacts # Assignment requires explicitly declared use of global\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n my_contacts = {k: v for k, v in my_contacts.items() if v[\"Name\"] != user_input} # Flip test, build new dict\n # Detecting no matches is more annoying here (it's basically comparing\n # length before and after), so I'm omitting it\n" }, { "answer_id": 74632542, "author": "CodeKorn", "author_id": 10882128, "author_profile": "https://Stackoverflow.com/users/10882128", "pm_score": 0, "selected": false, "text": "range def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for i in range(1,len(my_contacts)+1):\n if my_contacts[i]['Name'] == user_input:\n del my_contacts[i]\n break\n Tom Jones dict index = len(my_contacts) + 1 my_contacts[index] = details \"Name\": \"Bob Marley\"" }, { "answer_id": 74632628, "author": "pizoooo", "author_id": 10902484, "author_profile": "https://Stackoverflow.com/users/10902484", "pm_score": 0, "selected": false, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\n\ndef add_contact():\n user_input = int(input(\"please enter how many contacts you wanna add: \"))\n index = len(my_contacts) + 1\n for _ in range(user_input):\n details = {}\n name = input(\"Enter the name: \")\n number = input(\"Enter the number: \")\n birthday = input(\"Enter the birthday\")\n address = input(\"Enter the address\")\n details[\"Name\"] = name\n details[\"Number\"] = number\n details[\"Birthday\"] = birthday\n details[\"Address\"] = address\n my_contacts[index] = details\n index += 1\n print(my_contacts)\n\nadd_contact()\n\nprint(my_contacts)\ndef del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n values = [key for key in my_contacts.keys() if user_input in my_contacts[key].values()]\n for value in values:\n my_contacts.pop(value)\ndel_contact()\nprint(my_contacts)\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 2: {'Name': 'Bob Marley', 'Number': '0800838383', 'Birthday': '22.10.1991', 'Address': '31 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n Please enter the name of the contact you want to delete: Bob Marley\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20642580/" ]
74,632,315
<p>How can I change the size of an <code>icon()</code> in shiny dashboard?</p> <pre><code>library(shiny) library(shinydashboardPlus) shinyApp( ui = dashboardPage(skin = &quot;purple&quot;, options = list(sidebarExpandOnHover = TRUE), header = dashboardHeader( controlbarIcon = shiny::icon(&quot;filter&quot;) ), sidebar = dashboardSidebar(), body = dashboardBody( tags$style(&quot;.fa-filter {color:red;size:26px}&quot;), ), controlbar = dashboardControlbar( id = &quot;controlbar&quot;, collapsed = FALSE, overlay = TRUE, skin = &quot;light&quot;, pinned = T ) ), server = function(input, output, session) { } ) </code></pre>
[ { "answer_id": 74632391, "author": "Nimrod Shanny", "author_id": 20631164, "author_profile": "https://Stackoverflow.com/users/20631164", "pm_score": 2, "selected": true, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\nuser_input = \"Tom Jones\"\n\nmy_contacts = {key: value for key, value in my_contacts.items() if value[\"Name\"] != user_input}\n" }, { "answer_id": 74632460, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 0, "selected": false, "text": "def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for k, v in my_contacts.items(): # Need both key and value, we test key, delete by value\n if v[\"Name\"] == user_input:\n del my_contacts[k]\n break # Deleted one item, stop now (we'd RuntimeError if iteration continued)\n else:\n # Optionally raise exception or print error indicating name wasn't found\n dict def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n to_delete = [k for k, v in my_contacts.items() if v[\"Name\"] == user_input]\n if not to_delete:\n # Optionally raise exception or print error indicating name wasn't found\n for k in to_delete:\n del my_contacts[k]\n dict def del_contact():\n global my_contacts # Assignment requires explicitly declared use of global\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n my_contacts = {k: v for k, v in my_contacts.items() if v[\"Name\"] != user_input} # Flip test, build new dict\n # Detecting no matches is more annoying here (it's basically comparing\n # length before and after), so I'm omitting it\n" }, { "answer_id": 74632542, "author": "CodeKorn", "author_id": 10882128, "author_profile": "https://Stackoverflow.com/users/10882128", "pm_score": 0, "selected": false, "text": "range def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for i in range(1,len(my_contacts)+1):\n if my_contacts[i]['Name'] == user_input:\n del my_contacts[i]\n break\n Tom Jones dict index = len(my_contacts) + 1 my_contacts[index] = details \"Name\": \"Bob Marley\"" }, { "answer_id": 74632628, "author": "pizoooo", "author_id": 10902484, "author_profile": "https://Stackoverflow.com/users/10902484", "pm_score": 0, "selected": false, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\n\ndef add_contact():\n user_input = int(input(\"please enter how many contacts you wanna add: \"))\n index = len(my_contacts) + 1\n for _ in range(user_input):\n details = {}\n name = input(\"Enter the name: \")\n number = input(\"Enter the number: \")\n birthday = input(\"Enter the birthday\")\n address = input(\"Enter the address\")\n details[\"Name\"] = name\n details[\"Number\"] = number\n details[\"Birthday\"] = birthday\n details[\"Address\"] = address\n my_contacts[index] = details\n index += 1\n print(my_contacts)\n\nadd_contact()\n\nprint(my_contacts)\ndef del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n values = [key for key in my_contacts.keys() if user_input in my_contacts[key].values()]\n for value in values:\n my_contacts.pop(value)\ndel_contact()\nprint(my_contacts)\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 2: {'Name': 'Bob Marley', 'Number': '0800838383', 'Birthday': '22.10.1991', 'Address': '31 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n Please enter the name of the contact you want to delete: Bob Marley\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9198260/" ]
74,632,362
<p>I would like it to return true in C1 if A1 and B1 have at least one common character and return false in C2 if A2 and B1 do not have any common character</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>[1, 7, 12]</td> <td>1, 8, 9, 40</td> <td></td> </tr> <tr> <td>2</td> <td>[10, 15, 22]</td> <td></td> <td></td> </tr> <tr> <td>3</td> <td>[1, 15, 121, 10]</td> <td></td> <td></td> </tr> </tbody> </table> </div> <pre><code>=INDEX(REGEXMATCH(A1:A3, &quot;\b&quot;&amp;SUBSTITUTE(B1:B3, &quot;,&quot;, &quot;|&quot;)&amp;&quot;\b&quot;)) </code></pre>
[ { "answer_id": 74632391, "author": "Nimrod Shanny", "author_id": 20631164, "author_profile": "https://Stackoverflow.com/users/20631164", "pm_score": 2, "selected": true, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\nuser_input = \"Tom Jones\"\n\nmy_contacts = {key: value for key, value in my_contacts.items() if value[\"Name\"] != user_input}\n" }, { "answer_id": 74632460, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 0, "selected": false, "text": "def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for k, v in my_contacts.items(): # Need both key and value, we test key, delete by value\n if v[\"Name\"] == user_input:\n del my_contacts[k]\n break # Deleted one item, stop now (we'd RuntimeError if iteration continued)\n else:\n # Optionally raise exception or print error indicating name wasn't found\n dict def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n to_delete = [k for k, v in my_contacts.items() if v[\"Name\"] == user_input]\n if not to_delete:\n # Optionally raise exception or print error indicating name wasn't found\n for k in to_delete:\n del my_contacts[k]\n dict def del_contact():\n global my_contacts # Assignment requires explicitly declared use of global\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n my_contacts = {k: v for k, v in my_contacts.items() if v[\"Name\"] != user_input} # Flip test, build new dict\n # Detecting no matches is more annoying here (it's basically comparing\n # length before and after), so I'm omitting it\n" }, { "answer_id": 74632542, "author": "CodeKorn", "author_id": 10882128, "author_profile": "https://Stackoverflow.com/users/10882128", "pm_score": 0, "selected": false, "text": "range def del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n for i in range(1,len(my_contacts)+1):\n if my_contacts[i]['Name'] == user_input:\n del my_contacts[i]\n break\n Tom Jones dict index = len(my_contacts) + 1 my_contacts[index] = details \"Name\": \"Bob Marley\"" }, { "answer_id": 74632628, "author": "pizoooo", "author_id": 10902484, "author_profile": "https://Stackoverflow.com/users/10902484", "pm_score": 0, "selected": false, "text": "my_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n 2: {\"Name\": \"Bob Marley\",\n \"Number\": \"0800838383\",\n \"Birthday\": \"22.10.1991\",\n \"Address\": \"31 street\"}\n }\n\ndef add_contact():\n user_input = int(input(\"please enter how many contacts you wanna add: \"))\n index = len(my_contacts) + 1\n for _ in range(user_input):\n details = {}\n name = input(\"Enter the name: \")\n number = input(\"Enter the number: \")\n birthday = input(\"Enter the birthday\")\n address = input(\"Enter the address\")\n details[\"Name\"] = name\n details[\"Number\"] = number\n details[\"Birthday\"] = birthday\n details[\"Address\"] = address\n my_contacts[index] = details\n index += 1\n print(my_contacts)\n\nadd_contact()\n\nprint(my_contacts)\ndef del_contact():\n user_input = input(\"Please enter the name of the contact you want to delete: \")\n values = [key for key in my_contacts.keys() if user_input in my_contacts[key].values()]\n for value in values:\n my_contacts.pop(value)\ndel_contact()\nprint(my_contacts)\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 2: {'Name': 'Bob Marley', 'Number': '0800838383', 'Birthday': '22.10.1991', 'Address': '31 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n Please enter the name of the contact you want to delete: Bob Marley\n {1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20613916/" ]
74,632,371
<p>For each element in a list I want to add the value before and after the element and append the result to an empty list. The problem is that at index 0 there is no index before and at the end there is no index next. At index 0 I want to add the value of index 0 with value of index 1, and in the last index I want to add the value of the last index with the same index value. As following:</p> <pre><code>vec = [1,2,3,4,5] newVec = [] for i in range(len(vec)): newValue = vec[i] + vec[i+1] + vec[i-1] # if i + 1 or i - 1 does now exist pass newVec.append(newValue) Expected output: newVec = [1+2, 2+1+3, 3+2+4,4+3+5,5+4] # newVec = [3, 6, 9, 12, 9] </code></pre>
[ { "answer_id": 74632469, "author": "Hunter", "author_id": 15076691, "author_profile": "https://Stackoverflow.com/users/15076691", "pm_score": 1, "selected": false, "text": "0 vec for i in range(1, ...) 1 i vec = [1,2,3,4,5]\nnewVec = []\nvec.insert(0, 0)\nvec.insert(len(vec) + 1, 0)\nfor i in range(1, len(vec) - 1):\n newVec.append(vec[i-1] + vec[i] + vec[i+1])\nprint(newVec)\n" }, { "answer_id": 74632490, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 2, "selected": false, "text": "for i in range(len(vec)):\n if i == 0 :\n newValue = vec[i] + vec[i+1]\n elif i == len(vec)-1:\n newValue = vec[i] + vec[i-1]\n else:\n newValue = vec[i] + vec[i+1] + vec[i-1]\n newVec.append(newValue)\n\nprint(newVec)\n [3, 6, 9, 12, 9]\n" }, { "answer_id": 74632509, "author": "Nimrod Shanny", "author_id": 20631164, "author_profile": "https://Stackoverflow.com/users/20631164", "pm_score": 3, "selected": true, "text": "vec = [1, 2, 3, 4, 5]\nnew_vec = []\nfor index, number in enumerate(vec):\n new_value = number\n if index != 0:\n new_value += vec[index - 1]\n try:\n new_value += vec[index + 1]\n except IndexError:\n pass\n new_vec.append(new_value)\n [3, 6, 9, 12, 9]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19952753/" ]
74,632,381
<p>I want to show timer of 1 minute when user click on Re-send</p> <p><a href="https://i.stack.imgur.com/b6cds.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b6cds.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/K73QB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K73QB.png" alt="enter image description here" /></a></p> <pre><code>Text( text = &quot;Re-send&quot;, modifier = Modifier.clickable { }, color = Color.Blue ) </code></pre>
[ { "answer_id": 74633185, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 4, "selected": true, "text": "@Composable\nprivate fun ResendTextSample() {\n\n val str = \"Did you not receive the email? \"\n val length = str.length\n\n var isTimerActive by remember {\n mutableStateOf(false)\n }\n\n var time by remember { mutableStateOf(\"\") }\n\n LaunchedEffect(key1 = isTimerActive) {\n if(isTimerActive){\n var second = 0\n while (second < 15) {\n time = if(second <10) \"0:0$second\" else \"0:$second\"\n delay(1000)\n second++\n }\n isTimerActive = false\n }\n }\n\n val annotatedLinkString = buildAnnotatedString {\n\n append(str)\n withStyle(\n SpanStyle(\n color = Color.Blue,\n )\n ) {\n if (!isTimerActive) {\n append(\"Re-send\")\n } else {\n append(time)\n }\n }\n append(\"\\nCheck your spam filter\")\n\n }\n\n ClickableText(\n text = annotatedLinkString,\n style = TextStyle(fontSize = 20.sp),\n onClick = {\n if (!isTimerActive && it >= length && it <= length + 7) {\n isTimerActive = true\n }\n }\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18823812/" ]
74,632,426
<p>I've created this dataframe -</p> <pre><code>Range = np.arange(1,101,1) A={ 0:-1, 1:0, 2:4 } Table = pd.DataFrame({&quot;Row&quot;: Range}) Table[&quot;Intervals&quot;]=np.where(Table[&quot;Row&quot;]==1,0,(Table[&quot;Row&quot;]%3).map(A)) Table Row Intervals 0 1 0 1 2 4 2 3 -1 3 4 0 4 5 4 ... ... ... 95 96 -1 96 97 0 97 98 4 98 99 -1 99 100 0 </code></pre> <p>I'd like to add a new column that the first cell will contain the number -25 and the second number will be -25+4, the third number will be -25+4+(-1)...and so on.</p> <p>I've tried to use shift but no luck -</p> <pre><code>Table[&quot;X&quot;]=np.where(Table[&quot;Row&quot;]==1,-25,Table[&quot;X&quot;].shift(1)) </code></pre> <p>Will appreciate any help!</p>
[ { "answer_id": 74633185, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 4, "selected": true, "text": "@Composable\nprivate fun ResendTextSample() {\n\n val str = \"Did you not receive the email? \"\n val length = str.length\n\n var isTimerActive by remember {\n mutableStateOf(false)\n }\n\n var time by remember { mutableStateOf(\"\") }\n\n LaunchedEffect(key1 = isTimerActive) {\n if(isTimerActive){\n var second = 0\n while (second < 15) {\n time = if(second <10) \"0:0$second\" else \"0:$second\"\n delay(1000)\n second++\n }\n isTimerActive = false\n }\n }\n\n val annotatedLinkString = buildAnnotatedString {\n\n append(str)\n withStyle(\n SpanStyle(\n color = Color.Blue,\n )\n ) {\n if (!isTimerActive) {\n append(\"Re-send\")\n } else {\n append(time)\n }\n }\n append(\"\\nCheck your spam filter\")\n\n }\n\n ClickableText(\n text = annotatedLinkString,\n style = TextStyle(fontSize = 20.sp),\n onClick = {\n if (!isTimerActive && it >= length && it <= length + 7) {\n isTimerActive = true\n }\n }\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16667667/" ]
74,632,438
<p>I need to make sure that the pipeline runs every day except every second Thursday and Friday by cron. The cron is located in the azure pipeline. Now I have this:</p> <pre><code>schedules: - cron: 0 19 * * 1-5 displayName: evening-deployment branches: include: - develop always: false </code></pre>
[ { "answer_id": 74633185, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 4, "selected": true, "text": "@Composable\nprivate fun ResendTextSample() {\n\n val str = \"Did you not receive the email? \"\n val length = str.length\n\n var isTimerActive by remember {\n mutableStateOf(false)\n }\n\n var time by remember { mutableStateOf(\"\") }\n\n LaunchedEffect(key1 = isTimerActive) {\n if(isTimerActive){\n var second = 0\n while (second < 15) {\n time = if(second <10) \"0:0$second\" else \"0:$second\"\n delay(1000)\n second++\n }\n isTimerActive = false\n }\n }\n\n val annotatedLinkString = buildAnnotatedString {\n\n append(str)\n withStyle(\n SpanStyle(\n color = Color.Blue,\n )\n ) {\n if (!isTimerActive) {\n append(\"Re-send\")\n } else {\n append(time)\n }\n }\n append(\"\\nCheck your spam filter\")\n\n }\n\n ClickableText(\n text = annotatedLinkString,\n style = TextStyle(fontSize = 20.sp),\n onClick = {\n if (!isTimerActive && it >= length && it <= length + 7) {\n isTimerActive = true\n }\n }\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14751570/" ]
74,632,445
<p>I'm new to prolog, I don't understand much of the language and I had already posted a question about Prolog before. Now I want to obtain, from a list of integers, the numbers in the interval that contains the largest amount of numbers in that list, in other words the maximum range. Example:</p> <pre><code>maxrange(X,Y,[1,3,2,7,4,5,6,9,8]). X = 1, Y= 10. maxrange(1,10,[1,3,2,7,4,5,6,9,8]. True. maxrange(1,8,[1,3,2,7,4,5,6,9,8]. False. </code></pre> <p>Lists must contain all numbers between [X,Y) and must be the maximum interval.</p>
[ { "answer_id": 74633185, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 4, "selected": true, "text": "@Composable\nprivate fun ResendTextSample() {\n\n val str = \"Did you not receive the email? \"\n val length = str.length\n\n var isTimerActive by remember {\n mutableStateOf(false)\n }\n\n var time by remember { mutableStateOf(\"\") }\n\n LaunchedEffect(key1 = isTimerActive) {\n if(isTimerActive){\n var second = 0\n while (second < 15) {\n time = if(second <10) \"0:0$second\" else \"0:$second\"\n delay(1000)\n second++\n }\n isTimerActive = false\n }\n }\n\n val annotatedLinkString = buildAnnotatedString {\n\n append(str)\n withStyle(\n SpanStyle(\n color = Color.Blue,\n )\n ) {\n if (!isTimerActive) {\n append(\"Re-send\")\n } else {\n append(time)\n }\n }\n append(\"\\nCheck your spam filter\")\n\n }\n\n ClickableText(\n text = annotatedLinkString,\n style = TextStyle(fontSize = 20.sp),\n onClick = {\n if (!isTimerActive && it >= length && it <= length + 7) {\n isTimerActive = true\n }\n }\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19936225/" ]
74,632,449
<p>I have a json file with multiple json objects (each object can be a multiple line json) Example:</p> <pre class="lang-none prettyprint-override"><code>{&quot;date&quot;: &quot;2022-11-29&quot;, &quot;runs&quot;: [{&quot;23597&quot;: 821260}, {&quot;23617&quot;: 821699}]} {&quot;date&quot;: &quot;2022-11-30&quot;, &quot;runs&quot;: [{&quot;23597&quot;: 821269}, {&quot;23617&quot;: 8213534}]} </code></pre> <p>Note that indeed this is not valid JSON as whole file (and hence regular &quot;read JSON in Python&quot; code fails, expected), but each individual &quot;fragment&quot; is complete and valid JSON. It sounds like file was produced by some logging tool that simply appends the next block as text to the file.</p> <p>As expected, regular way of reading that I have tried with the below snippet fails:</p> <pre><code>with open('run_log.json','r') as file: d = json.load(file) print(d) </code></pre> <p>Produces expected error about invalid JSON:</p> <blockquote> <p>JSONDecodeError: Extra data: line 3 column 1 (char 89)</p> </blockquote> <p>How can I solve this, possibly using the json module? Ideally, I want to read the json file and get the runs list for only a particular date (Ex : 2022-11-30), but just being able to read all entries would be enough.</p>
[ { "answer_id": 74633185, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 4, "selected": true, "text": "@Composable\nprivate fun ResendTextSample() {\n\n val str = \"Did you not receive the email? \"\n val length = str.length\n\n var isTimerActive by remember {\n mutableStateOf(false)\n }\n\n var time by remember { mutableStateOf(\"\") }\n\n LaunchedEffect(key1 = isTimerActive) {\n if(isTimerActive){\n var second = 0\n while (second < 15) {\n time = if(second <10) \"0:0$second\" else \"0:$second\"\n delay(1000)\n second++\n }\n isTimerActive = false\n }\n }\n\n val annotatedLinkString = buildAnnotatedString {\n\n append(str)\n withStyle(\n SpanStyle(\n color = Color.Blue,\n )\n ) {\n if (!isTimerActive) {\n append(\"Re-send\")\n } else {\n append(time)\n }\n }\n append(\"\\nCheck your spam filter\")\n\n }\n\n ClickableText(\n text = annotatedLinkString,\n style = TextStyle(fontSize = 20.sp),\n onClick = {\n if (!isTimerActive && it >= length && it <= length + 7) {\n isTimerActive = true\n }\n }\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15289474/" ]
74,632,472
<p>I'm trying to contain this image grid within the viewport height and it works if I use overflow: hidden on its wrapper. However, I want to add label elements to the images that overflow their wrappers, so I need to find a solution that would keep them visible. I also need the images to stay grouped together even if the viewport is resized (always touching) as they are right now. The images need to be shown fully.</p> <p>I've added a label example in the first wrapper. As you can see, most of it is hidden, but I'd like it all to be visible and for it to overflow out of the wrapper (not to be contained in it). Any help is appreciated.</p> <p><a href="https://jsfiddle.net/k54doq89/2/" rel="nofollow noreferrer">https://jsfiddle.net/k54doq89/2/</a></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>#_parent { display: flex; position: relative; height: 100vh; width: 50vw; } #_grid { display: flex; height: 100%; width: 100%; place-items: center; justify-content: center; margin: auto; border: 0; padding: 0; } #_row { display: grid; max-width: 100%; height: 100%; align-content: center; margin: 0; border: 0; padding: 0; grid-template-columns: repeat(3, 1fr); } ._img { height: 100%; width: 100%; object-fit: contain; margin: 0; border: 0; padding: 0; } .wrapper { overflow: hidden; display: flex; justify-content: center; align-items: flex-end; margin: 0; border: 0; padding: 0; position: relative; clear: both; } .label-example { position: absolute; display: flex; flex-direction: column; justify-content: center; align-items: center; align-content: center; height: 100%; width: 100%; color:magenta; } body { margin: 0; padding: 0; border: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="_parent"&gt; &lt;div id="_grid"&gt; &lt;div id="_row"&gt; &lt;div class="wrapper"&gt; &lt;div class="label-example"&gt;1234567890&lt;/div&gt; &lt;img id="" src="//placeimg.com/295/420?text=1" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=2" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=3" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=4" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=5" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=6" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=7" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=8" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=9" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=10" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=11" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=12" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=13" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=14" class="_img"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;img id="" src="//placeimg.com/295/420?text=15" class="_img"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74633315, "author": "Pete Pearl", "author_id": 14290361, "author_profile": "https://Stackoverflow.com/users/14290361", "pm_score": 0, "selected": false, "text": "#_parent {\n display: flex;\n position: relative;\n height: 100vh;\n width: 50vw;\n}\n\n#_grid {\n display: flex;\n height: inherit;\n width: inherit;\n}\n\n#_row {\n display: grid;\n width: 100%;\n height: 100%;\n grid-template-columns: repeat(3, 1fr);\n}\n\n._img {\n height: 100%;\n width: 100%;\n object-fit: cover;\n object-position: center top;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n z-index: 1;\n}\n\n.wrapper {\n position: relative;\n}\n\n.label-example {\n position: absolute;\n z-index: 2;\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n align-content: center;\n height: 100%;\n width: 100%;\n color:magenta;\n}\n\nbody {\n margin: 0;\n padding: 0;\n border: 0;\n} <div id=\"_parent\">\n <div id=\"_grid\">\n <div id=\"_row\">\n <div class=\"wrapper\">\n <div class=\"label-example\">1234567890</div>\n <img id=\"\" src=\"//placeimg.com/295/420?text=1\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=2\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=3\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=4\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=5\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=6\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=7\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=8\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=9\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=10\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=11\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=12\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=13\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=14\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=15\" class=\"_img\">\n </div>\n </div>\n </div>\n</div> #_parent {\n height: 100vh;\n width: 50vw;\n}\n\n#_grid {\n display: flex;\n height: 100%;\n width: 100%;\n}\n\n#_row {\n display: grid;\n height: 100%;\n grid-template-columns: repeat(3, 1fr);\n}\n\n._img {\n height: 100%;\n width: 100%;\n object-fit: contain;\n display: block;\n}\n\n.wrapper {\n overflow: hidden;\n position: relative;\n}\n\nbody {\n margin: 0;\n padding: 0;\n border: 0;\n} <div id=\"_parent\">\n <div id=\"_grid\">\n <div id=\"_row\">\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=1\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=2\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=3\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=4\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=5\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=6\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=7\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=8\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=9\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=10\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=11\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=12\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=13\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=14\" class=\"_img\">\n </div>\n <div class=\"wrapper\">\n <img id=\"\" src=\"//placeimg.com/295/420?text=15\" class=\"_img\">\n </div>\n </div>\n </div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18618451/" ]
74,632,492
<p>I have a spreadsheet where I automatically get hundreds urls and spreadsheet names (half home address half full names) and put them in the spreadsheet column. I only need around 50 of the urls based on a set of addresses I track.</p> <p>Each spreadsheet name has the address inside of it that I need to search for.</p> <p>Somehow I need to search the spreadsheet name column for an address in another cell, and then return the url that is adjacent to the column. Even if it returned both the url column and the spreadsheet name column that would be great.</p> <p>I've tried a few things, most notably the formula below which has worked for me in the past for similar issues, but this formula doesn't explicitly include searching the cells for the string I am looking for.</p> <p>=ARRAYFORMULA(IFERROR(A1:A,QUERY('Finding INformation'!A:B,&quot;select A where B contains &quot;A1:A&quot;&quot;)))</p> <p>I created a spreadsheet with fewer values and no sensitive information. <a href="https://docs.google.com/spreadsheets/d/1oxtM_hQVIjBoB5SJ2b_b8oP5XIj4Gv5EngNx6KI4LiE/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1oxtM_hQVIjBoB5SJ2b_b8oP5XIj4Gv5EngNx6KI4LiE/edit?usp=sharing</a> Based on the spreadsheet I would need for example &quot;link 1&quot; to the right of &quot;Address 1&quot;, imagining that link 1 actually had a link in it so I can't use the URL as a search parameter.</p>
[ { "answer_id": 74632733, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 2, "selected": true, "text": "=BYROW(A:A,LAMBDA(ax,if(ax=\"\",,xlookup(ax&\"*\",'Finding INformation'!B:B,'Finding INformation'!A:A,,2))))" }, { "answer_id": 74633847, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IFNA(VLOOKUP(A1:A, {INDEX(SPLIT('Finding INformation'!B1:B, \" /\", ),,1), \n 'Finding INformation'!A1:A}, 2, )))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648105/" ]
74,632,499
<p>I am trying to join two data sets together, while at the same time aggregating data from the joining table based on timestamp values from the main table. Essentially, I have two data sets, the first one looks like this:</p> <pre><code>Table_1 user id | change | timestamp ------------------------------- user_1 initiate 2020-01-01 user_1 change 2020-03-01 user_1 change 2021-01-01 user_1 end 2021-06-01 user_2 change 2022-03-01 user_2 renew 2022-06-01 </code></pre> <p>The second looks like this:</p> <pre><code>Table_2 user_id | action | action_timestamp ----------------------------------- user_1 xyz 2020-02-01 user_1 zyx 2020-02-03 user_1 123 2021-01-02 user_1 234 2021-05-01 user_2 xyz 2022-03-02 user_2 abc 2022-04-01 user_2 234 2022-05-30 </code></pre> <p>I want to get to a table that looks like this:</p> <pre><code> user id | change | timestamp | actions_since_last_change ---------------------------------------------------- user_1 initiate 2020-01-01 null user_1 change 2020-03-01 xyz, zyx user_1 change 2021-01-01 null user_1 end 2021-06-01 123, 234 user_2 change 2022-03-01 null user_2 renew 2022-06-01 abc, 234 </code></pre> <p>I think its (maybe?) something (pseudo) like this:</p> <pre><code>on Table_1.user_id = Table_2.user_id and Table_2.timestamp between rows preceeding (partition by user_id) </code></pre> <p>It also might be in the Select statement of the main query that generates Table_1, like:</p> <pre><code>Select user_id, change, timestamp, string_agg(Select(action from Table_2),&quot;, &quot;) From Initial_table </code></pre> <p>Honestly, I'm not sure what the right approach to this is, so any advice would be appreciated!</p>
[ { "answer_id": 74632733, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 2, "selected": true, "text": "=BYROW(A:A,LAMBDA(ax,if(ax=\"\",,xlookup(ax&\"*\",'Finding INformation'!B:B,'Finding INformation'!A:A,,2))))" }, { "answer_id": 74633847, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IFNA(VLOOKUP(A1:A, {INDEX(SPLIT('Finding INformation'!B1:B, \" /\", ),,1), \n 'Finding INformation'!A1:A}, 2, )))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4709889/" ]
74,632,508
<p>By default, Python's <code>logging</code> module uses a special format for times, which includes milliseconds: <code>2003-01-23 00:29:50,411</code>.</p> <p>Notably, <code>strftime</code> and <code>strptime</code> don't have a standard &quot;milliseconds&quot; specifier (so <code>logging</code> first prints everything else with <code>strftime</code> and then inserts the milliseconds separately). This means there's no obvious way to parse these strings using the standard library.</p> <p>However, everything <em>seems</em> to work fine when I use <code>strptime</code> with the <code>%f</code> (microseconds) specifier: <code>%Y-%m-%d %H:%M:%S,%f</code>. While <code>%f</code> in <code>strftime</code> prints a six-digit number, in <code>strptime</code> it's apparently happy to take a three-digit number instead, and assume the last three digits are zeroes.</p> <p>My question is—<strong>is this standard/documented behavior</strong>? Can I rely on this to keep working, or is it liable to break unexpectedly in new versions? I haven't been able to find anything about this in the Python docs (or <code>man strptime</code>, which doesn't even mention <code>%f</code>), but this seems like a common enough use case that I'd be surprised if nobody's needed it before.</p> <p>I could also append three zeroes to the time string before passing it to <code>strptime</code>, but that's hacky enough that I'd prefer not to do it unless necessary.</p>
[ { "answer_id": 74632733, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 2, "selected": true, "text": "=BYROW(A:A,LAMBDA(ax,if(ax=\"\",,xlookup(ax&\"*\",'Finding INformation'!B:B,'Finding INformation'!A:A,,2))))" }, { "answer_id": 74633847, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IFNA(VLOOKUP(A1:A, {INDEX(SPLIT('Finding INformation'!B1:B, \" /\", ),,1), \n 'Finding INformation'!A1:A}, 2, )))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233017/" ]
74,632,510
<p>I want to find one city for each state that has the maximum average population? I have three table state, city and population. The table provided are simplified, to only have 2 states</p> <p>&quot;state&quot; Code is our key that is unquie for each state</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>code</th> </tr> </thead> <tbody> <tr> <td>Ohio</td> <td>OH</td> </tr> <tr> <td>Wisconsin</td> <td>WI</td> </tr> </tbody> </table> </div> <p>&quot;city&quot;</p> <p>two state codes to refer to border between two states</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>code</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>OH</td> <td>Cevland</td> </tr> <tr> <td>OH</td> <td>Dayton</td> </tr> <tr> <td>OH</td> <td>Toledo</td> </tr> <tr> <td>WI</td> <td>Madison</td> </tr> <tr> <td>WI</td> <td>Racine</td> </tr> </tbody> </table> </div> <p>&quot;citypop&quot;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>code</th> <th>name</th> <th>Year</th> <th>pop</th> </tr> </thead> <tbody> <tr> <td>OH</td> <td>Cevland</td> <td>1998</td> <td>10000</td> </tr> <tr> <td>OH</td> <td>Cevland</td> <td>2000</td> <td>1000</td> </tr> <tr> <td>OH</td> <td>Dayton</td> <td>1998</td> <td>6000</td> </tr> <tr> <td>OH</td> <td>Toledo</td> <td>1978</td> <td>8000</td> </tr> <tr> <td>WI</td> <td>Madison</td> <td>1999</td> <td>2000</td> </tr> <tr> <td>WI</td> <td>Madison</td> <td>2000</td> <td>20000</td> </tr> <tr> <td>WI</td> <td>Racine</td> <td>2000</td> <td>5000</td> </tr> </tbody> </table> </div> <p>Expected result : Cevland not choose because avgpop, madison and toledo are selected</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>city</th> <th>avgpop</th> </tr> </thead> <tbody> <tr> <td>Toledo</td> <td>8000</td> </tr> <tr> <td>Madison</td> <td>11000</td> </tr> </tbody> </table> </div> <p>The query i have made so far.</p> <pre><code>Select c.name, avg(cp.length) from city c Inner Join citypop cp On c.name = cp.city Group by c.name </code></pre> <p>My thinking is I want to select the name and avg, but not sure how to get the next step of only one city for each country.</p> <p>'Edit' The reason its madison is because we add 2000, 20000 and then devide to get the average. so madision avg pop is 11000 and racine(having only one data point value) is 5000. We want the max average so we select madison.</p>
[ { "answer_id": 74632733, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 2, "selected": true, "text": "=BYROW(A:A,LAMBDA(ax,if(ax=\"\",,xlookup(ax&\"*\",'Finding INformation'!B:B,'Finding INformation'!A:A,,2))))" }, { "answer_id": 74633847, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(IFNA(VLOOKUP(A1:A, {INDEX(SPLIT('Finding INformation'!B1:B, \" /\", ),,1), \n 'Finding INformation'!A1:A}, 2, )))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20265307/" ]
74,632,526
<p>I am writing code, which loads the data of a JSON file and parses it using Pydantic.</p> <p>Here is the Python code:</p> <pre class="lang-py prettyprint-override"><code>import json import pydantic from typing import Optional, List class Car(pydantic.BaseModel): manufacturer: str model: str date_of_manufacture: str date_of_sale: str number_plate: str price: float type_of_fuel: Optional[str] location_of_sale: Optional[str] def load_data() -&gt; None: with open(&quot;./data.json&quot;) as file: data = json.load(file) cars: List[Car] = [Car(**item) for item in data] print(cars[0]) if __name__ == &quot;__main__&quot;: load_data() </code></pre> <p>And here is the JSON data:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;manufacturer&quot;: &quot;BMW&quot;, &quot;model&quot;: &quot;i8&quot;, &quot;date_of_manufacture&quot;: &quot;14/06/2021&quot;, &quot;date_of_sale&quot;: &quot;19/11/2022&quot;, &quot;number_plate&quot;: &quot;ND21WHP&quot;, &quot;price&quot;: &quot;100,000&quot;, &quot;type_of_fuel&quot;: &quot;electric&quot;, &quot;location_of_sale&quot;: &quot;Leicester, England&quot; }, { &quot;manufacturer&quot;: &quot;Audi&quot;, &quot;model&quot;: &quot;TT RS&quot;, &quot;date_of_manufacture&quot;: &quot;22/02/2019&quot;, &quot;date_of_sale&quot;: &quot;12/08/2021&quot;, &quot;number_plate&quot;: &quot;LR69FOW&quot;, &quot;price&quot;: &quot;67,000&quot;, &quot;type_of_fuel&quot;: &quot;petrol&quot;, &quot;location_of_sale&quot;: &quot;Manchester, England&quot; } ] </code></pre> <p>And this is the error I am getting:</p> <pre> File "pydantic\main.py", line 342, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Car price value is not a valid float (type=type_error.float) </pre> <p>I have tried adding <code>.00</code> to the end of the price strings but I get the same error.</p>
[ { "answer_id": 74632606, "author": "Crimp City", "author_id": 7211646, "author_profile": "https://Stackoverflow.com/users/7211646", "pm_score": 0, "selected": false, "text": "\"price\": \"100,000\" \"price\": 100000" }, { "answer_id": 74633080, "author": "Paul", "author_id": 9236505, "author_profile": "https://Stackoverflow.com/users/9236505", "pm_score": 1, "selected": false, "text": ", _" }, { "answer_id": 74641436, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "float float float(\"100,000\") ValueError from pydantic import BaseModel, validator\n\nclass Car(BaseModel):\n manufacturer: str\n model: str\n date_of_manufacture: str\n date_of_sale: str\n number_plate: str\n price: float\n type_of_fuel: Optional[str]\n location_of_sale: Optional[str]\n\n @validator(\"price\", pre=True)\n def adjust_number_format(cls, v: object) -> object:\n if isinstance(v, str):\n return v.replace(\",\", \"\")\n return v\n pre=True str float ...\n @validator(\"price\", pre=True)\n def parse_number(cls, v: object) -> object:\n if isinstance(v, str):\n return float(v.replace(\",\", \"\"))\n return v\n from pydantic import BaseModel, validator\nfrom pydantic.fields import ModelField\n\n\nclass Car2(BaseModel):\n model: str\n price: float\n year: int\n numbers: list[float]\n\n @validator(\"*\", pre=True, each_item=True)\n def format_number_string(cls, v: object, field: ModelField) -> object:\n if issubclass(field.type_, (float, int)) and isinstance(v, str):\n return v.replace(\",\", \"\")\n return v\n\n\nif __name__ == \"__main__\":\n car = Car2.parse_obj({\n \"model\": \"foo\",\n \"price\": \"100,000\",\n \"year\": \"2,010\",\n \"numbers\": [\"1\", \"3.14\", \"10,000\"]\n })\n print(car) # model='foo' price=100000.0 year=2010 numbers=[1.0, 3.14, 10000.0]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442433/" ]
74,632,527
<p>I have pageView builder which each page contains different paragraph I want to let this paragraph take all the space in page without spaces to be in the same aligment.</p> <p>I tried it by my my problem was that some paragraphs come with 7 lines which can take 100% of the page but some of them come with 3 lines and does not take remaining space takes only 30% from the page</p> <p>Tried code:</p> <pre><code> Expanded( child: AutoSizeText.rich( textAlign: index == 0 ? TextAlign.center : TextAlign.justify, TextSpan( children: [ for (var i = 1; i &lt;= list.length; i++) ...{ TextSpan( text: &quot;${list[i - 1]} &quot;, style: GoogleFonts.balooBhai2( fontSize: 25, color: Colors.black87, ), ), } ], ), ), ), </code></pre> <p>Expected result:all texts on all pages is the same height</p> <p>The result is: some texts take 50% of the page some it take 150% some it take 100%</p>
[ { "answer_id": 74632606, "author": "Crimp City", "author_id": 7211646, "author_profile": "https://Stackoverflow.com/users/7211646", "pm_score": 0, "selected": false, "text": "\"price\": \"100,000\" \"price\": 100000" }, { "answer_id": 74633080, "author": "Paul", "author_id": 9236505, "author_profile": "https://Stackoverflow.com/users/9236505", "pm_score": 1, "selected": false, "text": ", _" }, { "answer_id": 74641436, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 3, "selected": true, "text": "float float float(\"100,000\") ValueError from pydantic import BaseModel, validator\n\nclass Car(BaseModel):\n manufacturer: str\n model: str\n date_of_manufacture: str\n date_of_sale: str\n number_plate: str\n price: float\n type_of_fuel: Optional[str]\n location_of_sale: Optional[str]\n\n @validator(\"price\", pre=True)\n def adjust_number_format(cls, v: object) -> object:\n if isinstance(v, str):\n return v.replace(\",\", \"\")\n return v\n pre=True str float ...\n @validator(\"price\", pre=True)\n def parse_number(cls, v: object) -> object:\n if isinstance(v, str):\n return float(v.replace(\",\", \"\"))\n return v\n from pydantic import BaseModel, validator\nfrom pydantic.fields import ModelField\n\n\nclass Car2(BaseModel):\n model: str\n price: float\n year: int\n numbers: list[float]\n\n @validator(\"*\", pre=True, each_item=True)\n def format_number_string(cls, v: object, field: ModelField) -> object:\n if issubclass(field.type_, (float, int)) and isinstance(v, str):\n return v.replace(\",\", \"\")\n return v\n\n\nif __name__ == \"__main__\":\n car = Car2.parse_obj({\n \"model\": \"foo\",\n \"price\": \"100,000\",\n \"year\": \"2,010\",\n \"numbers\": [\"1\", \"3.14\", \"10,000\"]\n })\n print(car) # model='foo' price=100000.0 year=2010 numbers=[1.0, 3.14, 10000.0]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570798/" ]
74,632,528
<p>I have the following data:</p> <pre><code>1 2 3 4 1 2 3 4 1 2 4 1 2 4 </code></pre> <p>If I use</p> <pre><code>plot &quot;file&quot; u 1:3 </code></pre> <p>then it plots {1,3},{1,3},{1,4},{1,4}</p> <p>How do I plot it following the column?</p> <p>This is a txt file.</p>
[ { "answer_id": 74632962, "author": "theozh", "author_id": 7295599, "author_profile": "https://Stackoverflow.com/users/7295599", "pm_score": 1, "selected": false, "text": "whitespace help datafile separator set datafile separator \" \" 1 2.1 3.1 4.1\n2 2.2 3.2 4.2\n3 2.3 4.3 # two spaces but not more\n4 2.4 4.4 # ditto\n5 2.5 3.5 4.5\n ### empty columns\nreset session\n\n$Data <<EOD\n1 2.1 3.1 4.1\n2 2.2 3.2 4.2\n3 2.3 4.3\n4 2.4 4.4\n5 2.5 3.5 4.5\nEOD\n\nset key out tmargin\n\nset multiplot layout 1,2\n\n set datafile separator whitespace # this is default\n plot $Data u 1:2 w lp pt 7 lc \"red\", \\\n '' u 1:3 w lp pt 7 lc \"green\", \\\n '' u 1:4 w lp pt 7 lc \"blue\"\n\n set datafile separator \" \"\n plot $Data u 1:2 w lp pt 7 lc \"red\", \\\n '' u 1:3 w lp pt 7 lc \"green\", \\\n '' u 1:4 w lp pt 7 lc \"blue\"\n\nunset multiplot\n### end of script\n" }, { "answer_id": 74634928, "author": "Ethan", "author_id": 6797953, "author_profile": "https://Stackoverflow.com/users/6797953", "pm_score": 0, "selected": false, "text": "$DATA << EOD\n1 2 3 4\n1 2 3 4\n1 2 4\n1 2 4\n1 2 7 8\nEOD\n\n# There are no commas, so the program will treat the entire line a \"column 1\"\nset datafile separator comma\n\n# Treat blank column as NaN, otherwise convert to integer\nconvert(s) = (s eq \" \" ? NaN : int(s))\n\n# For the sake of example, just print the result rather than plotting\nset table\n\nplot $DATA using (convert(strcol(1)[1:1]) : (convert(strcol(1)[5:7]) with points\n # Curve 0 of 1, 5 points\n# Curve title: \"$DATA using (convert(strcol(1)[1:1])):(convert(strcol(1)[5:7]))\"\n# x y type\n 1 3 i\n 1 3 i\n 1 NaN u\n 1 NaN u\n 1 7 i\n set table" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497470/" ]
74,632,543
<p>I have a table in a JSON whereby I need an entire row to be deleted/ filtered based on the condition if &quot;Disposition (Non Open Market)&quot; in &quot;transactionType&quot; then delete/ filter entry in all columns. Below is what my JSON file looks like:</p> <pre><code>{ &quot;lastDate&quot;:{ &quot;0&quot;:&quot;11\/22\/2022&quot;, &quot;1&quot;:&quot;10\/28\/2022&quot;, &quot;2&quot;:&quot;10\/17\/2022&quot;, &quot;3&quot;:&quot;10\/15\/2022&quot;, &quot;4&quot;:&quot;10\/15\/2022&quot;, &quot;5&quot;:&quot;10\/15\/2022&quot;, &quot;6&quot;:&quot;10\/15\/2022&quot;, &quot;7&quot;:&quot;10\/03\/2022&quot;, &quot;8&quot;:&quot;10\/03\/2022&quot;, &quot;9&quot;:&quot;10\/03\/2022&quot;, &quot;10&quot;:&quot;10\/01\/2022&quot;, &quot;11&quot;:&quot;10\/01\/2022&quot;, &quot;12&quot;:&quot;10\/01\/2022&quot;, &quot;13&quot;:&quot;10\/01\/2022&quot;, &quot;14&quot;:&quot;10\/01\/2022&quot;, &quot;15&quot;:&quot;10\/01\/2022&quot;, &quot;16&quot;:&quot;10\/01\/2022&quot;, &quot;17&quot;:&quot;10\/01\/2022&quot;, &quot;18&quot;:&quot;08\/17\/2022&quot;, &quot;19&quot;:&quot;08\/08\/2022&quot;, &quot;20&quot;:&quot;08\/05\/2022&quot;, &quot;21&quot;:&quot;08\/05\/2022&quot;, &quot;22&quot;:&quot;08\/03\/2022&quot;, &quot;23&quot;:&quot;05\/06\/2022&quot;, &quot;24&quot;:&quot;05\/04\/2022&quot; }, &quot;transactionType&quot;:{ &quot;0&quot;:&quot;Sell&quot;, &quot;1&quot;:&quot;Automatic Sell&quot;, &quot;2&quot;:&quot;Automatic Sell&quot;, &quot;3&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;4&quot;:&quot;Option Execute&quot;, &quot;5&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;6&quot;:&quot;Option Execute&quot;, &quot;7&quot;:&quot;Automatic Sell&quot;, &quot;8&quot;:&quot;Sell&quot;, &quot;9&quot;:&quot;Automatic Sell&quot;, &quot;10&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;11&quot;:&quot;Option Execute&quot;, &quot;12&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;13&quot;:&quot;Option Execute&quot;, &quot;14&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;15&quot;:&quot;Option Execute&quot;, &quot;16&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;17&quot;:&quot;Option Execute&quot;, &quot;18&quot;:&quot;Automatic Sell&quot;, &quot;19&quot;:&quot;Automatic Sell&quot;, &quot;20&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;21&quot;:&quot;Option Execute&quot;, &quot;22&quot;:&quot;Automatic Sell&quot;, &quot;23&quot;:&quot;Disposition (Non Open Market)&quot;, &quot;24&quot;:&quot;Automatic Sell&quot; }, &quot;sharesTraded&quot;:{ &quot;0&quot;:&quot;20,200&quot;, &quot;1&quot;:&quot;176,299&quot;, &quot;2&quot;:&quot;8,053&quot;, &quot;3&quot;:&quot;6,399&quot;, &quot;4&quot;:&quot;13,136&quot;, &quot;5&quot;:&quot;8,559&quot;, &quot;6&quot;:&quot;16,612&quot;, &quot;7&quot;:&quot;167,889&quot;, &quot;8&quot;:&quot;13,250&quot;, &quot;9&quot;:&quot;176,299&quot;, &quot;10&quot;:&quot;177,870&quot;, &quot;11&quot;:&quot;365,600&quot;, &quot;12&quot;:&quot;189,301&quot;, &quot;13&quot;:&quot;365,600&quot;, &quot;14&quot;:&quot;184,461&quot;, &quot;15&quot;:&quot;365,600&quot;, &quot;16&quot;:&quot;189,301&quot;, &quot;17&quot;:&quot;365,600&quot;, &quot;18&quot;:&quot;96,735&quot;, &quot;19&quot;:&quot;15,366&quot;, &quot;20&quot;:&quot;16,530&quot;, &quot;21&quot;:&quot;31,896&quot;, &quot;22&quot;:&quot;25,000&quot;, &quot;23&quot;:&quot;1,276&quot;, &quot;24&quot;:&quot;25,000&quot; } } </code></pre> <p>My current code is the attempt to delete/ filter out an entry if the value is &quot;Disposition (Non Open Market)&quot;:</p> <pre><code>import json data = json.load(open(&quot;AAPL22_institutional_table_MRKTVAL.json&quot;)) modified = lambda feature: 'Disposition (Non Open Market)' not in feature['transactionType'] data2 = filter(modified, data) open(&quot;AAPL22_institutional_table_MRKTVAL.json&quot;, &quot;w&quot;).write( json.dumps(data2, indent=4)) </code></pre> <p>The preferred output JSON (showing the entry being deleted on all 3 columns):</p> <pre><code>{ &quot;lastDate&quot;:{ &quot;0&quot;:&quot;11\/22\/2022&quot;, &quot;1&quot;:&quot;10\/28\/2022&quot;, &quot;2&quot;:&quot;10\/17\/2022&quot;, &quot;4&quot;:&quot;10\/15\/2022&quot;, &quot;6&quot;:&quot;10\/15\/2022&quot;, &quot;7&quot;:&quot;10\/03\/2022&quot;, &quot;8&quot;:&quot;10\/03\/2022&quot;, &quot;9&quot;:&quot;10\/03\/2022&quot;, &quot;11&quot;:&quot;10\/01\/2022&quot;, &quot;13&quot;:&quot;10\/01\/2022&quot;, &quot;15&quot;:&quot;10\/01\/2022&quot;, &quot;17&quot;:&quot;10\/01\/2022&quot;, &quot;18&quot;:&quot;08\/17\/2022&quot;, &quot;19&quot;:&quot;08\/08\/2022&quot;, &quot;21&quot;:&quot;08\/05\/2022&quot;, &quot;22&quot;:&quot;08\/03\/2022&quot;, &quot;24&quot;:&quot;05\/04\/2022&quot; }, &quot;transactionType&quot;:{ &quot;0&quot;:&quot;Sell&quot;, &quot;1&quot;:&quot;Automatic Sell&quot;, &quot;2&quot;:&quot;Automatic Sell&quot;, &quot;4&quot;:&quot;Option Execute&quot;, &quot;6&quot;:&quot;Option Execute&quot;, &quot;7&quot;:&quot;Automatic Sell&quot;, &quot;8&quot;:&quot;Sell&quot;, &quot;9&quot;:&quot;Automatic Sell&quot;, &quot;11&quot;:&quot;Option Execute&quot;, &quot;13&quot;:&quot;Option Execute&quot;, &quot;15&quot;:&quot;Option Execute&quot;, &quot;17&quot;:&quot;Option Execute&quot;, &quot;18&quot;:&quot;Automatic Sell&quot;, &quot;19&quot;:&quot;Automatic Sell&quot;, &quot;21&quot;:&quot;Option Execute&quot;, &quot;22&quot;:&quot;Automatic Sell&quot;, &quot;24&quot;:&quot;Automatic Sell&quot; }, &quot;sharesTraded&quot;:{ &quot;0&quot;:&quot;20,200&quot;, &quot;1&quot;:&quot;176,299&quot;, &quot;2&quot;:&quot;8,053&quot;, &quot;4&quot;:&quot;13,136&quot;, &quot;6&quot;:&quot;16,612&quot;, &quot;7&quot;:&quot;167,889&quot;, &quot;8&quot;:&quot;13,250&quot;, &quot;9&quot;:&quot;176,299&quot;, &quot;11&quot;:&quot;365,600&quot;, &quot;13&quot;:&quot;365,600&quot;, &quot;15&quot;:&quot;365,600&quot;, &quot;17&quot;:&quot;365,600&quot;, &quot;18&quot;:&quot;96,735&quot;, &quot;19&quot;:&quot;15,366&quot;, &quot;21&quot;:&quot;31,896&quot;, &quot;22&quot;:&quot;25,000&quot;, &quot;24&quot;:&quot;25,000&quot; } } </code></pre>
[ { "answer_id": 74632720, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "data = {\n \"lastDate\":{\n \"0\":\"11\\/22\\/2022\",\n \"1\":\"10\\/28\\/2022\",\n \"2\":\"10\\/17\\/2022\",\n \"3\":\"10\\/15\\/2022\",\n \"4\":\"10\\/15\\/2022\",\n \"5\":\"10\\/15\\/2022\",\n \"6\":\"10\\/15\\/2022\",\n \"7\":\"10\\/03\\/2022\",\n \"8\":\"10\\/03\\/2022\",\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"3\":\"Disposition (Non Open Market)\",\n \"4\":\"Option Execute\",\n \"5\":\"Disposition (Non Open Market)\",\n \"6\":\"Option Execute\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"3\":\"6,399\",\n \"4\":\"13,136\",\n \"5\":\"8,559\",\n \"6\":\"16,612\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n }\n}\n\nfor k,v in data[\"transactionType\"].copy().items():\n if v == \"Disposition (Non Open Market)\":\n for key in data: # Remove the key from all other nested dictionaries \n del data[key][k]\n\nprint(data)\n" }, { "answer_id": 74632758, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 3, "selected": true, "text": "import json\n\ndata = json.load(open(\"AAPL22_institutional_table_MRKTVAL.json\"))\n\ndelete_keys = []\n\nfor value in data['transactionType']:\n if data['transactionType'][value] == 'Disposition (Non Open Market)':\n delete_keys.append(value)\n\nprint(delete_keys)\n\nfor key in delete_keys:\n del data['transactionType'][key]\n del data['lastDate'][key]\n del data['sharesTraded'][key]\n\nprint(data)\n\nopen(\"AAPL22_institutional_table_MRKTVAL.json\", \"w\").write(\n json.dumps(data, indent=4))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18823431/" ]
74,632,544
<p>I created an element visibility trigger and attached it to my tag. The element visibility trigger was based on an id. It turns out that that id was not unique. Hence the tag connected to my trigger is being triggered for behaviors I don't want the tag triggered for. However there is a unique message that appears along with this id. Is there a way I can create a trigger that fires only when this message appears on the website? Thanks!</p> <p>I researched to see if there are any additional GTM triggers based on not only an id but also actual text on the page.</p>
[ { "answer_id": 74632720, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "data = {\n \"lastDate\":{\n \"0\":\"11\\/22\\/2022\",\n \"1\":\"10\\/28\\/2022\",\n \"2\":\"10\\/17\\/2022\",\n \"3\":\"10\\/15\\/2022\",\n \"4\":\"10\\/15\\/2022\",\n \"5\":\"10\\/15\\/2022\",\n \"6\":\"10\\/15\\/2022\",\n \"7\":\"10\\/03\\/2022\",\n \"8\":\"10\\/03\\/2022\",\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"3\":\"Disposition (Non Open Market)\",\n \"4\":\"Option Execute\",\n \"5\":\"Disposition (Non Open Market)\",\n \"6\":\"Option Execute\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"3\":\"6,399\",\n \"4\":\"13,136\",\n \"5\":\"8,559\",\n \"6\":\"16,612\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n }\n}\n\nfor k,v in data[\"transactionType\"].copy().items():\n if v == \"Disposition (Non Open Market)\":\n for key in data: # Remove the key from all other nested dictionaries \n del data[key][k]\n\nprint(data)\n" }, { "answer_id": 74632758, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 3, "selected": true, "text": "import json\n\ndata = json.load(open(\"AAPL22_institutional_table_MRKTVAL.json\"))\n\ndelete_keys = []\n\nfor value in data['transactionType']:\n if data['transactionType'][value] == 'Disposition (Non Open Market)':\n delete_keys.append(value)\n\nprint(delete_keys)\n\nfor key in delete_keys:\n del data['transactionType'][key]\n del data['lastDate'][key]\n del data['sharesTraded'][key]\n\nprint(data)\n\nopen(\"AAPL22_institutional_table_MRKTVAL.json\", \"w\").write(\n json.dumps(data, indent=4))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648637/" ]
74,632,566
<p>I am trying to create a sample noisy signal that I will be filtering in C. I have written the code in python but will be deploying it to a microcotroller so I want to create it in C.</p> <p>Here is the python code I am trying to replicate</p> <pre><code># 1000 samples per second sample_rate = 1000 # frequency in Hz center_freq = 20 # filter frequency in Hz cutoff_freq = 10 test_signal = np.linspace( start=0., stop=2. * pi * center_freq, num=sample_rate, endpoint=False ) test_signal = np.cos(test_signal) second_test_signal = np.random.randn(sample_rate) </code></pre> <p>I tried manually coding a linearlly spaced array but I cannot seem to get it to work. I have looked into libraries to make it easier but can't find any. Does anyone have any ideas on how to translate this python code into C a simple and easy to use way?</p> <p>Here is the C code I have so far. I am also wondering if I need to do this a completely different way?</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;math.h&gt; int sampleRate = 1000; int center_freq = 20; int cutoff_freq = 10; </code></pre>
[ { "answer_id": 74632720, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 0, "selected": false, "text": "data = {\n \"lastDate\":{\n \"0\":\"11\\/22\\/2022\",\n \"1\":\"10\\/28\\/2022\",\n \"2\":\"10\\/17\\/2022\",\n \"3\":\"10\\/15\\/2022\",\n \"4\":\"10\\/15\\/2022\",\n \"5\":\"10\\/15\\/2022\",\n \"6\":\"10\\/15\\/2022\",\n \"7\":\"10\\/03\\/2022\",\n \"8\":\"10\\/03\\/2022\",\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"3\":\"Disposition (Non Open Market)\",\n \"4\":\"Option Execute\",\n \"5\":\"Disposition (Non Open Market)\",\n \"6\":\"Option Execute\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"3\":\"6,399\",\n \"4\":\"13,136\",\n \"5\":\"8,559\",\n \"6\":\"16,612\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n }\n}\n\nfor k,v in data[\"transactionType\"].copy().items():\n if v == \"Disposition (Non Open Market)\":\n for key in data: # Remove the key from all other nested dictionaries \n del data[key][k]\n\nprint(data)\n" }, { "answer_id": 74632758, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 3, "selected": true, "text": "import json\n\ndata = json.load(open(\"AAPL22_institutional_table_MRKTVAL.json\"))\n\ndelete_keys = []\n\nfor value in data['transactionType']:\n if data['transactionType'][value] == 'Disposition (Non Open Market)':\n delete_keys.append(value)\n\nprint(delete_keys)\n\nfor key in delete_keys:\n del data['transactionType'][key]\n del data['lastDate'][key]\n del data['sharesTraded'][key]\n\nprint(data)\n\nopen(\"AAPL22_institutional_table_MRKTVAL.json\", \"w\").write(\n json.dumps(data, indent=4))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648642/" ]
74,632,576
<p>I need to find a regex that will match both date formats:</p> <pre><code>MM/dd/yyyy and M/d/yyyy ex. 01/31/2022, 1/1/2022, 12/13/2022, 12/1/2022 </code></pre> <p>So far I tried</p> <pre><code>^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9]{1}$)/[0-9]{4}$ </code></pre> <p>Which seems to be the closes to what I need, but it's still not perfect. I am on Java 7 and I need to validate user's input, thus I need to verify if they gave me correct date format. For example, if they enter <code>13/1/2022</code>, then <code>SimpleDateFormat</code> translates this to <code>Sun Jan 01 00:00:00 CET 2023</code>.</p>
[ { "answer_id": 74632659, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "\"M/d/yyyy\" M d DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"M/d/yyyy\");\nSystem.out.println(LocalDate.parse(\"01/31/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"1/1/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"12/13/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"12/1/2022\", formatter));\n 2022-01-31\n2022-01-01\n2022-12-13\n2022-12-01\n DateTimeFormatter LocalDate" }, { "answer_id": 74634019, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": true, "text": "java.time DateFormat#setLenient(boolean) false import java.text.ParseException;\nimport java.text.SimpleDateFormat;\n\npublic class Main {\n public static void main(String[] args) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"M/d/yyyy\");\n sdf.setLenient(false);\n String[] arr = { \"01/31/2022\", \"1/1/2022\", \"12/13/2022\", \"12/1/2022\", \"13/01/2022\" };\n\n for (String s : arr) {\n try {\n System.out.println(\"==================\");\n sdf.parse(s);\n System.out.println(s + \" is a valid date\");\n } catch (ParseException e) {\n System.out.println(e.getMessage());\n\n // Recommended so that the caller can handle the exception appropriately\n // throw new IllegalArgumentException(\"Invalid date\");\n }\n }\n }\n}\n ==================\n01/31/2022 is a valid date\n==================\n1/1/2022 is a valid date\n==================\n12/13/2022 is a valid date\n==================\n12/1/2022 is a valid date\n==================\nUnparseable date: \"13/01/2022\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873779/" ]
74,632,596
<p>I have a property in my state which is Map&lt;string, object | 'error'&gt; . When I get response from service I wish to update this map. I have tried below in the reducer</p> <pre><code> on(setMapData, (state, action) =&gt; { const { data } = action data.forEach( (value, id) =&gt; { let dataMap = state.dataMap dataMap.set(id, value) return { ...state, dataMap: {...state.dataMap, ...dataMap} } }) //Till here I can see dataMap having all the values in state. return { ...state //dataMap: state.dataMap } // But nothing is returned from here, my selectors are not getting invoked. }) </code></pre> <p>Below is my state object</p> <pre><code>export const initialState: dataState = { loading: true, dataMap: new Map&lt;string, object | 'error'&gt;() } </code></pre> <p>Please help me in this issue. Thanks in advance.</p>
[ { "answer_id": 74632659, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "\"M/d/yyyy\" M d DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"M/d/yyyy\");\nSystem.out.println(LocalDate.parse(\"01/31/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"1/1/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"12/13/2022\", formatter));\nSystem.out.println(LocalDate.parse(\"12/1/2022\", formatter));\n 2022-01-31\n2022-01-01\n2022-12-13\n2022-12-01\n DateTimeFormatter LocalDate" }, { "answer_id": 74634019, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": true, "text": "java.time DateFormat#setLenient(boolean) false import java.text.ParseException;\nimport java.text.SimpleDateFormat;\n\npublic class Main {\n public static void main(String[] args) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"M/d/yyyy\");\n sdf.setLenient(false);\n String[] arr = { \"01/31/2022\", \"1/1/2022\", \"12/13/2022\", \"12/1/2022\", \"13/01/2022\" };\n\n for (String s : arr) {\n try {\n System.out.println(\"==================\");\n sdf.parse(s);\n System.out.println(s + \" is a valid date\");\n } catch (ParseException e) {\n System.out.println(e.getMessage());\n\n // Recommended so that the caller can handle the exception appropriately\n // throw new IllegalArgumentException(\"Invalid date\");\n }\n }\n }\n}\n ==================\n01/31/2022 is a valid date\n==================\n1/1/2022 is a valid date\n==================\n12/13/2022 is a valid date\n==================\n12/1/2022 is a valid date\n==================\nUnparseable date: \"13/01/2022\"\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2261968/" ]
74,632,637
<p>I've tried all types of date extraction from this timestamp but nothing works.</p> <p>Data samples:</p> <ol> <li>Mon 2021 Jul 26 2021 8:26 PM</li> <li>Wed May 19 2021 22:54:00 GMT+0800 (Hong Kong Standard Time)</li> </ol> <p>Tried MOD, = Time,Minute, and Timevalue</p> <p>Does anyone have any idea?</p> <p>Tried MOD, = Time,Minute, and Timevalue. Expected to extract the date but it doesn't.</p>
[ { "answer_id": 74632721, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 0, "selected": false, "text": "regexextract() =to_date( value( regexextract( to_text(A2), \"^\\w+ (\\w+ \\w+ \\w+)\" ) ) )" }, { "answer_id": 74633798, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=INDEX(TEXT(IFNA(1*REGEXEXTRACT(TO_TEXT(A1:A), \n \"(\\w+ \\d+ \\d{4})\" ), \"​\"), \"dd/mm/e\"))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20001886/" ]
74,632,639
<p>I have a data frame (df) that is a larger version of this:</p> <pre><code>txnID date product sold repID lastName 1001 8/5/2020 Clobromizen 600 203 Kappoorthy 1002 6/28/2020 Alaraphosol 276 887 da Silva 1003 6/28/2020 Alaraphosol 184 887 da Silva 1004 4/16/2020 Diaprogenix 36 887 da Silva 1005 6/14/2020 Diaprogenix 40 887 da Silva 1006 5/19/2020 Xinoprozen 5640 332 McRowe 1007 8/23/2020 Diaprogenix 60 332 McRowe 1008 11/14/2020 Clobromizen 2880 332 McRowe 1009 9/26/2020 Colophrazen 738 203 Kappoorthy 1010 2/5/2020 Diaprogenix 20 332 McRowe 1011 9/23/2020 Gerantrazeophem 3740 100 Schwab 1012 12/4/2020 Clobromizen 1584 221 Sixt </code></pre> <p>I want to create a new data frame that takes the sum of all the sold products for each employee shown (All of the employees are shown), which would look something like this:</p> <pre><code>View(df1) lastName totalSold 1 Kappoorthy sum(df$sold) 2 da Silva sum(df$sold) 3 McRowe sum(df$sold) 4 Schwab sum(df$sold) 5 Sixt sum(df$sold) </code></pre>
[ { "answer_id": 74632663, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 2, "selected": false, "text": "dplyr library(dplyr)\n\ndf %>% \n filter(!(product %in% c(\"Xinoprozen\", \"Diaprogenix\") )%>%\n group_by(lastName) %>% \n summarize(totalSold = sum(sold,na.rm = TRUE))\n" }, { "answer_id": 74632707, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "aggregate aggregate(sold ~ lastName, sum, na.rm=TRUE, data=df)\n" }, { "answer_id": 74634378, "author": "Yomi.blaze93", "author_id": 16087142, "author_profile": "https://Stackoverflow.com/users/16087142", "pm_score": 2, "selected": false, "text": "library(dplyr) \n\n df%>%\n group_by(lastName)%>%\n summarise(Totalsold = sum(sold))\n df%>%\n filter(!(product %in% c(\"Xinoprozen\", product!=\"Diaprogenix\")))%>%\n group_by(lastName)%>%\n summarise(Totalsold = sum(sold))\n" }, { "answer_id": 74634599, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 2, "selected": false, "text": "aggregate(sold~lastName, df, sum)\n\n lastName sold\n1 da Silva 536\n2 Kappoorthy 1338\n3 McRowe 8600\n4 Schwab 3740\n5 Sixt 1584\n aggregate(sold~lastName, df, sum, subset = !product %in%c(\"Xinoprozen\",\"Diaprogenix\"))\n lastName sold\n1 da Silva 460\n2 Kappoorthy 1338\n3 McRowe 2880\n4 Schwab 3740\n5 Sixt 1584\n NA aggregate(sold~lastName, df, sum, na.rm =TRUE)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19095892/" ]
74,632,645
<p><a href="https://i.stack.imgur.com/iJRPM.png" rel="nofollow noreferrer">example background</a></p> <p>I've been trying to replicate the background pattern on the photo above. It seems to me like there is a linear gradient with 2 radial gradients nested within it. But I'm not sure... Can someone please confirm? Can someone explained how to position the 2 radial gradients within the actual background? Thanks for helping.</p> <p>I've searched google multiple times but my queries can't seem to find what I am looking for. I've tried nesting a radial-gradient within my linear-gradient but it doesn't work.</p> <pre><code>background: linear-gradient(45deg, radial-gradient(#b1f2ff, #63e5ff, #3cdfff), radial-gradient(#dd2288, #ff0057, #cc08c7)); </code></pre>
[ { "answer_id": 74632829, "author": "mahdi gholami", "author_id": 19267262, "author_profile": "https://Stackoverflow.com/users/19267262", "pm_score": 1, "selected": false, "text": "div{\nwidth:100%;\nheight:400px;\nbackground-image:radial-gradient(circle at 20% 70%,yellow 0%, transparent 30%),linear-gradient(45deg, #6634ff, #00e5ff);\n} <div></div>" }, { "answer_id": 74633042, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 0, "selected": false, "text": "radial-gradient * {\n margin: 0;\n}\n\nbody {\n width: 100vw;\n height: 100vh;\n background: radial-gradient(circle at 25% 60%, #3BBFFE 0, transparent 25%), radial-gradient(circle at 70% top, #D21372 0, #7120FD 60%);\n}" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398101/" ]
74,632,650
<p>Having a dataframe like this:</p> <pre><code>structure(list(id = c(&quot;id1&quot;, &quot;id1&quot;, &quot;id2&quot;, &quot;id2&quot;, &quot;id3&quot;, &quot;id3&quot; ), title_num = c(1, 2, 1, 2, 1, 2), title_name = c(&quot;amazon1&quot;, &quot;yahoo2&quot;, &quot;google1&quot;, NA, &quot;yahoo1&quot;, &quot;amazon2&quot;)), row.names = c(NA, -6L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre> <p>and another one like this:</p> <pre><code> dfcheck &lt;- structure(list(status = c(&quot;open/close&quot;, &quot;close&quot;, &quot;open&quot;), stock = c(&quot;company energy&quot;, &quot;goods and books&quot;, &quot;other&quot;), name = c(&quot;amazon1;google1&quot;, &quot;google3;yahoo1&quot;, &quot;yahoo2;amazon2;google2&quot;)), class = &quot;data.frame&quot;, row.names = c(NA, -3L)) </code></pre> <p>How is it possible to have an output like this:</p> <pre><code>id title_num title_name stock status id1 1 amazon1 company energy open/close id1 2 yahoo2 other open id2 1 google1 company energy open/close id2 2 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; id3 1 yahoo1 goods and books close id3 2 amazon2 other open </code></pre>
[ { "answer_id": 74632829, "author": "mahdi gholami", "author_id": 19267262, "author_profile": "https://Stackoverflow.com/users/19267262", "pm_score": 1, "selected": false, "text": "div{\nwidth:100%;\nheight:400px;\nbackground-image:radial-gradient(circle at 20% 70%,yellow 0%, transparent 30%),linear-gradient(45deg, #6634ff, #00e5ff);\n} <div></div>" }, { "answer_id": 74633042, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 0, "selected": false, "text": "radial-gradient * {\n margin: 0;\n}\n\nbody {\n width: 100vw;\n height: 100vh;\n background: radial-gradient(circle at 25% 60%, #3BBFFE 0, transparent 25%), radial-gradient(circle at 70% top, #D21372 0, #7120FD 60%);\n}" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224217/" ]
74,632,667
<p>I have two lists:</p> <pre><code>expected = [&quot;apple&quot;, &quot;banana&quot;, &quot;pear&quot;] actual = [&quot;banana_yellow&quot;, &quot;apple&quot;, &quot;pear_green&quot;] </code></pre> <p>I'm trying to assert that expected = actual. Even though the color is added at the end to some elements, it should still return true.</p> <p>Things I tried:</p> <pre><code>for i in expected: assert i in actual </code></pre> <p>I was hoping something like this would work but it's trying to match the first element apple to banana and returns false rather than checking the entire list and returns true if there is apple anywhere in the list. I was hoping someone can help?</p>
[ { "answer_id": 74632829, "author": "mahdi gholami", "author_id": 19267262, "author_profile": "https://Stackoverflow.com/users/19267262", "pm_score": 1, "selected": false, "text": "div{\nwidth:100%;\nheight:400px;\nbackground-image:radial-gradient(circle at 20% 70%,yellow 0%, transparent 30%),linear-gradient(45deg, #6634ff, #00e5ff);\n} <div></div>" }, { "answer_id": 74633042, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 0, "selected": false, "text": "radial-gradient * {\n margin: 0;\n}\n\nbody {\n width: 100vw;\n height: 100vh;\n background: radial-gradient(circle at 25% 60%, #3BBFFE 0, transparent 25%), radial-gradient(circle at 70% top, #D21372 0, #7120FD 60%);\n}" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19643955/" ]
74,632,677
<p>I'm attempting to setup an <code>async</code> function so that my next step will not start until the function finishes.</p> <p>I coded one module to connect to mongodb server, and then check to see if it's connected. These two functions work well together.</p> <pre><code>const mongoose = require('mongoose'); const mongoServer = `mongodb://127.0.0.1/my_database`; const consoleColor = { green: '\x1b[42m%s\x1b[0m', yellow: '\x1b[43m%s\x1b[0m', red: '\x1b[41m%s\x1b[0m' } exports.connectMongoose = () =&gt; { mongoose.connect(mongoServer, { useNewUrlParser: true }); } exports.checkState = () =&gt; { const mongooseState = mongoose.STATES[mongoose.connection.readyState]; return new Promise((resolve) =&gt; { if (mongooseState === 'connected') { console.log(consoleColor.green, `Mongoose is ${mongooseState}.`); resolve(); } else if (mongooseState === 'connecting') { console.log(`Mongoose is ${mongooseState}.`); setTimeout(() =&gt; { this.checkState(); }, 1000); } else { console.log(consoleColor.red, `Mongoose is ${mongooseState}.`); } }); } </code></pre> <p>The next thing I tried to do was connect to the mongo db using my connectMongoose function, and then call a second function that will run my checkState function, and only perform the next function if it resolves (the if statement for the &quot;connected&quot; state.</p> <pre><code>const dbconfig = require('./dbconfig') dbconfig.connectMongoose() const testAwait = async () =&gt; { await dbconfig.checkState(); console.log(&quot;Do this next&quot;); } testAwait() </code></pre> <p>The <code>testAwait</code> function runs, but it does not get to the <code>console.log</code> function which leads me to believe I'm doing something wrong when passing the resolve.</p>
[ { "answer_id": 74633297, "author": "OliverRadini", "author_id": 5011469, "author_profile": "https://Stackoverflow.com/users/5011469", "pm_score": 2, "selected": true, "text": "setTimeout(() => {\n this.checkState();\n}, 1000);\n let attempts = 0;\n\nconst isConnected = async () => {\n console.log(\"checking connection state...\");\n attempts++;\n if (attempts >= 5) {\n return true;\n }\n return false;\n}\n\nconst wait = ms => new Promise(res => setTimeout(res, ms));\n\nconst checkState = async () => {\n while (!(await isConnected())) {\n await wait(1000);\n }\n \n return;\n};\n\ncheckState().then(() => console.log(\"done\")); const checkState = () => {\n const mongooseState = Math.random() > 0.2 ? \"connecting\" : \"connected\";\n \n return new Promise((resolve) => {\n if (mongooseState === 'connected') {\n console.log(`Mongoose is ${mongooseState}.`);\n resolve();\n } else if (mongooseState === 'connecting') {\n console.log(`Mongoose is ${mongooseState}.`);\n setTimeout(() => {\n checkState().then(resolve);\n }, 1000);\n }\n });\n} \n\ncheckState().then(() => console.log(\"done\"));" }, { "answer_id": 74633521, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 0, "selected": false, "text": "resolve reject const random = parseInt(Math.random());\nconst testAwait =\n async() => {\n await new Promise((resolve, reject) => {\n if (random === 0) {\n resolve(random);\n } else {\n reject(random);\n }\n });\n console.log(\"Do this next\");\n }\ntestAwait()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12986274/" ]
74,632,776
<p>Been spending the past few hours figuring out why Axios is doing this.</p> <p>I tried to do this in the request library in nodeJS and it works fine, but Axios isn't.</p> <p>Essentially what i'm doing is sending a request of XML data:</p> <pre><code> var options = { 'method': 'POST', 'url': 'https://rvices.svc', 'headers': { 'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'http://etProject' }, data: xmlData}; </code></pre> <p>with XMLData looking simliar to :</p> <pre><code> let xmlData = `&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:com=&quot;http://p&quot; xmlns:pws=&quot;http://&quot; </code></pre> <p>etc etc (it has mostly private data in it so I stripped most of it out).</p> <p>when I try to use axios to get this</p> <pre><code>const testData = await axios(options) </code></pre> <p>i get returned a whole lot of code that looks like this:</p> <pre><code> '���_\x1B�\f�10�\x17�Ч�{O�\x00��5h�S�������\x0F���s�(+Ғ�\x0F�����m�\x15\x01\x13��6b��\x06%\x00��\x15p8&lt;;��W�4����\x0B���\x01���e�\x7FvZ�{���Ï������\x06��-�z��\x01}�!�r�A�\x13��\x11O�w6ũ���{�\x03����;{����\x01\x7Fy��KoՎ���\x1Bߚe��W��mЇ�qD�a��[�7Ӄ���@��F&lt;\x1C/mF�{\x03�h��#�\x16�\x11\x1F\x1F�L9\x0FM\x8A\x0E�\x 17�h���\x03�4�7�f=bj*8�p�\x13_�\x17�5���_�Ӑ�|M&gt;����\r��F�8q�iE�#��\x0E?�v�������O�xq3���x�Q�튱\x1F?G&amp;HG9��6���V\x1B⫯Ev\x01rc\x13\x10�\'�7��`�Ii��x�~LM6�#˒74#@�����f�*\x7F\x16(5|\x1CWl��\x07\t\x1F��z�\x15\x00\x1B��4�\x13���LCTG�\x1FI�����\fec�h\x02�~��i`�:Ғ�\x0F���y\b#�]V��g��Ӈ�\x14|���6~\x19~c`�/�O���M\x01��k\x 10�\'+���\x07S\r?|��T�A�\x0FӒ�\x0F��ܷ\'.s�!&gt;�tbX\x05�\fs\x18�\r�&quot;`���\x10lV٠\x05@ܲ�\x02\x0E\x07h���\n' + '���[�7}�&gt;54 r�����ʦ\x15�\x17��\x0E: </code></pre> <p>that is the right amount of characters (100k +) but jumbled</p> <p>compared to doing this with request which returns the xml back I expect ala:</p> <pre><code>&lt;/b:ProjectTaskTypeDetail&gt;&lt;/b:PwsProjectTaskTypeElement&gt;&lt;b:PwsProjectTaskTypeElement&gt;&lt;b:ProjectTaskTypeDetail&gt;&lt;b:ExternalSystemIdentifier i:nil=&quot;true&quot;/&gt;&lt;b:ProjectTaskTypeId i:nil=&quot;true&quot;/&gt;&lt;b:ProjectTaskTypeUid&gt;5776&lt;/b:ProjectTaskTypeUid&gt;&lt;b:ProjectTaskTypeName&gt;Faon&lt;/b:Proj ectTaskTypeName&gt; </code></pre> <p>one thing I noticed is axios is breaking my request up into multiple lines like this:</p> <pre><code> '&lt;com:PwsProjectRef&gt;&lt;com:ProjectCode&gt;201268&lt;/com:ProjectCode&gt;&lt;/com:PwsProjectRef&gt;\n' + '\n' + '&lt;com:PwsProjectRef&gt;&lt;com:ProjectCode&gt;210115-01&lt;/com:ProjectCode&gt;&lt;/com:PwsProjectRef&gt;\n' + '\n' + </code></pre> <p>even though there's no \n's in my request or breaks like that.</p> <p>So i'm wondering if anyone has ran into this before and knows how to solve it?</p> <p>Request is working but request (from what I can tell?) doesn't work with asynch code (i'm probably wrong about this)</p> <p>Sorry for the vagueness!</p>
[ { "answer_id": 74633297, "author": "OliverRadini", "author_id": 5011469, "author_profile": "https://Stackoverflow.com/users/5011469", "pm_score": 2, "selected": true, "text": "setTimeout(() => {\n this.checkState();\n}, 1000);\n let attempts = 0;\n\nconst isConnected = async () => {\n console.log(\"checking connection state...\");\n attempts++;\n if (attempts >= 5) {\n return true;\n }\n return false;\n}\n\nconst wait = ms => new Promise(res => setTimeout(res, ms));\n\nconst checkState = async () => {\n while (!(await isConnected())) {\n await wait(1000);\n }\n \n return;\n};\n\ncheckState().then(() => console.log(\"done\")); const checkState = () => {\n const mongooseState = Math.random() > 0.2 ? \"connecting\" : \"connected\";\n \n return new Promise((resolve) => {\n if (mongooseState === 'connected') {\n console.log(`Mongoose is ${mongooseState}.`);\n resolve();\n } else if (mongooseState === 'connecting') {\n console.log(`Mongoose is ${mongooseState}.`);\n setTimeout(() => {\n checkState().then(resolve);\n }, 1000);\n }\n });\n} \n\ncheckState().then(() => console.log(\"done\"));" }, { "answer_id": 74633521, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 0, "selected": false, "text": "resolve reject const random = parseInt(Math.random());\nconst testAwait =\n async() => {\n await new Promise((resolve, reject) => {\n if (random === 0) {\n resolve(random);\n } else {\n reject(random);\n }\n });\n console.log(\"Do this next\");\n }\ntestAwait()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15006497/" ]
74,632,777
<p>My goal is to create simple search filter by name in html/javascript for data that I am getting from API in JSON format. In bash script I already formatted data so it is in right format for me to filter it later in javascript:</p> <p>Data ready to be pushed/imported into let jsonData array (inside html file) from data file (example.json):</p> <pre><code>{&quot;name&quot;:&quot;vnode&quot;,&quot;address&quot;:&quot;10.19.110.51&quot;,&quot;group&quot;:&quot;windows&quot;,&quot;responsible&quot;:&quot;Alen&quot;}, {&quot;name&quot;:&quot;vnode2.izum.pri&quot;,&quot;address&quot;:&quot;10.1.30.100&quot;,&quot;group&quot;:&quot;windows&quot;,&quot;responsible&quot;:&quot;Mario&quot;}, {&quot;name&quot;:&quot;vnode3&quot;,&quot;address&quot;:&quot;10.19.110.52&quot;,&quot;group&quot;:&quot;windows&quot;,&quot;responsible&quot;:&quot;John&quot;} </code></pre> <p><strong>I want to send this data from example.json and insert it into jsonData array inside javascript (index.html), How do I do it?</strong></p> <p>This is inside index.html:</p> <pre><code>&lt;script&gt; let jsonData = `[ **DATA GOES HERE** ]` function search_server() { let input = document.getElementById(&quot;myInput&quot;).value; input = input.toLowerCase(); let x = document.querySelector(&quot;#myUL&quot;); x.innerHTML = &quot;1&quot;; for (i = 0; i &lt; data.length; i++) { let obj = data[i]; if (obj.name.toLowerCase().includes(input)) { const elem = document.createElement(&quot;li&quot;); elem.innerHTML = `${obj.name} , ${obj.address} , ${obj.group} , ${obj.responsible}`; x.appendChild(elem); } } } &lt;/script&gt; </code></pre> <p>I managed somehow to insert results from bash to html, but I only managed to do it into div class:</p> <p>Method for sending bash results from file into div class element:</p> <pre><code>reg='&lt;div class=&quot;content-middle&quot;&gt;' while IFS= read -r line; do printf '%s\n' &quot;$line&quot; [[ $line =~ $reg ]] &amp;&amp; cat /usr/share/inventory/data.txt done &lt; /usr/share/inventory/indextemplate.html &gt; /usr/share/inventory/index.html </code></pre> <p><strong>So here is where I managed to send data:</strong></p> <pre><code>&lt;div class=&quot;content-middle&quot;&gt; &lt;/div&gt; </code></pre> <p><strong>No success on trying it to send into javascript:</strong></p> <pre><code>reg='let jsonData = `[' while IFS= read -r line; do printf '%s\n' &quot;$line&quot; [[ $line =~ $reg ]] &amp;&amp; cat /usr/share/inventory/data.txt done &lt; /usr/share/inventory/indextemplate.html &gt; /usr/share/inventory/index.html </code></pre>
[ { "answer_id": 74633297, "author": "OliverRadini", "author_id": 5011469, "author_profile": "https://Stackoverflow.com/users/5011469", "pm_score": 2, "selected": true, "text": "setTimeout(() => {\n this.checkState();\n}, 1000);\n let attempts = 0;\n\nconst isConnected = async () => {\n console.log(\"checking connection state...\");\n attempts++;\n if (attempts >= 5) {\n return true;\n }\n return false;\n}\n\nconst wait = ms => new Promise(res => setTimeout(res, ms));\n\nconst checkState = async () => {\n while (!(await isConnected())) {\n await wait(1000);\n }\n \n return;\n};\n\ncheckState().then(() => console.log(\"done\")); const checkState = () => {\n const mongooseState = Math.random() > 0.2 ? \"connecting\" : \"connected\";\n \n return new Promise((resolve) => {\n if (mongooseState === 'connected') {\n console.log(`Mongoose is ${mongooseState}.`);\n resolve();\n } else if (mongooseState === 'connecting') {\n console.log(`Mongoose is ${mongooseState}.`);\n setTimeout(() => {\n checkState().then(resolve);\n }, 1000);\n }\n });\n} \n\ncheckState().then(() => console.log(\"done\"));" }, { "answer_id": 74633521, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 0, "selected": false, "text": "resolve reject const random = parseInt(Math.random());\nconst testAwait =\n async() => {\n await new Promise((resolve, reject) => {\n if (random === 0) {\n resolve(random);\n } else {\n reject(random);\n }\n });\n console.log(\"Do this next\");\n }\ntestAwait()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13365019/" ]
74,632,789
<p>I am trying to replicate this plot using ggplot</p> <pre><code>pacman::p_load(tidyverse, pls, remotes) install_github(&quot;rwehrens/ChemometricsWithR&quot;) data(gasoline) wavelengths &lt;- seq(900,1700, 2) matplot(wavelengths, t(gasoline$NIR), type = &quot;l&quot;, lty = 1, xlab = &quot;Wavelength (nm)&quot;, ylab = &quot;1/R&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/c2ZQK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c2ZQK.png" alt="pic matplot" /></a> but cannot seem to make it work. The <code>gasoline</code> dataset is a tricky one: one of the two variables is a matrix which I have never encountered before. How can I clean up this dataset to make it tidy? I tried the following:</p> <pre><code>gasoline2 &lt;- as.data.frame(as.matrix(gasoline)) %&gt;% pivot_longer(cols = -c(octane), names_to = &quot;wavelength&quot;, values_to = &quot;1/R&quot;) </code></pre> <p>but cannot seem to This code:</p> <pre><code>ggplot(gasoline, mapping = aes(x = wavelengths, y = t(gasoline$NIR)))+ geom_line(mapping = aes(color = octane)) </code></pre> <p>is returning this error:</p> <pre><code>Error in `geom_line()`: ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in `check_aesthetics()`: ! Aesthetics must be either length 1 or the same as the data (60) ✖ Fix the following mappings: `x` and `y` Backtrace: 1. base (local) `&lt;fn&gt;`(x) 2. ggplot2:::print.ggplot(x) 4. ggplot2:::ggplot_build.ggplot(x) 5. ggplot2:::by_layer(...) 12. ggplot2 (local) f(l = layers[[i]], d = data[[i]]) 13. l$compute_aesthetics(d, plot) 14. ggplot2 (local) compute_aesthetics(..., self = self) 15. ggplot2:::check_aesthetics(evaled, n) </code></pre>
[ { "answer_id": 74632790, "author": "user7264", "author_id": 16085883, "author_profile": "https://Stackoverflow.com/users/16085883", "pm_score": 1, "selected": false, "text": "pacman::p_load(tidyverse, pls, remotes)\ninstall_github(\"rwehrens/ChemometricsWithR\")\n\ngasoline2 <- as.data.frame(as.matrix(gasoline)) %>% \n pivot_longer(cols = -c(octane),\n names_to = \"wavelength\",\n values_to = \"1/R\") %>% \n mutate(wavelength = str_remove_all(wavelength, \"[^[:digit:]]\"))\n\nggplot(gasoline2, mapping = aes(x = wavelength, y = `1/R`))+\n geom_line(mapping = aes(color = octane))\n gasoline2 <- as.data.frame(as.matrix(gasoline)) %>% \n mutate(group = row_number()) %>%\n relocate(group, .after = octane) %>% \n pivot_longer(cols = -c(octane, group),\n names_to = \"wavelength\",\n values_to = \"spectra\") %>% \n mutate(wavelength = as.numeric(str_remove_all(wavelength, \"[^[:digit:]]\"))) %>% \n mutate(octane = as.factor(octane))\n\nggplot(gasoline2, mapping = aes(x = wavelength, y = `spectra`, color = octane, group = group))+\n geom_line(linewidth = 0.5)+\n scale_color_discrete(guide = \"none\")+\n xlab(label = \"\\nWavelength (nm)\")+\n ylab(label = \"1/R\\n\")+\n theme_classic()+\n scale_y_continuous(n.breaks = 7)+\n scale_x_continuous(breaks = seq(1000,1600,200))\n" }, { "answer_id": 74633473, "author": "Esther", "author_id": 20649000, "author_profile": "https://Stackoverflow.com/users/20649000", "pm_score": 2, "selected": false, "text": "pacman::p_load(tidyverse, pls, remotes)\ninstall_github(\"rwehrens/ChemometricsWithR\")\n\ngasoline2 <- as.data.frame(as.matrix(gasoline)) %>% \n pivot_longer(cols = -c(octane),\n names_to = \"wavelength\",\n values_to = \"1/R\") %>% \n # From the above code of @user7264, add as.numeric()\n mutate(wavelength = as.numeric(str_remove_all(wavelength, \"[^[:digit:]]\")))\n\nggplot(gasoline2, mapping = aes(x = wavelength, y = `1/R`)) +\n geom_line(mapping = aes(color = octane)) +\n scale_x_continuous(breaks = seq(1000, 2000, 200)) +\n scale_colour_continuous(type = \"viridis\") +\n theme_bw()\n" }, { "answer_id": 74633618, "author": "Eric Scott", "author_id": 8117178, "author_profile": "https://Stackoverflow.com/users/8117178", "pm_score": 2, "selected": true, "text": "scale_color_manual() scale_color_*() \n#give every octane a unique ID for grouping later on\ngasoline <- \n gasoline |> \n mutate(group = 1:n())\n\n#colbind matrix-column as a dataframe\ngasoline2 <- \n bind_cols(\n gasoline |> select(octane, group),\n gasoline |> pull(NIR)\n ) |> \n # convert colnames to numeric wavelengths\n pivot_longer(\n cols = c(-octane, -group),\n names_to = \"wavelength\",\n values_to = \"1/R\",\n names_pattern = \"(\\\\d+)\",\n names_transform = as.numeric\n ) |> \n # octane as factor for line colors\n mutate(octane = as.factor(octane)) \n\n\nggplot(gasoline2,\n #group aesthetic to plot separate lines for repeat values of octane\n aes(x = wavelength, y = `1/R`, color = octane, group = group)) +\n geom_line(size = .7) +\n scale_color_discrete(guide = \"none\") +\n theme_classic()\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16085883/" ]
74,632,796
<p>I am trying to delete an item from a shopping cart and I am using the filter hook to accomplish this. I have looked at the documentation for this and at the answers here on stack overflow. unfortunately no luck.</p> <p>this is my code for the entire component. the function is of course &quot;deleteItemFromBasket&quot; and it is being called at the onclick on the delete button:</p> <pre><code>function CheckoutProduct({id, title, price, description, rating, category, image }) { const [basket, addToBasket] = useAppContext(); const deleteItemFromBasket = (id) =&gt; { addToBasket(basket.filter((task) =&gt; task.id !== id)); }; return ( &lt;div&gt; {basket.map((element) =&gt; { if (element === id) { return ( &lt;div className='grid grid-cols-5 border-b pb-4'&gt; {/* far left */} &lt;Image src={image} height={200} width={200} objectFit='contain' /&gt; {/* middle */} &lt;div className=&quot;col-span-3 mx-5&quot;&gt; &lt;p&gt;{title}&lt;/p&gt; &lt;p className='text-xs my-2 line-clamp-3'&gt;{description}&lt;/p&gt; &lt;button onClick={deleteItemFromBasket} className='button'&gt;delete&lt;/button&gt; &lt;h1&gt;items ID in basket: {basket}&lt;/h1&gt; &lt;h1&gt;length of array: {basket.length}&lt;/h1&gt; &lt;/div&gt; {/* right */} &lt;div&gt; &lt;p&gt;${price}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; ) } })} &lt;/div&gt; ) } </code></pre> <p>here is the code of the context provider</p> <pre><code>import React, { createContext, useContext, useState } from 'react'; const AppContext = createContext(); export function AppWrapper({ children }) { var [basket, addToBasket]= useState([]); return ( &lt;AppContext.Provider value={[basket, addToBasket]}&gt; {children} &lt;/AppContext.Provider&gt; ); } export function useAppContext() { return useContext(AppContext); } </code></pre>
[ { "answer_id": 74632854, "author": "Zehan Khan", "author_id": 16884475, "author_profile": "https://Stackoverflow.com/users/16884475", "pm_score": -1, "selected": false, "text": "function CheckoutProduct({id, title, price, description, rating, category, image }) {\n const [baskets, addToBasket] = useAppContext();\n\n const deleteItemFromBasket = (id) => {\n addToBasket( baskets.filter((task) => task.id != id) );\n };\n\n return (\n <div>\n {baskets.map((basket) => {\n return (\n <div className='grid grid-cols-5 border-b pb-4'>\n {/* far left */}\n <Image src={image} height={200} width={200} objectFit='contain' />\n\n \n {/* middle */}\n <div className=\"col-span-3 mx-5\">\n <p>{title}</p>\n <p className='text-xs my-2 line-clamp-3'>{description}</p>\n\n <button onClick={ ()=> deleteItemFromBasket( basket.id ) } className='button'>delete</button>\n\n <h1>items ID in basket: {basket.id}</h1>\n <h1>length of array: {basket.length}</h1>\n </div>\n\n {/* right */} \n <div>\n <p>${price}</p>\n </div> \n </div> \n )\n }\n })}\n </div>\n )\n}\n\n" }, { "answer_id": 74632895, "author": "Joe Lissner", "author_id": 5552874, "author_profile": "https://Stackoverflow.com/users/5552874", "pm_score": 0, "selected": false, "text": "basket id const deleteItemFromBasket = (id) => {\n addToBasket(basket.filter((element) => element !== id));\n};\n addToBasket" }, { "answer_id": 74633805, "author": "Cameron Austin", "author_id": 14108719, "author_profile": "https://Stackoverflow.com/users/14108719", "pm_score": 0, "selected": false, "text": "import React from 'react';\nimport Image from 'next/image'\nimport { useAppContext } from '../state'\n\n\nfunction CheckoutProduct({id, title, price, description, rating, category, image }) {\n const [basket, addToBasket] = useAppContext();\n\n const deleteItemFromBasket = (item) => {\n\n addToBasket((current) => current.filter((element) => element !== item));\n };\n\n\n return (\n <div>\n {basket.map((element) => {\n if (element === id) {\n return (\n <div className='grid grid-cols-5 border-b pb-4'>\n {/* far left */}\n <Image src={image} height={200} width={200} objectFit='contain' />\n\n \n {/* middle */}\n <div className=\"col-span-3 mx-5\">\n <p>{title}</p>\n <p className='text-xs my-2 line-clamp-3'>{description}</p>\n {/* <button onClick={deleteItemFromBasket(element)} >delete item</button> */}\n <button onClick={ ()=> deleteItemFromBasket(id)} className='button'>delete</button>\n <h1>items ID in basket: {basket}</h1>\n <h1>length of array: {basket.length}</h1>\n </div>\n\n {/* right */} \n <div>\n <p>${price}</p>\n </div> \n </div> \n )\n }\n })}\n </div>\n )\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14108719/" ]
74,632,798
<p>I need to shift valid values to the top the of dataframe withing each <code>id</code>. Here is an example dataset:</p> <pre><code>df &lt;- data.frame(id = c(1,1,1,2,2,2,3,3,3,3), itemid = c(1,2,3,1,2,3,1,2,3,4), values = c(1,NA,0,NA,NA,0,1,NA,0,NA)) df id itemid values 1 1 1 1 2 1 2 NA 3 1 3 0 4 2 1 NA 5 2 2 NA 6 2 3 0 7 3 1 1 8 3 2 NA 9 3 3 0 10 3 4 NA </code></pre> <p>excluding the id column, when there is a missing value in <code>values</code> column, I want to shift all values aligned to the top for each <code>id</code>.</p> <p>How can I get this desired dataset below?</p> <pre><code>df1 id itemid values 1 1 1 1 2 1 2 0 3 1 3 NA 4 2 1 0 5 2 2 NA 6 2 3 NA 7 3 1 1 8 3 2 0 9 3 3 NA 10 3 4 NA </code></pre>
[ { "answer_id": 74632870, "author": "Ben", "author_id": 3460670, "author_profile": "https://Stackoverflow.com/users/3460670", "pm_score": 4, "selected": true, "text": "tidyverse arrange values library(tidyverse)\n\ndf %>%\n arrange(id, is.na(values))\n id itemid values\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 1 3 0\n 3 1 2 NA\n 4 2 3 0\n 5 2 1 NA\n 6 2 2 NA\n 7 3 1 1\n 8 3 3 0\n 9 3 2 NA\n10 3 4 NA\n itemid mutate values NA df %>%\n group_by(id) %>%\n mutate(across(.cols = values, ~values[order(is.na(.))]))\n id itemid values\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 1 2 0\n 3 1 3 NA\n 4 2 1 0\n 5 2 2 NA\n 6 2 3 NA\n 7 3 1 1\n 8 3 2 0\n 9 3 3 NA\n10 3 4 NA\n" }, { "answer_id": 74633140, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "ave order > transform(df, values = ave(values, id, FUN = function(x) x[order(is.na(x))]))\n id itemid values\n1 1 1 1\n2 1 2 0\n3 1 3 NA\n4 2 1 0\n5 2 2 NA\n6 2 3 NA\n7 3 1 1\n8 3 2 0\n9 3 3 NA\n10 3 4 NA\n" }, { "answer_id": 74633164, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 2, "selected": false, "text": "data.table library(data.table)\n\nsetDT(df)[, values := values[order(is.na(values))], id][]\n#> id itemid values\n#> 1: 1 1 1\n#> 2: 1 2 0\n#> 3: 1 3 NA\n#> 4: 2 1 0\n#> 5: 2 2 NA\n#> 6: 2 3 NA\n#> 7: 3 1 1\n#> 8: 3 2 0\n#> 9: 3 3 NA\n#> 10: 3 4 NA\n" }, { "answer_id": 74636452, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "id completed_first <- function(x) {\n completed <- x[!is.na(x)]\n length(completed) <- length(x)\n completed\n}\n\nlibrary(dplyr)\n\ndf %>%\n group_by(id) %>%\n mutate(\n values = completed_first(values)\n ) %>%\n ungroup()\n# # A tibble: 10 × 3\n# id itemid values\n# <dbl> <dbl> <dbl>\n# 1 1 1 1\n# 2 1 2 0\n# 3 1 3 NA\n# 4 2 1 0\n# 5 2 2 NA\n# 6 2 3 NA\n# 7 3 1 1\n# 8 3 2 0\n# 9 3 3 NA\n# 10 3 4 NA\n itemid library(dplyr)\n\ndf %>%\n group_by(id) %>%\n mutate(\n values = values[order(is.na(values))]\n ) %>%\n ungroup()\n# # A tibble: 10 × 3\n# id itemid values\n# <dbl> <dbl> <dbl>\n# 1 1 1 1\n# 2 1 2 0\n# 3 1 3 NA\n# 4 2 1 0\n# 5 2 2 NA\n# 6 2 3 NA\n# 7 3 1 1\n# 8 3 2 0\n# 9 3 3 NA\n# 10 3 4 NA\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5933306/" ]
74,632,800
<p>I need an output of current count vs total count in single line. I would like to know if this could be done Via Bash using 'for' 'while' loop.</p> <p>Expecting an output that should only update the count and should not display multiple lines</p> <p>File Content</p> <pre><code>$ cat ~/test.rtf hostname1 hostname2 hostname3 hostname4 </code></pre> <pre><code>#!/bin/sh j=1 k=$(cat ~/test.rtf | wc -l) for i in $(cat ~/test.rtf); do echo &quot;Working on line ($j/$k)&quot; echo &quot;$i&quot; #or any other command for i j=$((j+1)) done </code></pre> <p>EX:</p> <pre><code>Working on line (2/4) </code></pre> <p>Not like,</p> <pre><code>Working on line (2/4) Working on line (3/4) </code></pre>
[ { "answer_id": 74633041, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 0, "selected": false, "text": "file=~/test.rtf\nnl=$(wc -l \"$file\")\nnl=${nl%%[[:blank:]]*}\ni=0\nwhile IFS= read -r line; do\n i=$((i+1))\n echo \"Working on line ($i/$nl)\"\ndone < \"$file\"\n" }, { "answer_id": 74633711, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 0, "selected": false, "text": "\\n echo \\r for ((i=0; i<10; i++)); do \n printf \"Counter $i\\r\"\n sleep 1\ndone\necho\n echo \\n cut printf j=1\nk=$(cat ~/test.rtf | wc -l)\n\nwhile IFS= read -r line; do\n printf \"Working on line (%s): %s\\r\" \"$j/$k\" $(cut -c1-10 <<< \"${line}\")\n sleep 1\n ((j++))\ndone < ~/test.rft\n j=1\nk=$(cat ~/test.rtf | wc -l)\n\nwhile IFS= read -r line; do\n printf \"Working on line (%5.5s): %-20s\\r\" \"$j/$k\" \"$(cut -c1-20 <<< \"${line}\")\"; \n sleep 1\n ((j++))\ndone < ~/test.rft\n" }, { "answer_id": 74633762, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 2, "selected": true, "text": "n echo n=2 clear tput $ cat test.rtf\nthis is line1\nthen line2\nand line3\nand last but not least line4\nreal last line5\n clear j=1\nk=$(wc -l < test.rtf)\n\nwhile read -r line\ndo\n clear\n echo \"Working on line ($j/$k)\"\n echo \"${line}\"\n ((j++))\ndone < test.rtf\n tput j=1\nk=$(wc -l < test.rtf)\n\nEraseToEOL=$(tput el) # grab terminal specific code for clearing from cursor to EOL\n\nclear # optional: start with a new screen otherwise use current position in console/window for next command ...\ntput sc # grab current cursor position\n\nwhile read -r line\ndo\n tput rc # go (back) to cursor position stored via 'tput sc'\n echo \"Working on line ($j/$k)\"\n echo \"${line}${EraseToEOL}\" # ${EraseToEOL} forces clearing rest of line, effectively erasing a previous line that may have been longer then the current line of output\n ((j++))\ndone < test.rtf\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9379443/" ]
74,632,802
<p>LibreOffice API object is returning a URI path that contains relative path in the middle of the string, like:</p> <p><code>file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav</code></p> <p>How to convert this to the absolute like:</p> <p><code>file:///C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav</code></p> <p>How would I convert this?</p>
[ { "answer_id": 74632822, "author": "9769953", "author_id": 9769953, "author_profile": "https://Stackoverflow.com/users/9769953", "pm_score": 2, "selected": false, "text": "os.path.normpath import os\n\nos.path.normpath(\"file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav\")\n 'file:/C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav'\n \"file:///\" normpath \"file:///\"" }, { "answer_id": 74634342, "author": "Amour Spirit", "author_id": 1171746, "author_profile": "https://Stackoverflow.com/users/1171746", "pm_score": 1, "selected": true, "text": "def uri_absolute(uri: str) -> str:\n uri_re = r\"^(file:(?:/*))\"\n # converts\n # file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav\n # to\n # file:///C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav\n result = os.path.normpath(uri)\n # window will use back slash so convert to forward slash\n result = result.replace(\"\\\\\", \"/\")\n # result may now start with file:/ and not file:///\n\n # add proper file:/// again\n result = re.sub(uri_re, \"file:///\", result, 1)\n return result\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1171746/" ]
74,632,805
<ul> <li>Laravel Version: 9.42.0</li> <li>PHP Version: 8.1.13</li> <li>Database Driver &amp; Version:</li> </ul> <h3>Description:</h3> <p>Before laravel 9 update, form rules were working as I wanted. It started behaving differently after the update.</p> <p>While the same code and the same request occur without an error in laravel 8, error code 422 is returned in laravel 9.</p> <h3>Steps To Reproduce:</h3> <pre><code>Route::post('test', function (\Illuminate\Http\Request $request) { $request-&gt;validate([ 'type' =&gt; [ 'bail', 'exclude_if:type,', 'in:individual,corporate', ], 'name' =&gt; [ 'bail', 'exclude_if:type,', 'required_with:type', 'min:3', 'max:49', ], 'id' =&gt; [ 'bail', 'exclude_if:type,', 'required_with:type', 'digits:10', ], 'tax_office' =&gt; [ 'bail', 'exclude_unless:type,corporate', 'required_if:type,corporate', 'min:2', 'max:99', ], ], $request-&gt;all()); }); </code></pre> <h1>Request:</h1> <pre><code>curl --location --request POST 'https://site.dev/api/test' \ --header 'Accept: application/json' \ --header 'X-Requested-With: XMLHttpRequest' \ --header 'Content-Type: application/json;charset=UTF-8' \ --form 'type=&quot;&quot;' \ --form 'name=&quot;&quot;' \ --form 'id=&quot;&quot;' \ --form 'tax_office=&quot;&quot;' </code></pre> <p>Laravel 8.21.0 response status code: 200</p> <p>Laravel 9.42.0 response status code: 422</p> <pre><code></code></pre>
[ { "answer_id": 74635611, "author": "Tyler Wall", "author_id": 551878, "author_profile": "https://Stackoverflow.com/users/551878", "pm_score": 0, "selected": false, "text": "HTTP 422 HTTP 200 return response() HTTP 200 'exclude_if + required_with' required required_with" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470529/" ]
74,632,830
<p>Write a function that accepts a weekday as a string (e.g. ‘Sunday’) and returns the number of days to the next specified weekday. The input should be case-insensitive. If the specified weekday is today, return <code>Hey, today is ${ specifiedWeekday } =)</code>, otherwise return <code>It's ${ number } day(s) left till ${ specifiedWeekday }</code>. Please note, although input is case-insensitive, weekday name in the output string should be always in proper case. howFarIs(‘friday’); // &quot;It's 1 day(s) left till Friday.&quot; (on October 22nd) howFarIs('Thursday'); // &quot;Hey, today is Thursday =)&quot; (on October 22nd)</p> <p>That<code>s what I</code>we done, pls help me with the next steps or with the correct solution.</p> <pre><code>function howFarIs(day) { let test = new RegExp(`${day}`, 'gi') for (let day of days) { if (day.match(test)) { var dayIndex = days.indexOf(day); } } let date = new Date(); let todayIndex = date.getDay() } </code></pre>
[ { "answer_id": 74635611, "author": "Tyler Wall", "author_id": 551878, "author_profile": "https://Stackoverflow.com/users/551878", "pm_score": 0, "selected": false, "text": "HTTP 422 HTTP 200 return response() HTTP 200 'exclude_if + required_with' required required_with" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648825/" ]
74,632,882
<p>I have the following code</p> <pre><code>query = query.Where(x =&gt; words.Any(x.Message.Contains)); </code></pre> <p><code>words</code> is a <code>string[]</code> and <code>x.Message</code> is a <code>string</code></p> <p>I would like to filter out my query based on all the words in my array but I would like this not to be case sensitive comparison so if i type 'bob' or 'BOb' it should not care and still compare those words against the message if Message is 'BOB is awesome' or 'bob is awesome'</p>
[ { "answer_id": 74632967, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".ToLower() query = query.Where(x => words.Any(s => x.Message.ToLower().Contains(s.ToLower())));\n" }, { "answer_id": 74633028, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 3, "selected": true, "text": "Contains StringComparison query = query.Where(x => words.Any(s => x.Message\n .Contains(s, StringComparison.InvariantCultureIgnoreCase)));\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797038/" ]
74,632,926
<p>I have GitHub repository with multiple branches, and I want to commit and push changes to a specific branch, how can I switch from &quot;master*&quot; branch to another branch?</p> <p>I tried to switch by clicking the branch name in the left bottom side of the screen and it didn't switch.</p>
[ { "answer_id": 74632967, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".ToLower() query = query.Where(x => words.Any(s => x.Message.ToLower().Contains(s.ToLower())));\n" }, { "answer_id": 74633028, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 3, "selected": true, "text": "Contains StringComparison query = query.Where(x => words.Any(s => x.Message\n .Contains(s, StringComparison.InvariantCultureIgnoreCase)));\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19402870/" ]
74,632,992
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">keyword</th> <th style="text-align: center;">value</th> <th style="text-align: right;">keyword</th> <th style="text-align: right;">value</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Apple</td> <td style="text-align: center;">6%</td> <td style="text-align: right;">Apples</td> <td style="text-align: right;">2.21%</td> </tr> <tr> <td style="text-align: left;">Apples</td> <td style="text-align: center;">5%</td> <td style="text-align: right;">Mango</td> <td style="text-align: right;">8.40%</td> </tr> <tr> <td style="text-align: left;">Mango</td> <td style="text-align: center;">2.10%</td> <td style="text-align: right;">Orange</td> <td style="text-align: right;">9.50%</td> </tr> <tr> <td style="text-align: left;">Orange</td> <td style="text-align: center;">3.40%</td> <td style="text-align: right;">Apple</td> <td style="text-align: right;">3.10%</td> </tr> </tbody> </table> </div> <p>I have an example sheet here. I need to first look for the row that contain the exact keyword values. Subtract Value 1 and Value 2 (Value 1 - Value 2).</p> <p>For example:</p> <p>Look for Apple (row 2 for first pair, row 5 for second pair) Subtract the values: 6% - 3.10% = 2.9%</p> <p>Look for Apples (row 3 for first pair, row 2 for second pair) Subtract the values: 5% - 2.21% = 2.79%</p> <p>Look for Mango (row 4 for first pair, row 3 for second pair) Subtract the values: 2.10% - 8.40% = -6.3%</p> <p>Look for Orange (row 5 for first pair, row 4 for second pair) Subtract the values: 3.40% - 9.50% = -6.1%</p> <p>I tried using Vlookup and sumif but I only get errors. Here's a sample sheet <a href="https://docs.google.com/spreadsheets/d/1obKG_hp90PyEQ8lJ2Oywi8ctuK0CdAA0Sc5mdNLOyC0/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1obKG_hp90PyEQ8lJ2Oywi8ctuK0CdAA0Sc5mdNLOyC0/edit?usp=sharing</a></p>
[ { "answer_id": 74632967, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".ToLower() query = query.Where(x => words.Any(s => x.Message.ToLower().Contains(s.ToLower())));\n" }, { "answer_id": 74633028, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 3, "selected": true, "text": "Contains StringComparison query = query.Where(x => words.Any(s => x.Message\n .Contains(s, StringComparison.InvariantCultureIgnoreCase)));\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74632992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648840/" ]
74,633,002
<p>We have a Typescript based NodeJs project that makes use of Mongoose. We are trying to find an appropriate way to define an enum field on a Mongoose schema, based on a Typescript enum. Taking an example enum:</p> <pre><code>enum StatusType { Approved = 1, Decline = 0, } </code></pre> <pre><code>const userSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User' }, statusType: { type: Number, default: StatusType.Approved, enum: Object.values(StatusType) } }); </code></pre> <p>But we keep getting a validation error but anytime we change the type of the <strong>statusType</strong> to</p> <pre><code>type: String </code></pre> <p>It works but it saves the status as a string like <strong>&quot;0&quot;</strong> instead of <strong>0</strong></p>
[ { "answer_id": 74632967, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".ToLower() query = query.Where(x => words.Any(s => x.Message.ToLower().Contains(s.ToLower())));\n" }, { "answer_id": 74633028, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 3, "selected": true, "text": "Contains StringComparison query = query.Where(x => words.Any(s => x.Message\n .Contains(s, StringComparison.InvariantCultureIgnoreCase)));\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12047433/" ]
74,633,024
<p>I have an array as</p> <pre><code>[&quot;first_name&quot;] </code></pre> <p>and I want to convert it to</p> <pre><code>[&quot;user.first_name&quot;] </code></pre> <p>I cannot figure out how I can do this in rails.</p>
[ { "answer_id": 74633434, "author": "Jesse Antunes", "author_id": 17750651, "author_profile": "https://Stackoverflow.com/users/17750651", "pm_score": 3, "selected": true, "text": "my_array = [\"test\", \"test2\", \"first_name\"]\nnew_array = my_array.collect{|value| \"user.#{value}\" }\n [\"user.test\", \"user.test2\", \"user.first_name\"] my_array = [\"test\", \"test2\", \"first_name\"]\nmy_array.collect!{|value| \"user.#{value}\" }\n my_array = [\"test\", \"test2\", \"first_name\"]\nmy_array[1] = \"user.#{my_array[1]}}\n [\"test\", \"user.test2\", \"first_name\"]" }, { "answer_id": 74638874, "author": "Sumak", "author_id": 11509906, "author_profile": "https://Stackoverflow.com/users/11509906", "pm_score": 0, "selected": false, "text": ".map %w[first_name last_name email].map do |attr|\n \"user.#{attr}\"\nend\n# => [user.first_name, user.last_name, user.email] \n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12763413/" ]
74,633,032
<p>I am trying to update .</p> <p><strong>I am getting the error</strong></p> <p>The POST method is not supported for this route. Supported methods: GET, HEAD.</p> <p>Following are the code</p> <p><strong>In Route</strong></p> <p><code>Route::post('editcountries','App\Http\Controllers\backend\admineditcountryController@editcountries');</code></p> <p><strong>In Controller</strong></p> <pre><code> function editcountries(Request $request) { $country_en = $request-&gt;input('country_en'); $country_ar = $request-&gt;input('country_ar'); $id = $request-&gt;input('idd'); $cstatus = 1; if (isset($request-&gt;status)) $cstatus = 1; else $cstatus = 0; $isUpdateSuccess = country::where('id',$id)-&gt;update(['country_en'=&gt; $country_en, 'country_ar'=&gt; $country_ar, 'status' =&gt; $cstatus ]); $this-&gt;clearToastr(); session()-&gt;put('updated','Information updated Successfully.'); return view('backend.adminaddcountry'); } </code></pre> <p><strong>In blade</strong></p> <pre><code> &lt;form action=&quot;editcountries&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt; @csrf {{-- @method('PUT') --}} {{-- &lt;input type=&quot;hidden&quot; name=&quot;_method&quot; value=&quot;PUT&quot;&gt;&quot; --}} &lt;div class=&quot;input-style-1&quot;&gt; &lt;label&gt;Country Name in English &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;country_en&quot; placeholder=&quot;Country Name in English&quot; value='{{ $clist-&gt;country_en }}' required/&gt; &lt;/div&gt; &lt;div class=&quot;input-style-1&quot;&gt; &lt;label&gt;Country Name in Arabic&lt;/label&gt; &lt;input type=&quot;text&quot; dir=&quot;rtl&quot; name=&quot;country_ar&quot; placeholder=&quot;اسم الدولة بالعربية&quot; value='{{ $clist-&gt;country_ar }}' /&gt; &lt;/div&gt; &lt;!-- end input --&gt; &lt;div class=&quot;form-check form-switch toggle-switch&quot;&gt; &lt;input class=&quot;form-check-input&quot; name=&quot;status&quot; type=&quot;checkbox&quot; id=&quot;toggleSwitch2&quot; @if($clist-&gt;status==1) checked=&quot;&quot; @else @endif&gt; &lt;label class=&quot;form-check-label&quot; for=&quot;toggleSwitch2&quot;&gt;Enable or disable the country.&lt;/label&gt; &lt;/div&gt; &lt;input type=&quot;hidden&quot; id=&quot;idd&quot; name=&quot;idd&quot; value=&quot;{{ $clist-&gt;id }}&quot; /&gt; &lt;br&gt; &lt;button class=&quot;main-btn primary-btn btn-hover text-center&quot;&gt;Update&lt;/button&gt; &lt;/form&gt; </code></pre> <p>I tried using</p> <pre><code>@method('PUT') </code></pre> <p>but then getting error</p> <p><code>The PUT method is not supported for this route. Supported methods: GET, HEAD.</code></p> <p>Please help</p> <p>I tried putting</p> <p>I tried using</p> <pre><code>@method('PUT') </code></pre> <p>but then getting error</p> <p><code>The PUT method is not supported for this route. Supported methods: GET, HEAD.</code></p> <p>Please help</p>
[ { "answer_id": 74633434, "author": "Jesse Antunes", "author_id": 17750651, "author_profile": "https://Stackoverflow.com/users/17750651", "pm_score": 3, "selected": true, "text": "my_array = [\"test\", \"test2\", \"first_name\"]\nnew_array = my_array.collect{|value| \"user.#{value}\" }\n [\"user.test\", \"user.test2\", \"user.first_name\"] my_array = [\"test\", \"test2\", \"first_name\"]\nmy_array.collect!{|value| \"user.#{value}\" }\n my_array = [\"test\", \"test2\", \"first_name\"]\nmy_array[1] = \"user.#{my_array[1]}}\n [\"test\", \"user.test2\", \"first_name\"]" }, { "answer_id": 74638874, "author": "Sumak", "author_id": 11509906, "author_profile": "https://Stackoverflow.com/users/11509906", "pm_score": 0, "selected": false, "text": ".map %w[first_name last_name email].map do |attr|\n \"user.#{attr}\"\nend\n# => [user.first_name, user.last_name, user.email] \n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648937/" ]
74,633,037
<p>Sample:</p> <pre><code>id value 1 a 1 b 1 c 1 d 1 a 1 b 1 d 1 a </code></pre> <p>Expected outcome:</p> <pre><code>id value outcome 1 a 1 1 b 1 1 c 1 1 d 1 1 a 2 1 b 2 1 d 2 1 a 3 </code></pre> <p>So the basic idea is that I need to number the rows I have based on the value column - whenever it reaches &quot;d&quot;, the count starts over. Not sure which kind of window function I'd use do to that, so any help is appreciated! Thanks in advance!</p>
[ { "answer_id": 74633115, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 3, "selected": true, "text": "row_number value id value -- sample data\nwith dataset(id, value) as(\n values (1, 'a'),\n (1, 'b'),\n (1, 'c'),\n (1, 'd'),\n (1, 'a'),\n (1, 'b'),\n (1, 'd'),\n (1, 'a')\n)\n\n-- query\nselect *,\n row_number() over (partition by id, value) -- or (partition by value)\nfrom dataset;\n over over (partition by id, value order by some_column_like_timestamp)" }, { "answer_id": 74633116, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 1, "selected": false, "text": "row_number select\n *,\n row_number() over ( partition by (val) ) as rn\nfrom stuff\norder by rn, val;\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3642271/" ]
74,633,040
<p>Hi I am trying to use Data Service Call. When I use it in any proxy service in wso2 I get an error Unknown mediator referenced by configuration element: dataServiceCall</p> <blockquote> <p><a href="https://apim.docs.wso2.com/en/latest/reference/mediators/dss-mediator/" rel="nofollow noreferrer">https://apim.docs.wso2.com/en/latest/reference/mediators/dss-mediator/</a></p> </blockquote> <p>I am following the link as mentioned above. Can someone guide me what am I doing wrong ?</p> <p>Below is the code I have written</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;proxy name=&quot;TestData&quot; startOnLoad=&quot;true&quot; transports=&quot;http https local&quot; xmlns=&quot;http://ws.apache.org/ns/synapse&quot;&gt; &lt;target&gt; &lt;inSequence&gt; &lt;dataServiceCall serviceName=&quot;Hello&quot;&gt; &lt;/dataServiceCall&gt; &lt;respond/&gt; &lt;/inSequence&gt; &lt;outSequence/&gt; &lt;faultSequence/&gt; &lt;/target&gt; &lt;/proxy&gt; </code></pre> <p><a href="https://i.stack.imgur.com/JfJrY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JfJrY.png" alt="Error and service." /></a></p>
[ { "answer_id": 74634772, "author": "ycr", "author_id": 2627018, "author_profile": "https://Stackoverflow.com/users/2627018", "pm_score": 1, "selected": true, "text": "Integration Studio DataServiceCall Mediator" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19503782/" ]
74,633,109
<p>I'm trying to dynamically size a container to the width of its children when they're broken down into columns and rows. This can easily be achieved by writing a bunch of media queries and hard coding the width of the container, but I'm looking for a way to do it dynamically with CSS.</p> <p>In this example id like <code>.container</code> to only be a multiple of the width of a fixed size <code>.item</code> (<code>200px</code>, <code>410px</code>, <code>620px</code>, <code>830px</code>, etc) and not include the empty space to the right.</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>.container { background-color: #555; display: flex; flex-wrap: wrap; gap: 10px; max-width: 1000px; padding: 10px; } .item { aspect-ratio: 1; background-color: #ddd; width: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74633152, "author": "Seyfullah Akgun", "author_id": 18068342, "author_profile": "https://Stackoverflow.com/users/18068342", "pm_score": 0, "selected": false, "text": ".item {\n width: 100%;\n}" }, { "answer_id": 74634707, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": ".wrapper {\n display: grid;\n grid-template-columns: repeat(auto-fill,200px); /* same as width of items */\n gap: 10px;\n padding: 10px; /* move the padding here */\n}\n\n.container {\n grid-column: 1/-1; /* take all the columns */\n background-color: #555;\n outline: 10px solid #555; /* use outline to cover the padding */\n display: flex;\n flex-wrap: wrap;\n gap: inherit;\n}\n\n.item {\n aspect-ratio: 1;\n background-color: #ddd;\n width: 200px;\n} <div class=\"wrapper\">\n <div class=\"container\">\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n <div class=\"item\"></div>\n </div>\n</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648878/" ]
74,633,150
<p>I have this dataset <a href="https://dbfiddle.uk/wtbPEvoE" rel="nofollow noreferrer">https://dbfiddle.uk/wtbPEvoE</a></p> <p>like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE #RegionSales ( Region VARCHAR(100), Distributor VARCHAR(100), Sales INTEGER, PRIMARY KEY (Region, Distributor) ); INSERT INTO #RegionSales VALUES ('North','ACE',10), ('South','ACE',67), ('East','ACE',54), ('North','Direct Parts',8), ('South','Direct Parts',7), ('West','Direct Parts',12), ('North','ACME',65), ('South','ACME',9), ('East','ACME',1), ('West','ACME',7); WITH cte as ( SELECT distinct region FROM #RegionSales ) SELECT * FROM #RegionSales as rs RIGHT JOIN cte ON rs.Region = cte.Region WHERE Distributor = 'ACE' </code></pre> <p>Can someone understand why I do not get the Region West from the CTE? The right join should give me the following data:</p> <p><a href="https://i.stack.imgur.com/humTW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/humTW.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74633232, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 1, "selected": false, "text": "WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM cte\nLEFT JOIN #RegionSales rs ON rs.Region = cte.Region AND rs.Distributor='ACE';\n RIGHT JOIN WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM #RegionSales rs\nRIGHT JOIN cte ON rs.Region = cte.Region ;\n West/ACE" }, { "answer_id": 74633395, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " WITH cte as (\n SELECT distinct region \n FROM RegionSales )\n\nSELECT *\nFROM RegionSales as rs\nRIGHT JOIN cte ON rs.Region = cte.Region AND rs.Distributor = 'ACE'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20169539/" ]
74,633,161
<p>I am trying to scrape information from a website with the following HTML format:</p> <pre><code>&lt;tr class=&quot;odd&quot;&gt; &lt;td class=&quot;&quot;&gt; &lt;table class=&quot;inline-table&quot;&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td rowspan=&quot;2&quot;&gt; &lt;img src=&quot;https://img.a.transfermarkt.technology/portrait/medium/881116-1664480529.jpg?lm=1&quot; data-src=&quot;https://img.a.transfermarkt.technology/portrait/medium/881116-1664480529.jpg?lm=1&quot; title=&quot;Darío Osorio&quot; alt=&quot;Darío Osorio&quot; class=&quot;bilderrahmen-fixed lazy entered loaded&quot; data-ll-status=&quot;loaded&quot;&gt; &lt;/td&gt; &lt;td class=&quot;hauptlink&quot;&gt; &lt;a title=&quot;Darío Osorio&quot; href=&quot;/dario-osorio/profil/spieler/881116&quot;&gt;Darío Osorio&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Right Winger&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;/td&gt;&lt;td class=&quot;zentriert&quot;&gt;18&lt;/td&gt;&lt;td class=&quot;zentriert&quot;&gt;&lt;img src=&quot;https://tmssl.akamaized.net/images/flagge/verysmall/33.png?lm=1520611569&quot; title=&quot;Chile&quot; alt=&quot;Chile&quot; class=&quot;flaggenrahmen&quot;&gt;&lt;/td&gt;&lt;td class=&quot;&quot;&gt;&lt;table class=&quot;inline-table&quot;&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td rowspan=&quot;2&quot;&gt; &lt;a title=&quot;Club Universidad de Chile&quot; href=&quot;/club-universidad-de-chile/startseite/verein/1037&quot;&gt;&lt;img src=&quot;https://tmssl.akamaized.net/images/wappen/tiny/1037.png?lm=1420190110&quot; title=&quot;Club Universidad de Chile&quot; alt=&quot;Club Universidad de Chile&quot; class=&quot;tiny_wappen&quot;&gt;&lt;/a&gt; &lt;/td&gt; &lt;td class=&quot;hauptlink&quot;&gt; &lt;a title=&quot;Club Universidad de Chile&quot; href=&quot;/club-universidad-de-chile/startseite/verein/1037&quot;&gt;U. de Chile&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;img src=&quot;https://tmssl.akamaized.net/images/flagge/tiny/33.png?lm=1520611569&quot; title=&quot;Chile&quot; alt=&quot;Chile&quot; class=&quot;flaggenrahmen&quot;&gt; &lt;a title=&quot;Primera División&quot; href=&quot;/primera-division-de-chile/transfers/wettbewerb/CLPD&quot;&gt;Primera División&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;/td&gt;&lt;td class=&quot;&quot;&gt;&lt;table class=&quot;inline-table&quot;&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td rowspan=&quot;2&quot;&gt; &lt;a title=&quot;Newcastle United&quot; href=&quot;/newcastle-united/startseite/verein/762&quot;&gt;&lt;img src=&quot;https://tmssl.akamaized.net/images/wappen/tiny/762.png?lm=1472921161&quot; title=&quot;Newcastle United&quot; alt=&quot;Newcastle United&quot; class=&quot;tiny_wappen&quot;&gt;&lt;/a&gt; &lt;/td&gt; &lt;td class=&quot;hauptlink&quot;&gt; &lt;a title=&quot;Newcastle United&quot; href=&quot;/newcastle-united/startseite/verein/762&quot;&gt;Newcastle&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;img src=&quot;https://tmssl.akamaized.net/images/flagge/verysmall/189.png?lm=1520611569&quot; title=&quot;England&quot; alt=&quot;England&quot; class=&quot;flaggenrahmen&quot;&gt; &lt;a title=&quot;Premier League&quot; href=&quot;/premier-league/transfers/wettbewerb/GB1&quot;&gt;Premier League&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;/td&gt;&lt;td class=&quot;rechts&quot;&gt;-&lt;/td&gt;&lt;td class=&quot;rechts&quot;&gt;€3.00m&lt;/td&gt;&lt;td class=&quot;rechts hauptlink&quot;&gt;? &lt;/td&gt;&lt;td class=&quot;zentriert hauptlink&quot;&gt;&lt;a title=&quot;Darío Osorio to Newcastle United?&quot; id=&quot;27730/Newcastle United sent scouts to Chile to follow Dario Osorio. the 18-year-old is being monitored by Barcelona, ​​Wolverhampton and Newcastle United./http://www.90min.com//16127/180/Darío Osorio to Newcastle United?&quot; class=&quot;icons_sprite icon-pinnwand-sprechblase sprechblase-wechselwahrscheinlichkeit&quot; href=&quot;https://www.transfermarkt.co.uk/dario-osorio-to-newcastle-united-/thread/forum/180/thread_id/16127/post_id/27730#27730&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>I want to scrape &quot;Darió Osorio&quot;, &quot;U. de Chile&quot; and &quot;Newcastle&quot; all from the text of different elements with [class=&quot;hauptlink&quot;] from the HTML.</p> <p>I have tried a couple of different things, my most recent attempt looks like this:</p> <pre><code>$('.odd', html).each((index, el) =&gt; { const source = $(el) const information= source.find('td.main-link').first().text().trim() const differentInformation= source.find('a:nth-child(1)').text() }) </code></pre> <p>But I am only successful in scraping &quot;Darió Osorio&quot; with the first()-method. The variable for &quot;differentInformation&quot; currently looks like this with my code: &quot;Darió OsorioU. de ChileNewcastle&quot;. The result I want to get in the end is a JSON-Object like this:</p> <pre><code>[ { &quot;firstInfo&quot; : &quot;Darió Osorio&quot;, &quot;secondInfo&quot;: &quot;U. de Chile&quot;, &quot;thirdInfo&quot;: &quot;Newcastle&quot; }, { &quot;firstInfo&quot; : &quot;Information&quot;, &quot;secondInfo&quot;: &quot;Different Information&quot;, &quot;thirdInfo&quot;: &quot;More Different Information&quot; } ] </code></pre>
[ { "answer_id": 74633232, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 1, "selected": false, "text": "WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM cte\nLEFT JOIN #RegionSales rs ON rs.Region = cte.Region AND rs.Distributor='ACE';\n RIGHT JOIN WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM #RegionSales rs\nRIGHT JOIN cte ON rs.Region = cte.Region ;\n West/ACE" }, { "answer_id": 74633395, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " WITH cte as (\n SELECT distinct region \n FROM RegionSales )\n\nSELECT *\nFROM RegionSales as rs\nRIGHT JOIN cte ON rs.Region = cte.Region AND rs.Distributor = 'ACE'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648951/" ]
74,633,165
<p>I'm using <a href="https://github.com/kylefox/jquery-modal#installation" rel="nofollow noreferrer">this</a> jQuery Modal Plugin to show a popup on my site.</p> <p>When the page loads, I want to delay the popup by 5 seconds, but is not working together with the &quot;setTimeout&quot; method.</p> <p>Here is my HTML:</p> <pre><code>&lt;div id=&quot;ex1&quot; class=&quot;modal&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>setTimeout(() =&gt; { $('#ex1').modal({ fadeDuration: 500, showClose: false ); }, 5000) </code></pre> <p>Does anyone knows how to fix this?</p> <p>So whenever I use the &quot;setTimeout&quot; method, I get this error: &quot;Uncaught TypeError: $(...).modal is not a function&quot;, but it works fine without it.</p> <p>Edit: I also noticed that is not working when I try to call it inside of window.onload = function() {}</p> <p>How can I make this work?</p>
[ { "answer_id": 74633232, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 1, "selected": false, "text": "WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM cte\nLEFT JOIN #RegionSales rs ON rs.Region = cte.Region AND rs.Distributor='ACE';\n RIGHT JOIN WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM #RegionSales rs\nRIGHT JOIN cte ON rs.Region = cte.Region ;\n West/ACE" }, { "answer_id": 74633395, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " WITH cte as (\n SELECT distinct region \n FROM RegionSales )\n\nSELECT *\nFROM RegionSales as rs\nRIGHT JOIN cte ON rs.Region = cte.Region AND rs.Distributor = 'ACE'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13264461/" ]
74,633,181
<p>Suppose I have 2 tables in my database and 2 Windows Forms (C#) for each table <code>Section</code> and <code>Pages</code>. Now each <code>Section</code> can have 10 <code>Pages</code>.</p> <p><strong>Note</strong> that I am creating a Windows Forms app and first form looks like this</p> <p><a href="https://i.stack.imgur.com/fvEIf.jpg" rel="nofollow noreferrer">FORM 1 (For Section Table)</a></p> <p>And my second form for table <code>pages</code> looks like this:</p> <p><a href="https://i.stack.imgur.com/OpVa6.jpg" rel="nofollow noreferrer">FORM 2 for Pages Table</a>.</p> <p>By clicking on each <code>Section</code>, user will be directed to the 2nd form where user will/can have 10 pages.</p> <p>I have this:</p> <pre><code>create table Section ( Sectionid int primary key, SectionName varchar, Pageid int ) create table Page ( Pageid int primary key, Pagetitle varchar, Noteid int ) </code></pre> <pre><code>foreign key(pageid) references Page(pageid) </code></pre> <p>I am confused how to insert data to the database once you have created a page.</p> <p><strong>AGAIN</strong>: 1 SECTION CAN HAVE AT LEAST 10 PAGES AND 1 PAGE CAN HAVE 1 NOTE.</p> <p>If I have not made it easier to understand please just use Microsoft's One Note mobile app, I am basically copying it - thanks.</p>
[ { "answer_id": 74633232, "author": "Luuk", "author_id": 724039, "author_profile": "https://Stackoverflow.com/users/724039", "pm_score": 1, "selected": false, "text": "WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM cte\nLEFT JOIN #RegionSales rs ON rs.Region = cte.Region AND rs.Distributor='ACE';\n RIGHT JOIN WITH cte as (\n SELECT distinct region \n FROM #RegionSales )\nSELECT * \nFROM #RegionSales rs\nRIGHT JOIN cte ON rs.Region = cte.Region ;\n West/ACE" }, { "answer_id": 74633395, "author": "mikey22022", "author_id": 20169539, "author_profile": "https://Stackoverflow.com/users/20169539", "pm_score": 0, "selected": false, "text": " WITH cte as (\n SELECT distinct region \n FROM RegionSales )\n\nSELECT *\nFROM RegionSales as rs\nRIGHT JOIN cte ON rs.Region = cte.Region AND rs.Distributor = 'ACE'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19601212/" ]
74,633,246
<p>I am trying to make sort of sliding carousel that shows a different slide based on what the user has its mouse over. I am working with z-index to show the correct slide on top. But important is that the previous slide is underneath. So the idea is:</p> <ol> <li>All slides <code>z-index: 1</code> by default</li> <li>If slide is shown, set <code>z-index: 3</code></li> <li>When another slide is shown, set previous slide to <code>z-index: 2</code> and the new one to <code>3</code></li> </ol> <p>This was my work so far</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>slides = document.querySelectorAll('.slide'); navItems = document.querySelectorAll('.slider-navigation li'); navItems.forEach(navItem =&gt; { navItem.addEventListener('mouseover', () =&gt; onNavigationHover(navItem)); }); function onNavigationHover(navItem) { let slideKey = navItem.dataset.slide; slides.forEach((slide, index) =&gt; { if (slide.dataset.slide === slideKey) { slide.style.setProperty('--z-index', 3) // can i set the previous slide zIndex here to 2? slide.classList.add('slideIn') } else { slide.style.setProperty('--z-index', 1) slide.classList.remove('slideIn') } }); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>img { z-index: var(--z-index); position: absolute; top: 0; left: 0; width: 200px; height: 150px; object-fit: cover; } div { height: 200px; width: 200px; position: relative; } img.slideIn { animation: slideIn 2s ease forwards; } @keyframes slideIn { from { translate: 200px; } to { translate: 0px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul class='slider-navigation'&gt; &lt;li data-slide='1'&gt;Slide 1&lt;/li&gt; &lt;li data-slide='2'&gt;Slide 2&lt;/li&gt; &lt;li data-slide='3'&gt;Slide 3&lt;/li&gt; &lt;/ul&gt; &lt;div&gt; &lt;img class='slide' data-slide='1' src='https://images.unsplash.com/photo-1669818319938-bb7029dc3fa3?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60'&gt; &lt;img class='slide' data-slide='2' src='https://images.unsplash.com/photo-1669623313981-6af02eedb15c?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw1fHx8ZW58MHx8fHw%3D&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60'&gt; &lt;img class='slide' data-slide='3' src='https://images.unsplash.com/photo-1446776811953-b23d57bd21aa?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fHNwYWNlfGVufDB8fDB8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60' /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This is working great, except that the same image will always show underneath.</p> <p>Is it possible to save the previous index and give it a different z-index? Or should I approach this in a different way? Thank you!</p>
[ { "answer_id": 74633405, "author": "Fanvaron", "author_id": 2814958, "author_profile": "https://Stackoverflow.com/users/2814958", "pm_score": 1, "selected": false, "text": "function onNavigationHover(navItem) {\n let slideKey = navItem.dataset.slide;\n\n slides.forEach((slide, index) => {\n if (slide.dataset.slide === slideKey) {\n slide.style.setProperty('--z-index', 3)\n // Set the index of the old element\n document.getElementById('active')?.style.setPropery('--z-index', 2);\n // Remove the id of the old element\n document.getElementById('active')?.removeAttribute('id');\n // Set the id on the current element\n slide.id = 'active';\n } else {\n slide.style.setProperty('--z-index', 1)\n }\n });\n}\n" }, { "answer_id": 74633583, "author": "EssXTee", "author_id": 2339619, "author_profile": "https://Stackoverflow.com/users/2339619", "pm_score": 3, "selected": true, "text": ".filter() .filter() z-index onNavigationHover() z-index z-index z-index slides = document.querySelectorAll('.slide');\nnavItems = document.querySelectorAll('.slider-navigation li');\n\nnavItems.forEach(navItem => {\n navItem.addEventListener('mouseover', () => onNavigationHover(navItem));\n});\n\nfunction onNavigationHover(navItem) {\n let prevSlide = Array.from(slides).filter(slide => getComputedStyle(slide).zIndex == 3)[0]\n \n slides.forEach(slide => {\n slide.style.setProperty('--z-index', 1)\n slide.classList.toggle('slideIn', slide.dataset.slide == navItem.dataset.slide)\n })\n prevSlide?.style.setProperty('--z-index', 2)\n Array.from(slides).filter(slide => slide.dataset.slide == navItem.dataset.slide)[0]?.style.setProperty('--z-index', 3)\n} img {\n z-index: var(--z-index);\n position: absolute;\n top: 0;\n left: 0;\n width: 200px;\n height: 150px;\n object-fit: cover;\n}\n\ndiv {\n height: 200px;\n width: 200px;\n position: relative;\n}\n\nimg.slideIn {\n animation: slideIn 2s ease forwards;\n}\n\n@keyframes slideIn {\n from {\n translate: 200px;\n }\n to {\n translate: 0px;\n }\n} <div>\n <img class='slide' data-slide='1' width=200 src='https://images.unsplash.com/photo-1669818319938-bb7029dc3fa3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60'>\n\n <img class='slide' data-slide='2' width=200 src='https://images.unsplash.com/photo-1669623313981-6af02eedb15c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw1fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60'>\n \n <img class='slide' data-slide='3' width=200 src='https://images.unsplash.com/photo-1446776811953-b23d57bd21aa?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fHNwYWNlfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60' />\n</div>\n\n<ul class='slider-navigation'>\n <li data-slide='1'>Slide 1</li>\n <li data-slide='2'>Slide 2</li>\n <li data-slide='3'>Slide 3</li>\n</ul> prevSlide onNavigationHover() .filter() z-index const slides = document.querySelectorAll('.slide'),\nnavItems = document.querySelectorAll('.slider-navigation li')\n\nnavItems.forEach(navItem => {\n navItem.addEventListener('mouseover', () => onNavigationHover(navItem))\n});\n\nfunction onNavigationHover(navItem) {\n slides.forEach(slide => {\n let newIndex = (slide.dataset.slide == navItem.dataset.slide) ? 3 : (getComputedStyle(slide).zIndex == 3) ? 2 : 1\n slide.style.setProperty('--z-index', newIndex)\n slide.classList.toggle('slideIn', slide.dataset.slide == navItem.dataset.slide)\n })\n} img {\n z-index: var(--z-index);\n position: absolute;\n top: 0;\n left: 0;\n width: 200px;\n height: 150px;\n object-fit: cover;\n}\n\ndiv {\n height: 200px;\n width: 200px;\n position: relative;\n}\n\nimg.slideIn {\n animation: slideIn 2s ease forwards;\n}\n\n@keyframes slideIn {\n from {\n translate: 200px;\n }\n to {\n translate: 0px;\n }\n} <div>\n <img class='slide' data-slide='1' width=200 src='https://images.unsplash.com/photo-1669818319938-bb7029dc3fa3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60'>\n\n <img class='slide' data-slide='2' width=200 src='https://images.unsplash.com/photo-1669623313981-6af02eedb15c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw1fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60'>\n \n <img class='slide' data-slide='3' width=200 src='https://images.unsplash.com/photo-1446776811953-b23d57bd21aa?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fHNwYWNlfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60' />\n</div>\n\n<ul class='slider-navigation'>\n <li data-slide='1'>Slide 1</li>\n <li data-slide='2'>Slide 2</li>\n <li data-slide='3'>Slide 3</li>\n</ul>" }, { "answer_id": 74633591, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 1, "selected": false, "text": "const slides = document.querySelectorAll('.slide');\nconst navItems = document.querySelectorAll('.slider-navigation li');\nconst previousSlide = null;\n\nnavItems.forEach(navItem => {\n navItem.addEventListener('mouseover', () => onNavigationHover(navItem));\n});\n\nfunction onNavigationHover(navItem) {\n let slideKey = navItem.dataset.slide;\n\n slides.forEach((slide, index) => {\n if (slide.dataset.slide === slideKey) {\n slide.style.setProperty('--z-index', 3);\n if(previousSlide && previousSlide !== slide) {\n previousSlide.style.setProperty('--z-index', 2);\n }\n previousSlide = slide;\n slide.classList.add('slideIn')\n } else if(slide !== previousSlide) {\n slide.style.setProperty('--z-index', 1)\n slide.classList.remove('slideIn')\n }\n });\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10546172/" ]
74,633,248
<p>Given a div such as <code>&lt;div class=&quot;abcd ws-compid rh03 a11y-true&quot;&gt;&lt;/div&gt;</code>, I need to be able to find the last class on each div and pull it's value.</p> <p>I can currently get all the classes with classList, but can't seem to get the last class in the DOMTokenList:</p> <pre><code>[...document.querySelectorAll('.ws-compid')].map(component =&gt; component.classList ? {id: component.innerText, type: component.classList} : null); </code></pre> <p>The class I need will always be the last one in the array, but options like <code>.last()</code> don't seem to work.</p>
[ { "answer_id": 74633292, "author": "Robdll", "author_id": 2324133, "author_profile": "https://Stackoverflow.com/users/2324133", "pm_score": 1, "selected": false, "text": " Array.from(\n document.getElementsByTagName(\"div\")\n ).map( i => ({\n type: i.className.split(' ').pop(),\n id: i.innerText\n }))\n" }, { "answer_id": 74633348, "author": "Matt", "author_id": 350305, "author_profile": "https://Stackoverflow.com/users/350305", "pm_score": -1, "selected": false, "text": "Object.entries() [...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: Object.entries(component.classList).pop()[1]} : null);\n" }, { "answer_id": 74633365, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": false, "text": ".classList document.querySelectorAll(\".ws-compid\").forEach(d=>console.log([...d.classList].at(-1))) <div class=\"abcd ws-compid rh03 a11y-true\">one</div>\n<div class=\"abcd ws-compid rh03 a12y-false\">two</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350305/" ]
74,633,287
<p>I'm fairly new to firebase and I'm trying to get the path to one of my subcollections in order to install a firebase extension.</p> <p>This is how my JSON looks like</p> <p><img src="https://i.stack.imgur.com/gqHkx.png" alt="firebase-image" /></p> <p>The issue is I'm trying to get the subcollection &quot;comments&quot; under each &quot;post&quot; document as required by the extension</p> <p><img src="https://i.stack.imgur.com/mPSOx.png" alt="extension-configuration" /></p> <p>I'm aware I can use collection groups and simply give it &quot;comments&quot; however in my case the path is required by the extension</p> <p>I tried doing <code>post/comments</code> however it would detect that the path is incorrect and would throw out an error</p> <p>I tried <code>post/${postId}/comments</code> however that simply wouldn't work</p> <p>I know the extension does work because something like <code>/post/c9902c40-6e63-11ed-b700-2d9d4e8231b7/comments</code> does work for that one branch</p>
[ { "answer_id": 74633292, "author": "Robdll", "author_id": 2324133, "author_profile": "https://Stackoverflow.com/users/2324133", "pm_score": 1, "selected": false, "text": " Array.from(\n document.getElementsByTagName(\"div\")\n ).map( i => ({\n type: i.className.split(' ').pop(),\n id: i.innerText\n }))\n" }, { "answer_id": 74633348, "author": "Matt", "author_id": 350305, "author_profile": "https://Stackoverflow.com/users/350305", "pm_score": -1, "selected": false, "text": "Object.entries() [...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: Object.entries(component.classList).pop()[1]} : null);\n" }, { "answer_id": 74633365, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": false, "text": ".classList document.querySelectorAll(\".ws-compid\").forEach(d=>console.log([...d.classList].at(-1))) <div class=\"abcd ws-compid rh03 a11y-true\">one</div>\n<div class=\"abcd ws-compid rh03 a12y-false\">two</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13599741/" ]
74,633,288
<p>I am using React + d3js to render data on svg, i have a large array with data like this</p> <pre><code>const arrayItemExample = { id: 1, text: 'Some Text for node', x: 100, y: 300, selected: false, dragging: false } </code></pre> <p>The list of such elements can reach tens of thousands. The main problem is that when I click on a rendered element or drag it, I update the data on that element:</p> <pre><code>const handleDragStart = useCallback((id)=&gt;{ setData(data=&gt;{ return data.map(item=&gt;{ if(item.id === id){ return { ...item, dragging: true } } return item }) }) },[]) const handleSelect = useCallback((id)=&gt;{ setData(data=&gt;{ return data.map(item=&gt;{ if(item.id === id){ return { ...item, selected: true } } return item }) }) },[]) </code></pre> <p>Both of these functions work well on a small amount of data, but if there are 100 or more elements on the page, then clicking or dragging the element slows down the page during the redrawing of elements.</p> <p>Are there any ways to update the data in a specific element with redrawing its only one? I can't use the component's internal state because I need the total data for the selected and draggable elements: for example, I have selected several elements with ctrl , and when I start dragging one of the selected, the other will also have to be dragged</p>
[ { "answer_id": 74633292, "author": "Robdll", "author_id": 2324133, "author_profile": "https://Stackoverflow.com/users/2324133", "pm_score": 1, "selected": false, "text": " Array.from(\n document.getElementsByTagName(\"div\")\n ).map( i => ({\n type: i.className.split(' ').pop(),\n id: i.innerText\n }))\n" }, { "answer_id": 74633348, "author": "Matt", "author_id": 350305, "author_profile": "https://Stackoverflow.com/users/350305", "pm_score": -1, "selected": false, "text": "Object.entries() [...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: Object.entries(component.classList).pop()[1]} : null);\n" }, { "answer_id": 74633365, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": false, "text": ".classList document.querySelectorAll(\".ws-compid\").forEach(d=>console.log([...d.classList].at(-1))) <div class=\"abcd ws-compid rh03 a11y-true\">one</div>\n<div class=\"abcd ws-compid rh03 a12y-false\">two</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9722233/" ]
74,633,313
<p>I've got a basic swing GUI set up, including a dialog window. It looks the way I want it to, and acts the way I want it to... except that when I resize the dialog window vertically, it stretches a text field instead of the <code>JScrollPane</code> like I would like it to do.</p> <p>I've found lots of advice around the web about resizing in general, but I couldn't figure out how to apply what I'd found to this specific issue.</p> <p>Following is an example to replicate the behavior. I'd rather keep the <code>BoxLayout</code> managers, as I've already been through many other issues with other managers, and this setup is finally working... only with this one small remaining issue.</p> <pre><code>import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; public class ExampleDialog extends JDialog { private static final long serialVersionUID = 1L; public static void main(String[] args) { ExampleDialog dialog = new ExampleDialog(null, &quot;Title&quot;, true); dialog.setVisible(true); } public ExampleDialog(JFrame parent, String title, boolean modal) { super(parent, title, modal); // Top panel JTextField field = new JTextField(); field.setText(&quot;Text&quot;); field.setEnabled(false); JButton button1 = new JButton(&quot;Button 1&quot;); JPanel topPanel = new JPanel(); topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS)); topPanel.add(field); topPanel.add(button1); // Middle panel DefaultMutableTreeNode root = new DefaultMutableTreeNode(&quot;root&quot;); for (int i=0; i&lt;30; i++) root.add(new DefaultMutableTreeNode(String.format(&quot;%0100d&quot;, i))); ExamplePanel middlePanel = new ExamplePanel(new DefaultTreeModel(root)); // Bottom panel JButton button2 = new JButton(&quot;Button 2&quot;); JButton button3 = new JButton(&quot;Button 3&quot;); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); bottomPanel.add(button2); bottomPanel.add(button3); // Content panel JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); contentPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); contentPanel.add(topPanel); contentPanel.add(middlePanel); contentPanel.add(bottomPanel); this.setContentPane(contentPanel); this.pack(); } public class ExamplePanel extends JScrollPane { private static final long serialVersionUID = 1L; public ExamplePanel(TreeModel model) { super(); JTree tree = new JTree(model); tree.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.setViewportView(tree); } } } </code></pre> <p>Looks good: <a href="https://i.stack.imgur.com/d8AkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d8AkR.png" alt="Before scaling" /></a></p> <p>Until I scale it (vertically): <a href="https://i.stack.imgur.com/KL4cK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KL4cK.png" alt="After vertical scaling" /></a></p> <p>Horizontal scaling works great. Can you help me figure out what I need to change?</p> <p>Note, all the border stuff in the code is leftover from a coworker, and I haven't played with it much. Nor do I understand what exactly it's trying to accomplish. So I don't know if that's part of the problem, unrelated, or perhaps even accomplishing absolutely nothing.</p> <p>Thanks!</p>
[ { "answer_id": 74633292, "author": "Robdll", "author_id": 2324133, "author_profile": "https://Stackoverflow.com/users/2324133", "pm_score": 1, "selected": false, "text": " Array.from(\n document.getElementsByTagName(\"div\")\n ).map( i => ({\n type: i.className.split(' ').pop(),\n id: i.innerText\n }))\n" }, { "answer_id": 74633348, "author": "Matt", "author_id": 350305, "author_profile": "https://Stackoverflow.com/users/350305", "pm_score": -1, "selected": false, "text": "Object.entries() [...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: Object.entries(component.classList).pop()[1]} : null);\n" }, { "answer_id": 74633365, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": false, "text": ".classList document.querySelectorAll(\".ws-compid\").forEach(d=>console.log([...d.classList].at(-1))) <div class=\"abcd ws-compid rh03 a11y-true\">one</div>\n<div class=\"abcd ws-compid rh03 a12y-false\">two</div>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6888191/" ]
74,633,320
<p>I have tried to implement a flatten function to even flatten strings but got an error for Recursion. Could someone help resolve this puzzle?</p> <pre><code>def flatten(items): for x in items: if isinstance(x, Iterable): yield from flatten(x) else: yield x items = [2, [3, 4, [5, 6], 7], 8, 'abc'] for x in flatten(items): print(x) </code></pre> <p>I was expecting to print '2, 3, 4, 5, 6, 7, 8, a, b, c'; but instead, I got '2, 3, 4, 5, 6, 7, 8 and a RecursionError. I think the 'abc' is also 'Iterable', so why the code doesn't work?</p> <p>Thank you!</p>
[ { "answer_id": 74633468, "author": "Orfeas Bourchas", "author_id": 16781682, "author_profile": "https://Stackoverflow.com/users/16781682", "pm_score": 2, "selected": false, "text": "yield from flatten(x) from collections.abc import Iterable\ndef flatten(items):\n for x in items:\n if isinstance(x, Iterable):\n if len(x)==1:\n yield next(iter(x))\n else: \n yield from flatten(x)\n else:\n yield x\n\nitems = [2, [3, 4, [5, 6], 7], 8, 'abc']\n\nfor x in flatten(items):\n print(x)\n" }, { "answer_id": 74635624, "author": "Jameson-m-Jolley", "author_id": 20649156, "author_profile": "https://Stackoverflow.com/users/20649156", "pm_score": 0, "selected": false, "text": " from collections.abc import Iterable\n\ndef flatten(items):\n for x in items:\n if isinstance(x, str):\n yield from iter(x)\n elif isinstance(x, Iterable):\n yield from flatten(x)\n else: \n yield x\n\nitems = [2, [3, 4, [5, 6], 7], 8, 'abc']\n\nfor x in flatten(items):\n print(x)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1350219/" ]
74,633,345
<p>I have some code like:</p> <pre><code>num_grades = 0 for num_grades in range(8): grade = int(input(&quot;Enter grade &quot; + str(num_grades + 1) + &quot;: &quot;)) # additional logic to check the grade and categorize it print(&quot;Total number of grades:&quot;, num_grades) # additional code to output more results </code></pre> <p>When I try this code, I find that the displayed result for <code>num_grades</code> is <code>7</code>, rather than <code>8</code> like I expect. Why is this? What is wrong with the code, and how can I fix it? I tried adding a while loop to the code, but I was unable to fix the problem this way.</p>
[ { "answer_id": 74633385, "author": "Juan Cruz Carrau", "author_id": 13262535, "author_profile": "https://Stackoverflow.com/users/13262535", "pm_score": 1, "selected": false, "text": "num_grades num_grades + 1 num_grades num_grades" }, { "answer_id": 74633454, "author": "BSimjoo", "author_id": 7421566, "author_profile": "https://Stackoverflow.com/users/7421566", "pm_score": 1, "selected": false, "text": "for num_grades in range(8): num_grads" }, { "answer_id": 74633492, "author": "Dominic Miller", "author_id": 19817523, "author_profile": "https://Stackoverflow.com/users/19817523", "pm_score": 0, "selected": false, "text": "num_grades = 0\nfor num_grades in range(9):\n if num_grades == 0:\n continue\n grade = int(input(\"Enter grade \" + str(num_grades) + \": \"))\n # additional logic to check the grade and categorize it\nprint(\"Total number of grades:\", num_grades)\n continue num_grades 1\n2\n3\n4\n5\n6\n7\n8\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649181/" ]
74,633,352
<p>I have a dataset of part numbers, and for each of those part numbers, they were replaced at a certain cycle count. For example, in the below table is an example of my data, first column being the part number, and the second being the cycle count it was replaced (ie: part abc was replaced at 100 cycles, and then again at 594, and then at 1230, and 2291):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Part #</th> <th>Cycle Count</th> </tr> </thead> <tbody> <tr> <td>abc</td> <td>100</td> </tr> <tr> <td>abc</td> <td>594</td> </tr> <tr> <td>abc</td> <td>1230</td> </tr> <tr> <td>abc</td> <td>2291</td> </tr> <tr> <td>def</td> <td>329</td> </tr> <tr> <td>def</td> <td>2001</td> </tr> <tr> <td>ghi</td> <td>1671</td> </tr> <tr> <td>jkl</td> <td>29</td> </tr> <tr> <td>jkl</td> <td>190</td> </tr> <tr> <td>mno</td> <td>700</td> </tr> <tr> <td>mno</td> <td>1102</td> </tr> <tr> <td>pqr</td> <td>2991</td> </tr> </tbody> </table> </div> <p>With this data, I am trying to create a new table that counts the number of times a part was replaced within certain cycle ranges, and create a table such as the example below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Part #</th> <th>Cycle Count Range (1-1000)</th> <th>Cycle Count Range (1001-2000)</th> <th>Cycle Count Range (2001-3000)</th> </tr> </thead> <tbody> <tr> <td>abc</td> <td>2</td> <td>1</td> <td>1</td> </tr> <tr> <td>def</td> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <td>ghi</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <td>jkl</td> <td>2</td> <td>0</td> <td>0</td> </tr> <tr> <td>mno</td> <td>1</td> <td>1</td> <td>0</td> </tr> <tr> <td>pqr</td> <td>0</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p>I tried doing this in SQL but I am not proficient enough to do it.</p>
[ { "answer_id": 74633385, "author": "Juan Cruz Carrau", "author_id": 13262535, "author_profile": "https://Stackoverflow.com/users/13262535", "pm_score": 1, "selected": false, "text": "num_grades num_grades + 1 num_grades num_grades" }, { "answer_id": 74633454, "author": "BSimjoo", "author_id": 7421566, "author_profile": "https://Stackoverflow.com/users/7421566", "pm_score": 1, "selected": false, "text": "for num_grades in range(8): num_grads" }, { "answer_id": 74633492, "author": "Dominic Miller", "author_id": 19817523, "author_profile": "https://Stackoverflow.com/users/19817523", "pm_score": 0, "selected": false, "text": "num_grades = 0\nfor num_grades in range(9):\n if num_grades == 0:\n continue\n grade = int(input(\"Enter grade \" + str(num_grades) + \": \"))\n # additional logic to check the grade and categorize it\nprint(\"Total number of grades:\", num_grades)\n continue num_grades 1\n2\n3\n4\n5\n6\n7\n8\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19935294/" ]
74,633,357
<p>I've written this code not for practical purpose but mostly out of curiosity... (btw, I know the title is not great but I couldn't think of something better... suggestions are welcome)</p> <p>Consider the following:</p> <pre><code>State next = Stream.generate(q::poll).takeWhile(Objects::nonNull) .filter(s -&gt; { if (atGoal(s)) return true; s.expand().forEach(q::add); return false; }).findFirst().orElse(null); </code></pre> <p>Say I wanted to shorten it to use only lambdas... how would I do it?</p> <p>I managed this, but I was wondering if there's some way to avoid the part with <code>anyMatch(b -&gt; true)</code></p> <pre><code>State goal = Stream.generate(fringe::poll).takeWhile(Objects::nonNull) .filter(s -&gt; atGoal(s) || s.expand().map(fringe::add).anyMatch(b -&gt; true)) .findFirst().orElse(null); </code></pre>
[ { "answer_id": 74635343, "author": "Curiosa Globunznik", "author_id": 1428369, "author_profile": "https://Stackoverflow.com/users/1428369", "pm_score": 0, "selected": false, "text": "s.expand() t.findAny() t.reduce(false, (x,y) -> true) t.collect(Collectors.toList()).isEmpty() t.iterator().hasNext() s.expand() s.expand() int addSome(Stream<whatever> s)... .filter(s -> atGoal(s) || fringe.addSome(s.expand()) > 0 atGoal .filter(s -> s.atGoalOrCouldExpand()) .peek(fringe::add)" }, { "answer_id": 74636352, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "q Queue q Stream.filter() predicate Predicate filter peek() forEach() forEachOrdered()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2375105/" ]
74,633,362
<p>We have data in DB2 something similar as below :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>GUID</th> <th>ID</th> <th>Key</th> <th>SubKey</th> </tr> </thead> <tbody> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>20</td> <td>1</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>22</td> <td>1</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>21</td> <td>2</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234568</td> <td>22</td> <td>1</td> </tr> <tr> <td>ABC-124-DEF</td> <td>1234667</td> <td>21</td> <td>2</td> </tr> <tr> <td>ABC-124-DEF</td> <td>1234668</td> <td>22</td> <td>2</td> </tr> <tr> <td>ABC-125-DEF</td> <td>1234767</td> <td>21</td> <td>1</td> </tr> <tr> <td>ABC-125-DEF</td> <td>1234768</td> <td>22</td> <td>1</td> </tr> </tbody> </table> </div> <p>I want to output with all details only where Subkey condition with 1 is repeating more than once , something as below</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>GUID</th> <th>ID</th> <th>Key</th> <th>SubKey</th> </tr> </thead> <tbody> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>20</td> <td>1</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>22</td> <td>1</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234567</td> <td>21</td> <td>2</td> </tr> <tr> <td>ABC-123-DEF</td> <td>1234568</td> <td>22</td> <td>1</td> </tr> <tr> <td>ABC-125-DEF</td> <td>1234767</td> <td>21</td> <td>1</td> </tr> <tr> <td>ABC-125-DEF</td> <td>1234768</td> <td>22</td> <td>1</td> </tr> </tbody> </table> </div> <p>Appreciate any help!</p>
[ { "answer_id": 74635343, "author": "Curiosa Globunznik", "author_id": 1428369, "author_profile": "https://Stackoverflow.com/users/1428369", "pm_score": 0, "selected": false, "text": "s.expand() t.findAny() t.reduce(false, (x,y) -> true) t.collect(Collectors.toList()).isEmpty() t.iterator().hasNext() s.expand() s.expand() int addSome(Stream<whatever> s)... .filter(s -> atGoal(s) || fringe.addSome(s.expand()) > 0 atGoal .filter(s -> s.atGoalOrCouldExpand()) .peek(fringe::add)" }, { "answer_id": 74636352, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "q Queue q Stream.filter() predicate Predicate filter peek() forEach() forEachOrdered()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8195845/" ]
74,633,372
<p>Here is the error I get and I don't know what's the problem.</p> <p><a href="https://i.stack.imgur.com/3gKqd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3gKqd.png" alt="Error" /></a></p>
[ { "answer_id": 74635343, "author": "Curiosa Globunznik", "author_id": 1428369, "author_profile": "https://Stackoverflow.com/users/1428369", "pm_score": 0, "selected": false, "text": "s.expand() t.findAny() t.reduce(false, (x,y) -> true) t.collect(Collectors.toList()).isEmpty() t.iterator().hasNext() s.expand() s.expand() int addSome(Stream<whatever> s)... .filter(s -> atGoal(s) || fringe.addSome(s.expand()) > 0 atGoal .filter(s -> s.atGoalOrCouldExpand()) .peek(fringe::add)" }, { "answer_id": 74636352, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "q Queue q Stream.filter() predicate Predicate filter peek() forEach() forEachOrdered()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649236/" ]
74,633,377
<p>I have a page control, with a control called MyControl, and inside that is a 3rd party control called Autocomplete.</p> <p>In MyControl, I've setup the inner Autocomplete control to bind to propertiers in MyControl:</p> <pre><code>&lt;Autocomplete @bind-SelectedValue=&quot;@SelectedValue&quot; @bind-SelectedText=&quot;@SelectedText&quot;&gt; &lt;/Autocomplete&gt; @code { [Parameter] public int SelectedValue { get; set; } [Parameter] public EventCallback&lt;int&gt; SelectedValueChanged { get; set; } [Parameter] public string SelectedText { get; set; } [Parameter] public EventCallback&lt;string&gt; SelectedTextChanged { get; set; } } </code></pre> <p>In My page, I want to bind MyControl to properties on my page, but the properties on my page are not getting updated. Is this implementation correct?</p> <pre><code>&lt;MyControl @bind-SelectedText=&quot;SelectedText&quot;&gt;&lt;/MyControl &gt; @code { [Parameter] public int SelectedValue { get; set; } [Parameter] public string SelectedText { get; set; } } </code></pre>
[ { "answer_id": 74635343, "author": "Curiosa Globunznik", "author_id": 1428369, "author_profile": "https://Stackoverflow.com/users/1428369", "pm_score": 0, "selected": false, "text": "s.expand() t.findAny() t.reduce(false, (x,y) -> true) t.collect(Collectors.toList()).isEmpty() t.iterator().hasNext() s.expand() s.expand() int addSome(Stream<whatever> s)... .filter(s -> atGoal(s) || fringe.addSome(s.expand()) > 0 atGoal .filter(s -> s.atGoalOrCouldExpand()) .peek(fringe::add)" }, { "answer_id": 74636352, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "q Queue q Stream.filter() predicate Predicate filter peek() forEach() forEachOrdered()" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
74,633,427
<p>I have a column containing single characters, and want to concatenate them in reverse order. How can this be accomplished in an Excel formula, without explicitly providing some list? E.g., If my input is [a;b;c;d] stored in cells A1:A4, I want to get the string &quot;dcba&quot; back. The following Excel function returns the string &quot;abcd&quot;:</p> <pre><code>=CONCAT(A1:A4) </code></pre> <p>I have tried to reverse the range to <code>A4:A1</code>, but Excel auto-corrects that. There must be some way to tell Excel to reverse the iteration direction, but I haven't been able to find anything. The reason I want to code this using the range syntax, is that recently someone inserted a row into the spreadsheet, but that additional row wasn't picked up in the formula (which is currently written as <code>CONCAT(A4,A3,A2,A1)</code>). I want people to be able to insert/delete rows without having to update the formula.</p>
[ { "answer_id": 74633792, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": false, "text": "=CONCAT(INDEX(A1:A4,SEQUENCE(ROWS(A1:A4),,ROWS(A1:A4),-1)))\n =LET(rng,A1:A4,rw,ROWS(rng),CONCAT(INDEX(rng,SEQUENCE(rw,,rw,-1))))\n" }, { "answer_id": 74638338, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "SORTBY() =CONCAT(SORTBY(A1:A4,ROW(A1:A4),-1))\n LET() =LET(a,A1:A4,CONCAT(SORTBY(a,ROW(a),-1)))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/960115/" ]
74,633,479
<p>I just cloned the a project and modified it but the centering of my logo does not work properly. When the side bar is unfolded my logo is centered properly but when its folded its not.</p> <p><a href="https://i.stack.imgur.com/GxA42.png" rel="nofollow noreferrer">Unfolded</a>, <a href="https://i.stack.imgur.com/Ts3AV.png" rel="nofollow noreferrer">Folded</a></p> <p>Git link: <a href="https://github.com/hosseinnabi-ir/Responsive-Glass-Sidebar-using-CSS-and-JavaScript" rel="nofollow noreferrer">Responsive Glass Sidebar using CSS and JavaScript</a></p> <p>I want to be able to view the div and center the logo in the sidebar when its unfolded and folded.</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>.display { color: rgb(255, 255, 255); background-color: rgb(255, 0, 0); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="display"&gt; Hello world &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74633792, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 2, "selected": false, "text": "=CONCAT(INDEX(A1:A4,SEQUENCE(ROWS(A1:A4),,ROWS(A1:A4),-1)))\n =LET(rng,A1:A4,rw,ROWS(rng),CONCAT(INDEX(rng,SEQUENCE(rw,,rw,-1))))\n" }, { "answer_id": 74638338, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "SORTBY() =CONCAT(SORTBY(A1:A4,ROW(A1:A4),-1))\n LET() =LET(a,A1:A4,CONCAT(SORTBY(a,ROW(a),-1)))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,633,504
<p>I wish to run a line detector between two known points on an image but firstly I need to widen the area around the line so my line detector has more area to work with. The main issue it stretch the area around line with respect to the line slope. For instance: <a href="https://i.stack.imgur.com/0eZsr.png" rel="nofollow noreferrer">white line generated form two points with black bounding box</a>.</p> <p>I tried manualy manipulating the box array:</p> <pre><code>input_to_min_area = np.array([[660, 888], [653, 540]]) # this works instead of contour as an input to minAreaRect rect = cv.minAreaRect(input_to_min_area) box = cv.boxPoints(rect) box[[0, 3], 0] += 20 box[[1, 2], 0] -= 20 box = np.int0(box) cv.drawContours(self.images[0], [box], 0, (0, 255, 255), 2) </code></pre> <p>But that doesn't work for any line slope. From vertical to <a href="https://i.stack.imgur.com/k02sf.png" rel="nofollow noreferrer">this angle</a> everything is fine, but for the <a href="https://i.stack.imgur.com/wYpVp.png" rel="nofollow noreferrer">horizontal lines</a> doesn't work.</p> <p>What would be a simpler solution that works for any line slope?</p>
[ { "answer_id": 74635056, "author": "Rotem", "author_id": 4926757, "author_profile": "https://Stackoverflow.com/users/4926757", "pm_score": 2, "selected": false, "text": " angle = np.deg2rad(rect[2]) # Angle of minAreaRect\n pad_x = 20*np.sin(angle)\n pad_y = 20*np.cos(angle)\n rect box[[0, 3], 0] -= pad_x\n box[[1, 2], 0] += pad_x\n box[[0, 3], 1] += pad_y\n box[[1, 2], 1] -= pad_y\n box = np.int0(box)\n import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n input_to_min_area import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\npad_x = int(round(20*np.cos(angle)))\npad_y = int(round(20*np.sin(angle)))\ntmp_to_min_area = np.array([[input_to_min_area[0, 0]+pad_x, input_to_min_area[0, 1]+pad_y], [input_to_min_area[1, 0]-pad_x, input_to_min_area[1, 1]-pad_y]])\nrect = cv2.minAreaRect(tmp_to_min_area)\n\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\n\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.line(img, (tmp_to_min_area[0, 0], tmp_to_min_area[0, 1]), (tmp_to_min_area[1, 0], tmp_to_min_area[1, 1]), (255, 0, 0), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n" }, { "answer_id": 74635505, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 3, "selected": true, "text": "minAreaRect() boxPoints() padding = 42\n\nrect = cv.minAreaRect(input_to_min_area)\n\n(center, (w,h), angle) = rect # take it apart\n\nif w < h: # we don't know which side is longer, add to shorter side\n w += padding\nelse:\n h += padding\n\nrect = (center, (w,h), angle) # rebuild\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20614959/" ]
74,633,530
<p>We have a list of orders that have multiple items, request is to have a value for each of the individual set of IDs. Like this:</p> <pre><code>order_id id_number ABC123 1 ABC123 1 DEF456 2 DEF456 2 DEF456 2 DEF456 2 GHI987 3 </code></pre> <p>So that way we get a single number for each of the order_ids (and thus they can order the list using the id_number column). Customer wants this to have an 'easier' view due to the amount of times an order can be repeated. Is there a way to achieve this?</p> <p>Thanks</p>
[ { "answer_id": 74635056, "author": "Rotem", "author_id": 4926757, "author_profile": "https://Stackoverflow.com/users/4926757", "pm_score": 2, "selected": false, "text": " angle = np.deg2rad(rect[2]) # Angle of minAreaRect\n pad_x = 20*np.sin(angle)\n pad_y = 20*np.cos(angle)\n rect box[[0, 3], 0] -= pad_x\n box[[1, 2], 0] += pad_x\n box[[0, 3], 1] += pad_y\n box[[1, 2], 1] -= pad_y\n box = np.int0(box)\n import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n input_to_min_area import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\npad_x = int(round(20*np.cos(angle)))\npad_y = int(round(20*np.sin(angle)))\ntmp_to_min_area = np.array([[input_to_min_area[0, 0]+pad_x, input_to_min_area[0, 1]+pad_y], [input_to_min_area[1, 0]-pad_x, input_to_min_area[1, 1]-pad_y]])\nrect = cv2.minAreaRect(tmp_to_min_area)\n\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\n\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.line(img, (tmp_to_min_area[0, 0], tmp_to_min_area[0, 1]), (tmp_to_min_area[1, 0], tmp_to_min_area[1, 1]), (255, 0, 0), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n" }, { "answer_id": 74635505, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 3, "selected": true, "text": "minAreaRect() boxPoints() padding = 42\n\nrect = cv.minAreaRect(input_to_min_area)\n\n(center, (w,h), angle) = rect # take it apart\n\nif w < h: # we don't know which side is longer, add to shorter side\n w += padding\nelse:\n h += padding\n\nrect = (center, (w,h), angle) # rebuild\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552281/" ]
74,633,538
<p>I have a query in Microsoft SQL Server Management Studio 18 and I am trying to show the 5 most recent dates for each customer.</p> <p>Here is the query I use:</p> <pre><code>SELECT Customer, Plant, ForecastDate FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY Plant, ForecastDate ORDER BY Customer DESC) AS ROW_NUM FROM table) AS T WHERE ROW_NUM = 1 </code></pre> <p>Here is the output of this query:</p> <p><img src="https://i.stack.imgur.com/ecofm.png" alt="Output" /></p> <p>This is what I would like the output to look like:</p> <p><img src="https://i.stack.imgur.com/7lEno.png" alt="Desired output" /></p> <p>Here is some <a href="https://zumbiel.weebly.com/uploads/4/1/5/0/41508101/book4.xlsx" rel="nofollow noreferrer">Consumable sample data</a></p> <p>I am dealing with weekly forecasts that my customers give to me that changes every week or so. I upload the data into SQL Server. I am trying to to compare and contrast the Quantity to other forecast dates. This is why I want the past 5 dates. I have multiple rows on the same date but I need the past date as well because I am trying to compare past forecasts to each other.</p>
[ { "answer_id": 74635056, "author": "Rotem", "author_id": 4926757, "author_profile": "https://Stackoverflow.com/users/4926757", "pm_score": 2, "selected": false, "text": " angle = np.deg2rad(rect[2]) # Angle of minAreaRect\n pad_x = 20*np.sin(angle)\n pad_y = 20*np.cos(angle)\n rect box[[0, 3], 0] -= pad_x\n box[[1, 2], 0] += pad_x\n box[[0, 3], 1] += pad_y\n box[[1, 2], 1] -= pad_y\n box = np.int0(box)\n import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n input_to_min_area import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\npad_x = int(round(20*np.cos(angle)))\npad_y = int(round(20*np.sin(angle)))\ntmp_to_min_area = np.array([[input_to_min_area[0, 0]+pad_x, input_to_min_area[0, 1]+pad_y], [input_to_min_area[1, 0]-pad_x, input_to_min_area[1, 1]-pad_y]])\nrect = cv2.minAreaRect(tmp_to_min_area)\n\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\n\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.line(img, (tmp_to_min_area[0, 0], tmp_to_min_area[0, 1]), (tmp_to_min_area[1, 0], tmp_to_min_area[1, 1]), (255, 0, 0), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n" }, { "answer_id": 74635505, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 3, "selected": true, "text": "minAreaRect() boxPoints() padding = 42\n\nrect = cv.minAreaRect(input_to_min_area)\n\n(center, (w,h), angle) = rect # take it apart\n\nif w < h: # we don't know which side is longer, add to shorter side\n w += padding\nelse:\n h += padding\n\nrect = (center, (w,h), angle) # rebuild\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19880719/" ]
74,633,636
<p>I have a table with two columns, and the two entries of a row show that they are related:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col1</th> <th>Col2</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>A</td> </tr> <tr> <td>b</td> <td>B</td> </tr> <tr> <td>a</td> <td>C</td> </tr> <tr> <td>c</td> <td>A</td> </tr> <tr> <td>b</td> <td>D</td> </tr> </tbody> </table> </div> <p>Here <code>a</code> is related to <code>A, C</code> and <code>b</code> to <code>B, D</code> and <code>c</code> to <code>A</code>, meaning the same entry in <code>col1</code> might have multiple labels in <code>col2</code> related. I trained a <code>Machine Learning</code> model to quantify the relationship between <code>Col1</code> and <code>Col2</code> by creating a vector embedding of <code>Col1</code> and <code>Col2</code> and optimizing the <code>cosine_similarity</code> between the two vectors. Now, I want to test my model by calculating <code>Recall</code> on a test set. I want to check if at various <code>recall@N</code>, what proportion of these positive relationships can be retrieved. Suppose I have normalized vector representation of all entries in each column, then I can calculate the cosine distance between them as :</p> <pre><code>cosine_distance = torch.mm(col1_feature, col2_feature.t()) </code></pre> <p>which gives a matrix of distances between all pairs that can be formed between <code>col1</code> and <code>col2</code>.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>dist(a,A)</td> <td>dist(a,B)</td> <td>dist(a,C)</td> <td>dist(a,A)</td> <td>dist(a, D)</td> </tr> <tr> <td>dist(b,A)</td> <td>dist(b,B)</td> <td>dist(b,C)</td> <td>dist(b,A)</td> <td>dist(b, D)</td> </tr> <tr> <td>dist(a,A)</td> <td>dist(a,B)</td> <td>dist(a,C)</td> <td>dist(a,A)</td> <td>dist(a, D)</td> </tr> <tr> <td>dist(c,A)</td> <td>dist(c,B)</td> <td>dist(c,C)</td> <td>dist(c,A)</td> <td>dist(c, D)</td> </tr> <tr> <td>dist(b,A)</td> <td>dist(b,B)</td> <td>dist(b,C)</td> <td>dist(b,A)</td> <td>dist(b, D)</td> </tr> </tbody> </table> </div> <p>I can then calculate which pairs have largest distance to calculate <code>recall@k</code>. My question is how can I make this efficient for a millions of rows. I found out this module in pytorch: <code>torchmetrics.classification.MultilabelRecall</code>(<a href="https://torchmetrics.readthedocs.io/en/stable/classification/recall.html" rel="nofollow noreferrer">https://torchmetrics.readthedocs.io/en/stable/classification/recall.html</a>), that seems to be useful but for that I need to specify number of labels. In my case, I can have variable number of labels for each unique entry of <code>col1</code>. Any ideas?</p>
[ { "answer_id": 74635056, "author": "Rotem", "author_id": 4926757, "author_profile": "https://Stackoverflow.com/users/4926757", "pm_score": 2, "selected": false, "text": " angle = np.deg2rad(rect[2]) # Angle of minAreaRect\n pad_x = 20*np.sin(angle)\n pad_y = 20*np.cos(angle)\n rect box[[0, 3], 0] -= pad_x\n box[[1, 2], 0] += pad_x\n box[[0, 3], 1] += pad_y\n box[[1, 2], 1] -= pad_y\n box = np.int0(box)\n import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n input_to_min_area import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\npad_x = int(round(20*np.cos(angle)))\npad_y = int(round(20*np.sin(angle)))\ntmp_to_min_area = np.array([[input_to_min_area[0, 0]+pad_x, input_to_min_area[0, 1]+pad_y], [input_to_min_area[1, 0]-pad_x, input_to_min_area[1, 1]-pad_y]])\nrect = cv2.minAreaRect(tmp_to_min_area)\n\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\n\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.line(img, (tmp_to_min_area[0, 0], tmp_to_min_area[0, 1]), (tmp_to_min_area[1, 0], tmp_to_min_area[1, 1]), (255, 0, 0), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n" }, { "answer_id": 74635505, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 3, "selected": true, "text": "minAreaRect() boxPoints() padding = 42\n\nrect = cv.minAreaRect(input_to_min_area)\n\n(center, (w,h), angle) = rect # take it apart\n\nif w < h: # we don't know which side is longer, add to shorter side\n w += padding\nelse:\n h += padding\n\nrect = (center, (w,h), angle) # rebuild\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680455/" ]
74,633,650
<p>So I have an assignment that asked me to draw any regular polygon using Turtle and I created the code. It works but my mentor said to try again. I would like to know what I did wrong, Thank you!</p> <p>The requirements for this assignment are:</p> <ul> <li>The program should take in input from the user.</li> <li>The program should have a function that: <ul> <li>takes in the number of sides as a parameter.</li> <li>calculates the angle</li> <li>uses the appropriate angle to draw the polygon</li> </ul> </li> </ul> <pre><code>from turtle import Turtle turtle = Turtle() side = int(input(&quot;Enter the number of the sides: &quot;)) def poly(): for i in range(side): turtle.forward(100) turtle.right(360 / side) poly() </code></pre>
[ { "answer_id": 74635056, "author": "Rotem", "author_id": 4926757, "author_profile": "https://Stackoverflow.com/users/4926757", "pm_score": 2, "selected": false, "text": " angle = np.deg2rad(rect[2]) # Angle of minAreaRect\n pad_x = 20*np.sin(angle)\n pad_y = 20*np.cos(angle)\n rect box[[0, 3], 0] -= pad_x\n box[[1, 2], 0] += pad_x\n box[[0, 3], 1] += pad_y\n box[[1, 2], 1] -= pad_y\n box = np.int0(box)\n import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n input_to_min_area import cv2\nimport numpy as np\n\nimg = cv2.imread('sketch.png')\n\n#input_to_min_area = np.array([[584, 147], [587, 502]]) # this works instead of contour as an input to minAreaRect\n#input_to_min_area = np.array([[109, 515], [585, 144]]) # this works instead of contour as an input to minAreaRect\ninput_to_min_area = np.array([[80, 103], [590, 502]]) # this works instead of contour as an input to minAreaRect\n\nrect = cv2.minAreaRect(input_to_min_area)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\npad_x = int(round(20*np.cos(angle)))\npad_y = int(round(20*np.sin(angle)))\ntmp_to_min_area = np.array([[input_to_min_area[0, 0]+pad_x, input_to_min_area[0, 1]+pad_y], [input_to_min_area[1, 0]-pad_x, input_to_min_area[1, 1]-pad_y]])\nrect = cv2.minAreaRect(tmp_to_min_area)\n\nbox = cv2.boxPoints(rect)\n\nangle = np.deg2rad(rect[2]) # Angle of minAreaRect\n\n# Padding in each direction is perpendicular to the angle of minAreaRect\npad_x = 20*np.sin(angle)\npad_y = 20*np.cos(angle)\n\nbox[[0, 3], 0] -= pad_x\nbox[[1, 2], 0] += pad_x\nbox[[0, 3], 1] += pad_y\nbox[[1, 2], 1] -= pad_y\n\nbox = np.int0(box)\n\ncv2.drawContours(img, [box], 0, (0, 255, 255), 2)\n\ncv2.line(img, (tmp_to_min_area[0, 0], tmp_to_min_area[0, 1]), (tmp_to_min_area[1, 0], tmp_to_min_area[1, 1]), (255, 0, 0), 2)\n\ncv2.imshow('img', img)\ncv2.waitKey()\ncv2.destroyAllWindows()\n" }, { "answer_id": 74635505, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 3, "selected": true, "text": "minAreaRect() boxPoints() padding = 42\n\nrect = cv.minAreaRect(input_to_min_area)\n\n(center, (w,h), angle) = rect # take it apart\n\nif w < h: # we don't know which side is longer, add to shorter side\n w += padding\nelse:\n h += padding\n\nrect = (center, (w,h), angle) # rebuild\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20421383/" ]
74,633,667
<p>I have a noisy list with 3 different rows that looks like this:</p> <pre><code>array = ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper', 'cup, egg, pillow, leash, banana, raindrop, phone, animal, shirt, basket', '1. Dog 2. America 3. Notebook 4. Moisturizer 5. ADHD 6. Balloon 7. Contacts 8. Blanket 9. Home 10. Pencil'] </code></pre> <p>How do I index each element in each row to normalize all the strings and remove any &quot;,&quot; as well as any numerical values to look like this:</p> <pre><code>array = ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper', 'cup egg pillow leash banana raindrop phone animal shirt basket', 'Dog America Notebook Moisturizer ADHD Balloon Contacts Blanket Home Pencil'] </code></pre> <p>I have tried:</p> <pre><code> for i in array: for j in i: j.strip(&quot; &quot;) j.strip(&quot;,&quot;) </code></pre> <p>However am confused by the order and sequence in which to store the words back into their specific row. Thanks</p>
[ { "answer_id": 74633781, "author": "S3DEV", "author_id": 6340496, "author_profile": "https://Stackoverflow.com/users/6340496", "pm_score": 3, "selected": true, "text": "[a-zA-Z]+ str.join() import re\n\nout = [' '.join(re.findall('[a-zA-Z]+', i)) for i in array]\n ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper',\n 'cup egg pillow leash banana raindrop phone animal shirt basket',\n 'Dog America Notebook Moisturizer ADHD Balloon Contacts Blanket Home Pencil']\n" }, { "answer_id": 74644439, "author": "Ethan Chartrand", "author_id": 13514681, "author_profile": "https://Stackoverflow.com/users/13514681", "pm_score": 0, "selected": false, "text": "out = []\nfor i in array:\n row = []\n for j in i.split():\n j = j.strip(',.')\n try:\n int(j)\n except:\n row.append(j)\n row = f\"{' '.join(row)}\"\n out.append(row)\nprint(out)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18317880/" ]
74,633,694
<p>I have a registered <code>onmousemove</code> event in useEffect as follows. But in order not to run the effect every time the component renders I pass it an empty array dependency. But still the function that handles the event is called. But the function is inside useEffect. How could this be possible?</p> <pre><code> import { useEffect, useState } from &quot;react&quot;; const UseEffect1 = () =&gt; { const [X, setX] = useState(0); const [Y, setY] = useState(0); const handleMouseMove = (e) =&gt; { setX(e.clientX); setY(e.clientY); }; useEffect(() =&gt; { window.addEventListener(&quot;onmousemove&quot;, handleMouseMove); }, []); return ( &lt;div&gt; &lt;p&gt; width {X} - height {Y} &lt;/p&gt; &lt;/div&gt; ); }; export default UseEffect1; </code></pre>
[ { "answer_id": 74633781, "author": "S3DEV", "author_id": 6340496, "author_profile": "https://Stackoverflow.com/users/6340496", "pm_score": 3, "selected": true, "text": "[a-zA-Z]+ str.join() import re\n\nout = [' '.join(re.findall('[a-zA-Z]+', i)) for i in array]\n ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper',\n 'cup egg pillow leash banana raindrop phone animal shirt basket',\n 'Dog America Notebook Moisturizer ADHD Balloon Contacts Blanket Home Pencil']\n" }, { "answer_id": 74644439, "author": "Ethan Chartrand", "author_id": 13514681, "author_profile": "https://Stackoverflow.com/users/13514681", "pm_score": 0, "selected": false, "text": "out = []\nfor i in array:\n row = []\n for j in i.split():\n j = j.strip(',.')\n try:\n int(j)\n except:\n row.append(j)\n row = f\"{' '.join(row)}\"\n out.append(row)\nprint(out)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17051327/" ]
74,633,695
<p>I would like to create a numeric indicator variable that captures the levels of a complex string <code>id</code> variable in SAS. Note that I cannot use if-then logic, as the <code>id</code> values will change constantly.</p> <p>I have searched multiple threads and previous questions, and I am unable to find an approach that works.</p> <p>Below is some sample code that captures the essence of the problem.</p> <hr /> <pre><code>data value_id; length id $54 ; informat id $54. ; input id $ ; cards ; 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 tsknifwb29-818zgpj2be-vq7558xhqa-1lgqck7219-rq1ojedtmp ts1j2y9q6u-nghpfhdxsl-vkdwk060gg-s3tred6a7g-h5iqsl8cir jg1qpqhofy-02d2m62ayb-fg2f6dtvqc-vx4lsnowcj-s4kg37wxah o3qadvrqtl-kdyw9qpfir-7xeilvuk7e-g73olb67tm-nwwvla6r4g gc6dny3d5n-qzdkgfkpoc-iv1vnmwu4d-hubjun73y1-mbaggyrmkq dbvdcbvafv-cmb2zp67tn-gpnfwcvvpt-nl8qpgwn8b-l3biox4318 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym wfrbcr3i8e-3vodo5wkrr-hp733zwkhy-uxm9uf16zp-5y11re5um5 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 tsknifwb29-818zgpj2be-vq7558xhqa-1lgqck7219-rq1ojedtmp ts1j2y9q6u-nghpfhdxsl-vkdwk060gg-s3tred6a7g-h5iqsl8cir jg1qpqhofy-02d2m62ayb-fg2f6dtvqc-vx4lsnowcj-s4kg37wxah o3qadvrqtl-kdyw9qpfir-7xeilvuk7e-g73olb67tm-nwwvla6r4g gc6dny3d5n-qzdkgfkpoc-iv1vnmwu4d-hubjun73y1-mbaggyrmkq dbvdcbvafv-cmb2zp67tn-gpnfwcvvpt-nl8qpgwn8b-l3biox4318 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym wfrbcr3i8e-3vodo5wkrr-hp733zwkhy-uxm9uf16zp-5y11re5um5 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 tsknifwb29-818zgpj2be-vq7558xhqa-1lgqck7219-rq1ojedtmp ts1j2y9q6u-nghpfhdxsl-vkdwk060gg-s3tred6a7g-h5iqsl8cir jg1qpqhofy-02d2m62ayb-fg2f6dtvqc-vx4lsnowcj-s4kg37wxah o3qadvrqtl-kdyw9qpfir-7xeilvuk7e-g73olb67tm-nwwvla6r4g gc6dny3d5n-qzdkgfkpoc-iv1vnmwu4d-hubjun73y1-mbaggyrmkq dbvdcbvafv-cmb2zp67tn-gpnfwcvvpt-nl8qpgwn8b-l3biox4318 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym wfrbcr3i8e-3vodo5wkrr-hp733zwkhy-uxm9uf16zp-5y11re5um5 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 tsknifwb29-818zgpj2be-vq7558xhqa-1lgqck7219-rq1ojedtmp ts1j2y9q6u-nghpfhdxsl-vkdwk060gg-s3tred6a7g-h5iqsl8cir jg1qpqhofy-02d2m62ayb-fg2f6dtvqc-vx4lsnowcj-s4kg37wxah o3qadvrqtl-kdyw9qpfir-7xeilvuk7e-g73olb67tm-nwwvla6r4g gc6dny3d5n-qzdkgfkpoc-iv1vnmwu4d-hubjun73y1-mbaggyrmkq dbvdcbvafv-cmb2zp67tn-gpnfwcvvpt-nl8qpgwn8b-l3biox4318 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym wfrbcr3i8e-3vodo5wkrr-hp733zwkhy-uxm9uf16zp-5y11re5um5 ; proc sort data = value_id out = value_id_s ascii ; by id ; run; </code></pre> <hr /> <p>Ideally, I would like to have a result where I can create a numeric indicator variable <code>id_n</code>, like the following:</p> <pre><code> id id_n 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym 1 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym 1 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym 1 98llcibqon-u86ww0mzgo-ut58htcfv1-lybgj2gsn2-zlvu6n0mym 1 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 2 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 2 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 2 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20vk4xwo-ybcx8gaiy8 2 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 3 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 3 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 3 byxl352kpd-se5godm0gv-jukpzv1u7x-8kffj5th80-mf04nzwvrf 3 ... ... </code></pre> <p>Any advice / guidance on the approach would be very much appreciated.</p> <hr /> <p><strong>Aside</strong></p> <p>If I were using Stata, I would use <code>encode</code> and move on with my day...</p> <pre><code>. encode id, gen(id_n) . . . tab1 id id_n , nolabel -&gt; tabulation of id id | Freq. Percent Cum. ----------------------------------------+----------------------------------- 98llcibqon-u86ww0mzgo-ut58htcfv1-lybg.. | 4 10.00 10.00 9jdbh2e7z8-dc4o8mgsft-qi778mt7s0-rz20.. | 4 10.00 20.00 byxl352kpd-se5godm0gv-jukpzv1u7x-8kff.. | 4 10.00 30.00 dbvdcbvafv-cmb2zp67tn-gpnfwcvvpt-nl8q.. | 4 10.00 40.00 gc6dny3d5n-qzdkgfkpoc-iv1vnmwu4d-hubj.. | 4 10.00 50.00 jg1qpqhofy-02d2m62ayb-fg2f6dtvqc-vx4l.. | 4 10.00 60.00 o3qadvrqtl-kdyw9qpfir-7xeilvuk7e-g73o.. | 4 10.00 70.00 ts1j2y9q6u-nghpfhdxsl-vkdwk060gg-s3tr.. | 4 10.00 80.00 tsknifwb29-818zgpj2be-vq7558xhqa-1lgq.. | 4 10.00 90.00 wfrbcr3i8e-3vodo5wkrr-hp733zwkhy-uxm9.. | 4 10.00 100.00 ----------------------------------------+----------------------------------- Total | 40 100.00 -&gt; tabulation of id_n id_n | Freq. Percent Cum. ------------+----------------------------------- 1 | 4 10.00 10.00 2 | 4 10.00 20.00 3 | 4 10.00 30.00 4 | 4 10.00 40.00 5 | 4 10.00 50.00 6 | 4 10.00 60.00 7 | 4 10.00 70.00 8 | 4 10.00 80.00 9 | 4 10.00 90.00 10 | 4 10.00 100.00 ------------+----------------------------------- Total | 40 100.00 </code></pre>
[ { "answer_id": 74633781, "author": "S3DEV", "author_id": 6340496, "author_profile": "https://Stackoverflow.com/users/6340496", "pm_score": 3, "selected": true, "text": "[a-zA-Z]+ str.join() import re\n\nout = [' '.join(re.findall('[a-zA-Z]+', i)) for i in array]\n ['Apple Mug Seaweed Wallet Toilet Bear Toy Key Alcohol Paper',\n 'cup egg pillow leash banana raindrop phone animal shirt basket',\n 'Dog America Notebook Moisturizer ADHD Balloon Contacts Blanket Home Pencil']\n" }, { "answer_id": 74644439, "author": "Ethan Chartrand", "author_id": 13514681, "author_profile": "https://Stackoverflow.com/users/13514681", "pm_score": 0, "selected": false, "text": "out = []\nfor i in array:\n row = []\n for j in i.split():\n j = j.strip(',.')\n try:\n int(j)\n except:\n row.append(j)\n row = f\"{' '.join(row)}\"\n out.append(row)\nprint(out)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798099/" ]
74,633,702
<p>I'm facing this weird issue with <code>fillMaxWidth(fraction = ...)</code> with an AlertDialog and Button, where the Button shows up initially at one size, and on click it shrinks to wrapping its content. Here is the most basic example I can create. I've tried with multiple versions of Compose but they all do the same thing. Any ideas?</p> <pre><code>AlertDialog( modifier = modifier, onDismissRequest = {}, text = { }, buttons = { Button( onClick = { }, modifier = Modifier .fillMaxWidth(0.75f) .padding(start = 12.dp, end = 12.dp, bottom = 8.dp) ) { Text(text = &quot;Done&quot;) } } ) </code></pre> <p><strong>Before click:</strong></p> <p><img src="https://i.stack.imgur.com/YutKo.png" alt="Button fills size of AlertDialog" /></p> <p><strong>After click:</strong></p> <p><img src="https://i.stack.imgur.com/FssOL.png" alt="Button's width has shrunk" /></p>
[ { "answer_id": 74634186, "author": "Chris", "author_id": 2199001, "author_profile": "https://Stackoverflow.com/users/2199001", "pm_score": 0, "selected": false, "text": "@Composable\nfun AlertDialogSample() {\n MaterialTheme {\n Column {\n val openDialog = remember { mutableStateOf(false) }\n\n Button(onClick = {\n openDialog.value = true\n }) {\n Text(\"Click me\")\n }\n\n if (openDialog.value) {\n\n AlertDialog(\n onDismissRequest = {\n // Dismiss the dialog when the user clicks outside the dialog or on the back\n // button. If you want to disable that functionality, simply use an empty\n // onCloseRequest.\n openDialog.value = false\n },\n title = {\n Text(text = \"Dialog Title\")\n },\n text = {\n Text(\"Here is a text \")\n },\n confirmButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the Confirm Button\")\n }\n },\n dismissButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the dismiss Button\")\n }\n }\n )\n }\n }\n\n }\n}\n" }, { "answer_id": 74636555, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "AlertDialog AlertDialog(\n modifier = Modifier.fillMaxWidth(),\n ...\n AlertDialog(\n modifier = Modifier.width(150.dp),\n ...\n AlertDialog Button recomposition" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7359286/" ]
74,633,705
<p>I have an <code>unordered_map</code> which is supposed to mimic a filter, taking key and value as <code>std::string_view</code> respectively. Now say I want to compare two filters that have the same key-value-pairs: Will they always compare equal?</p> <p>My thought is the following: The compiler tries its best to merge const char*'s with the same byte information into one place in the binary, therefore within a specific translation unit, the string literal addresses will always match. Later I'm passing these addresses into the constructor of std::string_view. Naturally, as std::string_view doesn't implement the comparison <code>operator==()</code>, the compyler will byte-compare the classes and only when address and length match exactly, the std::string_views compare equal.</p> <p><strong>However</strong>: What happens if I instantiate a filter outside of this translation unit with exactly the same contents as the first filter and link the files together later? Will the compiler be able to see beyond the TU boundaries and merge the string literal locations as well? Or will the equal comparison fail as the underlying string views will have different addresses for their respective string literals?</p> <p><a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:9,positionColumn:2,positionLineNumber:9,selectionStartColumn:2,selectionStartLineNumber:9,startColumn:2,startLineNumber:9),source:%27%23include+%3Cunordered_map%3E%0A%23include+%3Cstring_view%3E%0A%23include+%3Ccstdio%3E%0A%0A%0Ausing+filter_t+%3D+std::unordered_map%3Cstd::string_view,+std::string_view%3E%3B%0A%0Aint+main()%0A%7B%0A++++filter_t+myfilter+%3D+%7B%7B+%22key1%22,+%22value%22%7D,+%7B%22key2%22,+%22value2%22+%7D%7D%3B%0A%0A++++filter_t+my_second_filter+%3D+%7B%7B+%22key1%22,+%22value%22%7D,+%7B%22key2%22,+%22value2%22+%7D%7D%3B%0A%0A++++if+(my_second_filter+%3D%3D+myfilter)+%7B%0A++++++++printf(%22filters+are+the+same!!%5Cn%22)%3B%0A++++%7D%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:47.31070496083551,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((g:!((h:compiler,i:(compiler:g122,deviceViewOpen:%271%27,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,libs:!(),options:%27-Wall+-Os+--std%3Dc%2B%2B20%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27+x86-64+gcc+12.2+(Editor+%231)%27,t:%270%27)),header:(),l:%274%27,m:41.3677130044843,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:output,i:(compilerName:%27x86-64+gcc+12.2%27,editorid:1,fontScale:14,fontUsePx:%270%27,j:1,wrap:%271%27),l:%275%27,n:%270%27,o:%27Output+of+x86-64+gcc+12.2+(Compiler+%231)%27,t:%270%27)),k:50,l:%274%27,m:58.632286995515706,n:%270%27,o:%27%27,s:0,t:%270%27)),k:52.689295039164485,l:%273%27,n:%270%27,o:%27%27,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">Demo</a></p> <pre><code>#include &lt;unordered_map&gt; #include &lt;string_view&gt; #include &lt;cstdio&gt; using filter_t = std::unordered_map&lt;std::string_view, std::string_view&gt;; int main() { filter_t myfilter = {{ &quot;key1&quot;, &quot;value&quot;}, {&quot;key2&quot;, &quot;value2&quot; }}; filter_t my_second_filter = {{ &quot;key1&quot;, &quot;value&quot;}, {&quot;key2&quot;, &quot;value2&quot; }}; if (my_second_filter == myfilter) { printf(&quot;filters are the same!\n&quot;); } } </code></pre>
[ { "answer_id": 74634186, "author": "Chris", "author_id": 2199001, "author_profile": "https://Stackoverflow.com/users/2199001", "pm_score": 0, "selected": false, "text": "@Composable\nfun AlertDialogSample() {\n MaterialTheme {\n Column {\n val openDialog = remember { mutableStateOf(false) }\n\n Button(onClick = {\n openDialog.value = true\n }) {\n Text(\"Click me\")\n }\n\n if (openDialog.value) {\n\n AlertDialog(\n onDismissRequest = {\n // Dismiss the dialog when the user clicks outside the dialog or on the back\n // button. If you want to disable that functionality, simply use an empty\n // onCloseRequest.\n openDialog.value = false\n },\n title = {\n Text(text = \"Dialog Title\")\n },\n text = {\n Text(\"Here is a text \")\n },\n confirmButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the Confirm Button\")\n }\n },\n dismissButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the dismiss Button\")\n }\n }\n )\n }\n }\n\n }\n}\n" }, { "answer_id": 74636555, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "AlertDialog AlertDialog(\n modifier = Modifier.fillMaxWidth(),\n ...\n AlertDialog(\n modifier = Modifier.width(150.dp),\n ...\n AlertDialog Button recomposition" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11770390/" ]
74,633,709
<p>When I try to install npm I get this error version 8.19.3</p> <p>npm ERR! 404 Not Found - GET <a href="https://skimdb.npmjs.com/registry/laravel-echo-server/-/laravel-echo-server-1.6.3.tgz" rel="nofollow noreferrer">https://skimdb.npmjs.com/registry/laravel-echo-server/-/laravel-echo-server-1.6.3.tgz</a> - not_found npm ERR! 404 npm ERR! 404 'laravel-echo-server@https://skimdb.npmjs.com/registry/laravel-echo-server/-/laravel-echo-server-1.6.3.tgz' is not in this registry.</p>
[ { "answer_id": 74634186, "author": "Chris", "author_id": 2199001, "author_profile": "https://Stackoverflow.com/users/2199001", "pm_score": 0, "selected": false, "text": "@Composable\nfun AlertDialogSample() {\n MaterialTheme {\n Column {\n val openDialog = remember { mutableStateOf(false) }\n\n Button(onClick = {\n openDialog.value = true\n }) {\n Text(\"Click me\")\n }\n\n if (openDialog.value) {\n\n AlertDialog(\n onDismissRequest = {\n // Dismiss the dialog when the user clicks outside the dialog or on the back\n // button. If you want to disable that functionality, simply use an empty\n // onCloseRequest.\n openDialog.value = false\n },\n title = {\n Text(text = \"Dialog Title\")\n },\n text = {\n Text(\"Here is a text \")\n },\n confirmButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the Confirm Button\")\n }\n },\n dismissButton = {\n Button(\n modifier = Modifier\n .fillMaxWidth(0.75f)\n .padding(start = 12.dp, end = 12.dp, bottom = 8.dp),\n onClick = {\n openDialog.value = false\n }) {\n Text(\"This is the dismiss Button\")\n }\n }\n )\n }\n }\n\n }\n}\n" }, { "answer_id": 74636555, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": "AlertDialog AlertDialog(\n modifier = Modifier.fillMaxWidth(),\n ...\n AlertDialog(\n modifier = Modifier.width(150.dp),\n ...\n AlertDialog Button recomposition" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74633709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649071/" ]