qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,484,688
<p>I currently have the code below which produces a resizable list, except the li elements do not match the height of their neighbor. It's similar to the question <a href="https://stackoverflow.com/questions/17011822/force-all-items-in-list-in-each-row-to-have-the-same-height-each-item-has-dynam">posted here</a> with the exception that the number of items per row should be dynamic. How can I make each li in a row match that row's highest li while preserving the existing functionality?</p> <p>List example used in images:</p> <pre><code> &lt;ul&gt; &lt;li&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra nunc vitae massa elementum ultricies a non ipsum.&lt;/li&gt; &lt;li&gt;Nunc porttitor pretium ex, in molestie lacus molestie eget.&lt;/li&gt; &lt;li&gt;Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. &lt;/li&gt; &lt;li&gt;Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu nisi dictum, a tincidunt sapien dictum.&lt;/li&gt; &lt;li&gt;Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam elementum laoreet lacus.&lt;/li&gt; &lt;li&gt;Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate, cursus volutpat nulla vehicula.&lt;/li&gt; &lt;li&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra nunc vitae massa elementum ultricies a non ipsum.&lt;/li&gt; &lt;li&gt;Nunc porttitor pretium ex, in molestie lacus molestie eget.&lt;/li&gt; &lt;li&gt;Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. &lt;/li&gt; &lt;li&gt;Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu nisi dictum, a tincidunt sapien dictum.&lt;/li&gt; &lt;li&gt;Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam elementum laoreet lacus.&lt;/li&gt; &lt;li&gt;Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate, cursus volutpat nulla vehicula.&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre><code>ul { overflow: scroll; list-style: none; resize: horizontal; height: 30vh; width: 80vw; padding: 0px; } li { background-color: grey; vertical-align: top; display: inline-block; width: 20vw; margin: 2px; } </code></pre> <p>It produces the following output: <a href="https://i.stack.imgur.com/V4IAv.png" rel="nofollow noreferrer">resized to show 4 li per row</a> <a href="https://i.stack.imgur.com/Se1vX.png" rel="nofollow noreferrer">resized to show 3 li per row</a></p>
[ { "answer_id": 74484718, "author": "John", "author_id": 11111119, "author_profile": "https://Stackoverflow.com/users/11111119", "pm_score": 1, "selected": false, "text": " height: 100%; li ul {\n overflow: scroll;\n list-style: none;\n resize: horizontal;\n height: 30vh;\n width: 80vw;\n padding: 0px;\n}\nli {\n background-color: grey;\n vertical-align: top;\n display: inline-block;\n width: 20vw;\n margin: 2px;\n height: 100%;\n} <ul>\n <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra nunc vitae massa elementum ultricies a non ipsum.</li> \n <li>Nunc porttitor pretium ex, in molestie lacus molestie eget.</li>\n <li>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </li>\n <li>Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu nisi dictum, a tincidunt sapien dictum.</li>\n <li>Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam elementum laoreet lacus.</li>\n <li>Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate, cursus volutpat nulla vehicula.</li>\n <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pharetra nunc vitae massa elementum ultricies a non ipsum.</li> \n <li>Nunc porttitor pretium ex, in molestie lacus molestie eget.</li>\n <li>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </li>\n <li>Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu nisi dictum, a tincidunt sapien dictum.</li>\n <li>Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam elementum laoreet lacus.</li>\n <li>Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate, cursus volutpat nulla vehicula.</li>\n </ul>" }, { "answer_id": 74484962, "author": "abgregs", "author_id": 3145115, "author_profile": "https://Stackoverflow.com/users/3145115", "pm_score": 1, "selected": true, "text": "ul {\n display: grid;\n grid-template-columns: repeat(4, 1fr);\n grid-row-gap: 1rem;\n grid-column-gap: 1rem;\n}\n\nli {\n background: #efefef;\n list-style-type: none;\n padding: 10px;\n} <ul>\n <li>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas\n pharetra nunc vitae massa elementum ultricies a non ipsum.\n </li>\n <li>Nunc porttitor pretium ex, in molestie lacus molestie eget.</li>\n <li>\n Pellentesque habitant morbi tristique senectus et netus et malesuada\n fames ac turpis egestas.\n </li>\n <li>\n Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu\n nisi dictum, a tincidunt sapien dictum.\n </li>\n <li>\n Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam\n elementum laoreet lacus.\n </li>\n <li>\n Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate,\n cursus volutpat nulla vehicula.\n </li>\n <li>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas\n pharetra nunc vitae massa elementum ultricies a non ipsum.\n </li>\n <li>Nunc porttitor pretium ex, in molestie lacus molestie eget.</li>\n <li>\n Pellentesque habitant morbi tristique senectus et netus et malesuada\n fames ac turpis egestas.\n </li>\n <li>\n Fusce faucibus lacus eu tellus interdum aliquet. Donec euismod nisi eu\n nisi dictum, a tincidunt sapien dictum.\n </li>\n <li>\n Fusce aliquet tempus ex quis tincidunt. Donec at varius enim. Nullam\n elementum laoreet lacus.\n </li>\n <li>\n Aenean id volutpat ipsum. Maecenas vulputate odio nec lectus vulputate,\n cursus volutpat nulla vehicula.\n </li>\n </ul>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784160/" ]
74,484,709
<pre><code>def main(): plate = input(&quot;Plate: &quot;) if is_valid(plate): print(&quot;Valid&quot;) else: print(&quot;Invalid&quot;) def is_valid(s): index = [] for i in s: if i.isdigit(): index += i break print(index) if 6 &gt;= len(s) &gt;= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0': return True main() </code></pre> <p>Before I added and index[0] != '0' the code worked perfectly, but for some reason after adding that piece of code, when I go to input &quot;KEVIN&quot; an error(index out of range) pops up. How do I prevent this error from popping while still checking out the requirements for the code in the if statement?</p>
[ { "answer_id": 74484772, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": false, "text": "def is_valid(s):\n index = []\n for i in s:\n if i.isdigit():\n index += i\n break\n print(index)\n if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0':\n return True\n\nis_valid(\"KEVIN\")\n \"KEVIN\" i.isdigit() True index def is_valid(s):\n index = []\n for i in s:\n if i.isdigit():\n index += i\n break\n print(index)\n if (6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() \n and index and index[0] != '0'):\n return True\n" }, { "answer_id": 74484788, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": 0, "selected": false, "text": "s index index[0] != '0' s" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19395309/" ]
74,484,711
<p>I want to make a program where 2 options will be written on text and I want to make my program whenever the user choose one of those option the other option will be greyed out.</p> <p><a href="https://i.stack.imgur.com/IC170.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IC170.png" alt="enter image description here" /></a></p> <p>I've tried using text button, but it's still a bit wacky for my taste.</p>
[ { "answer_id": 74484757, "author": "manhtuan21", "author_id": 8921450, "author_profile": "https://Stackoverflow.com/users/8921450", "pm_score": 3, "selected": true, "text": "class _MyHomePageState extends State<MyHomePage> {\n int _selectIndex = 0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Row(\n children: [\n InkWell(\n onTap: () {\n setState(() {\n _selectIndex = 0;\n });\n },\n child: Text(\n 'Celcius',\n style: TextStyle(\n color: _selectIndex == 0 ? Colors.black : Colors.grey,\n ),\n ),\n ),\n const Text(' | '),\n InkWell(\n onTap: () {\n setState(() {\n _selectIndex = 1;\n });\n },\n child: Text(\n 'Fashrenheit',\n style: TextStyle(\n color: _selectIndex == 1 ? Colors.black : Colors.grey,\n ),\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74484950, "author": "Soliev", "author_id": 19945688, "author_profile": "https://Stackoverflow.com/users/19945688", "pm_score": 1, "selected": false, "text": "class HomePage extends StatefulWidget {\n const HomePage({super.key});\n\n @override\n State<HomePage> createState() => _HomePageState();\n}\n\nenum Temperature { celcius, fahrenheit }\n\nclass _HomePageState extends State<HomePage> {\n late Temperature _currentScale;\n late num _currentTemp;\n @override\n void initState() {\n super.initState();\n _currentScale = Temperature.celcius;\n _currentTemp = 24; //multiply by 1.8 add 32 C->F\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(),\n body: Center(\n child: Card(\n child: Column(\n mainAxisSize: MainAxisSize.min,\n children: [\n Text(\n _currentScale == Temperature.celcius\n ? '$_currentTemp°C'\n : '${_currentTemp * 1.8 + 32}°F',\n style: Theme.of(context).textTheme.headline2,\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n TextButton(\n child: Text(\n 'Celcius',\n style: TextStyle(\n color: _currentScale == Temperature.celcius\n ? Colors.red\n : Colors.grey),\n ),\n onPressed: () =>\n setState(() => _currentScale = Temperature.celcius)),\n const SizedBox(\n width: 10,\n ),\n TextButton(\n child: Text('Fahrenheit',\n style: TextStyle(\n color: _currentScale == Temperature.fahrenheit\n ? Colors.red\n : Colors.grey)),\n onPressed: () => setState(\n () => _currentScale = Temperature.fahrenheit))\n ],\n )\n ],\n ),\n ),\n ),\n );\n }\n}\n\n\n" }, { "answer_id": 74489507, "author": "moxa patel", "author_id": 20498098, "author_profile": "https://Stackoverflow.com/users/20498098", "pm_score": 0, "selected": false, "text": " class MyHomePage extends StatelessWidget {\n \n final RxInt _selectIndex = 0.obs;\n\n MyHomePage({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Obx(\n () => Center(\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.center,\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text(\n \"25\",\n style: TextStyle(\n fontSize: 30,\n color: _selectIndex.value == 0 ? Colors.grey : Colors.black,\n ),\n ),\n const SizedBox(\n height: 10,\n ),\n Row(\n crossAxisAlignment: CrossAxisAlignment.center,\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n InkWell(\n onTap: () {\n _selectIndex.value = 0;\n },\n child: Text(\n 'Celcius',\n style: TextStyle(\n color: _selectIndex.value == 0 ? Colors.black : Colors.grey,\n ),\n ),\n ),\n const Text(' | '),\n InkWell(\n onTap: () {\n _selectIndex.value = 1;\n },\n child: Text(\n 'Fashrenheit',\n style: TextStyle(\n color: _selectIndex.value == 1 ? Colors.black : Colors.grey,\n ),\n ),\n ),\n ],\n ),\n ],\n ),\n ),\n ),\n );\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20535950/" ]
74,484,724
<p><a href="https://i.stack.imgur.com/xvEh0.jpg" rel="nofollow noreferrer">enter image description here</a>im not able to use this keyword</p> <p>i was expecting to use this keywordim not able to use this keyword</p>
[ { "answer_id": 74484751, "author": "Soliev", "author_id": 19945688, "author_profile": "https://Stackoverflow.com/users/19945688", "pm_score": 2, "selected": false, "text": "ElevatedButton" }, { "answer_id": 74484754, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": false, "text": "RaisedButton ElevatedButton RaisedButton(/*...*/),\n ElevatedButton(/*...*/),\n" }, { "answer_id": 74484765, "author": "Jungwon", "author_id": 15134376, "author_profile": "https://Stackoverflow.com/users/15134376", "pm_score": 1, "selected": false, "text": "RaisedButton ElevatedButton return MaterialApp(\n home: Scaffold(\n body: Column(\n children: <Widget>[\n Text('question'),\n ElevatedButton(\n child: Text('answer1'),\n onPressed: null,\n ),\n ],\n ),\n ),\n );\n" }, { "answer_id": 74485322, "author": "Rahul Pandey", "author_id": 17615801, "author_profile": "https://Stackoverflow.com/users/17615801", "pm_score": 1, "selected": false, "text": "Raised button Elevated Button return MaterialApp(\n home: Scaffold(\n body: Column(children:[\n Text('question'),\n ElevatedButton(child: Text('answer1'),onPressed: null),\n ],),\n ),\n );\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18194679/" ]
74,484,744
<p>When new users sign up for our software, I get emails like:</p> <pre><code>Store Leads Account Created (ammar@123.com) </code></pre> <p>I'm trying to isolate the domain name.</p> <p>I found this regex expression which worked:</p> <pre><code>.*@(\S+) </code></pre> <p>but I get left with a trailing <code>)</code>, so I get:</p> <pre><code>123.com) </code></pre> <p>How do I remove the trailing <code>)</code>, at the end?</p>
[ { "answer_id": 74484751, "author": "Soliev", "author_id": 19945688, "author_profile": "https://Stackoverflow.com/users/19945688", "pm_score": 2, "selected": false, "text": "ElevatedButton" }, { "answer_id": 74484754, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": false, "text": "RaisedButton ElevatedButton RaisedButton(/*...*/),\n ElevatedButton(/*...*/),\n" }, { "answer_id": 74484765, "author": "Jungwon", "author_id": 15134376, "author_profile": "https://Stackoverflow.com/users/15134376", "pm_score": 1, "selected": false, "text": "RaisedButton ElevatedButton return MaterialApp(\n home: Scaffold(\n body: Column(\n children: <Widget>[\n Text('question'),\n ElevatedButton(\n child: Text('answer1'),\n onPressed: null,\n ),\n ],\n ),\n ),\n );\n" }, { "answer_id": 74485322, "author": "Rahul Pandey", "author_id": 17615801, "author_profile": "https://Stackoverflow.com/users/17615801", "pm_score": 1, "selected": false, "text": "Raised button Elevated Button return MaterialApp(\n home: Scaffold(\n body: Column(children:[\n Text('question'),\n ElevatedButton(child: Text('answer1'),onPressed: null),\n ],),\n ),\n );\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20535989/" ]
74,484,776
<p>I want to take screenshot using getDisplayMedia, but its giving me blank image.</p> <pre><code> document .getElementById(&quot;takeScreenshot&quot;) .addEventListener(&quot;click&quot;, async () =&gt; { const canvas = document.createElement(&quot;canvas&quot;); const context = canvas.getContext(&quot;2d&quot;); const video = document.createElement(&quot;video&quot;); try { const captureStream = await navigator.mediaDevices.getDisplayMedia(); video.srcObject = captureStream; video.addEventListener(&quot;loadedmetadata&quot;, (e) =&gt; { canvas.width = 600; //e.path[0]?.videoWidth; // set its size to the one of the video canvas.height = 600; //e.path[0]?.videoHeight; // video.videoHeight; context.drawImage(video, 0, 0); const frame = canvas.toDataURL(&quot;image/png&quot;); captureStream.getTracks().forEach((track) =&gt; track.stop()); const img = document.createElement(&quot;img&quot;); img.src = frame; document.body.append(img); }); } catch (err) { console.error(&quot;Error: &quot; + err); } }); </code></pre> <p>see issue on demo output: <a href="https://zm3kiy.csb.app/" rel="nofollow noreferrer">https://zm3kiy.csb.app/</a><br /> code: <a href="https://codesandbox.io/s/practical-wright-zm3kiy?file=/index.html:324-1403" rel="nofollow noreferrer">https://codesandbox.io/s/practical-wright-zm3kiy?file=/index.html:324-1403</a></p>
[ { "answer_id": 74484815, "author": "Nuro007", "author_id": 19669556, "author_profile": "https://Stackoverflow.com/users/19669556", "pm_score": 0, "selected": false, "text": "loadedmetadata video.addEventListener('loadedmetadata', () => {\n context.drawImage(video, 0, 0, window.width, window.height);\n const frame = canvas.toDataURL('image/png');\n captureStream.getTracks().forEach((track) => track.stop());\n \n const img = document.createElement('img');\n img.src = frame;\n document.body.append(img);\n});\n" }, { "answer_id": 74573949, "author": "François Beaufort", "author_id": 422957, "author_profile": "https://Stackoverflow.com/users/422957", "pm_score": 1, "selected": false, "text": "await video.play(); \"loadedmetadata\" document.body.onclick = async () => {\n const canvas = document.createElement(\"canvas\");\n const video = document.createElement(\"video\");\n\n // Capture media stream.\n const captureStream = await navigator.mediaDevices.getDisplayMedia();\n video.srcObject = captureStream;\n\n // Play it.\n await video.play();\n\n // Draw to canvas.\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext(\"2d\").drawImage(video, 0, 0);\n document.body.append(canvas);\n\n // Stop stream.\n captureStream.getTracks().forEach((track) => track.stop());\n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277696/" ]
74,484,801
<p>Using Node.js, I can pass a handle/ref for a http request to a child process using this construct:</p> <pre><code>const k = cp.fork(childPath); const server = http.createServer((req,res) =&gt; { k.send('foo', req.socket); }); </code></pre> <p>and in the child process, I can do:</p> <pre><code>process.on('message', (m, socket) =&gt; { // 'foo', socket socket.write([ 'HTTP/1.1 200 OK', 'Content-Type: text/html; charset=UTF-8', 'Content-Encoding: UTF-8', 'Accept-Ranges: bytes', 'Connection: keep-alive', ].join('\n') + '\n\n'); socket.write(` &lt;h1&gt; Example &lt;/h1&gt; `); socket.end('foobar'); }; </code></pre> <p>which is pretty cool, allows child processes to write directly to requests.</p> <p>I am wondering, how I can do the same for a websocket server:</p> <pre><code>const ws = require('ws'); const server = new ws.WebSocketServer({port: 5151}); </code></pre> <p>I assume passing a connection to a child process should work:</p> <pre><code>server.on('connection', c =&gt; { k.send('foo', c); /// error here }); </code></pre> <p>but I get an <strong>error</strong>, saying:</p> <p> <code>This handle type cannot be sent</code></p> <p>not sure if websocket connections have sockets as do http connections?</p>
[ { "answer_id": 74484864, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 0, "selected": false, "text": "server.on('connection', c => {\n\n console.log('new connection');\n\n const k = cp.fork('k.js', [],{\n stdio: 'pipe',\n detached: false\n });\n\n\n k.send({handle:true}, c._socket); // <--- here\n\n});\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223975/" ]
74,484,826
<p>When the <strong>More</strong> button is clicked, it should NOT expand and collapse.</p> <p><a href="https://i.stack.imgur.com/toV1b.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/toV1b.gif" alt="enter image description here" /></a></p> <p>If the accordion initial state is open, it must stay open even if button is clicked, if initial state is collapsed then after the more button the accordion should not expand.</p> <p><strong>This means clicking the more button should not have any effect on the accordion.</strong></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-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; .accordion { margin: 30px; } .accordion-button.collapsed { border-bottom: #ccc 1px solid } .accordion-body { border-left: #673ab744 1px solid; border-bottom: #673ab744 1px solid; border-right: #673ab744 1px solid } .accordion-button { display: inline !important } .flx-row { display: flex; justify-content: space-between; } .card-header-custom { display: flex; justify-content: space-between; } &lt;/style&gt; &lt;script src="/scripts/snippet-javascript-console.min.js?v=1"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="/scripts/snippet-javascript-console.min.js?v=1"&gt;&lt;/script&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"&gt; &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0"&gt; &lt;div class="card accordion-flush" id="accordionFlushExample"&gt; &lt;div class="accordion-item"&gt; &lt;h2 class="accordion-header" id="flush-headingOne"&gt; &lt;button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"&gt; &lt;div class="flx-row"&gt; &lt;div&gt; Hello World &lt;/div&gt; &lt;div id="abc"&gt; &lt;/div&gt; &lt;/div&gt; &lt;span class="text-secondary"&gt;Desc goes here&lt;/span&gt; &lt;/button&gt; &lt;/h2&gt; &lt;div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample"&gt; &lt;div class="accordion-body"&gt;Placeholder content for this accordion, which is intended to demonstrate the &lt;code&gt;.accordion-flush&lt;/code&gt; class. This is the first item's accordion body.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="accordion-item"&gt; &lt;h2 class="accordion-header" id="flush-headingTwo"&gt; &lt;button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo"&gt; Accordion Item #2 &lt;/button&gt; &lt;/h2&gt; &lt;div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample"&gt; &lt;div class="accordion-body"&gt;Placeholder content for this accordion, which is intended to demonstrate the &lt;code&gt;.accordion-flush&lt;/code&gt; class. This is the second item's accordion body. Let's imagine this being filled with some actual content.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="as-console-wrapper"&gt; &lt;div class="as-console"&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(".wdelete") .off() .on('click', function(event) { if (confirm(`Are you sure to delete the workflow ${$(this).prev().parent().prev().val()}?`) == true) { $(this) .closest('.accordion-item') .remove(); } event.preventDefault(); event.stopPropagation(); }); $("#abc").html(`&lt;div class="btn-group"&gt; &lt;button type="button" class="btn btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"&gt; More &lt;/button&gt; &lt;ul class="dropdown-menu dropdown-menu-lg-end" style=""&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Click me&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Hello me&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item tdelete" href="#"&gt;Justify me&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;`) &lt;/script&gt; &lt;div class="as-console-wrapper"&gt; &lt;div class="as-console"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="as-console-wrapper"&gt; &lt;div class="as-console"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74484864, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 0, "selected": false, "text": "server.on('connection', c => {\n\n console.log('new connection');\n\n const k = cp.fork('k.js', [],{\n stdio: 'pipe',\n detached: false\n });\n\n\n k.send({handle:true}, c._socket); // <--- here\n\n});\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549354/" ]
74,484,839
<p>I'm trying to use docker-compose to run a project with two Docker containers, MySQL and NodeJS. I'm having trouble connect to the SQL container from the backend container. My backend container uses Prisma as it's ORM and shows me the following error when <code>npx prisma migrate dev</code> is ran (during docker-compose up).</p> <pre><code>Error: P1001: Can't reach database server at `mysql`:`3306` Please make sure your database server is running at `mysql`:`3306`. </code></pre> <p>After some research, I thought the issue was my database url. The host name should match the db container name (mysql in this case), so I updated that but still no luck.</p> <pre><code>DATABASE_URL=mysql://root:root@mysql:3306/myshowlist # .env file </code></pre> <p>I also tried the container service name (db) but that wasn't it either.</p> <pre><code>DATABASE_URL=mysql://root:root@db:3306/myshowlist # .env file </code></pre> <p>What I'm finding puzzling is that my Prisma has no issue connecting to the MySQL container when it's not run inside the container. When I start the MySQL container solo and run the Prisma migrate command, it works and I can use the backend service like normal and save/read from the database. I do have to use localhost as the hostname though which makes sense.</p> <p>I'm not sure what could be the issue, I would really appreciate a nudge in the right direction!</p> <p>docker-compose.yml:</p> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.8&quot; services: api: build: context: ./api-old ports: - &quot;5001:3200&quot; container_name: api depends_on: - db db: image: mysql:5.7 restart: always container_name: mysql ports: - &quot;3306:3306&quot; environment: MYSQL_DATABASE: myshowlist MYSQL_ROOT_PASSWORD: &quot;root&quot; </code></pre> <p>./api-old/Dockerfile:</p> <pre><code>FROM node:latest WORKDIR /usr/src/app COPY package*.json ./ COPY .env ./ COPY prisma ./prisma/ RUN npm ci RUN npm run db-prod COPY . . EXPOSE 5001 CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p>schema.prisma:</p> <pre><code>datasource db { provider = &quot;mysql&quot; url = env(&quot;DATABASE_URL&quot;) } generator client { provider = &quot;prisma-client-js&quot; } </code></pre>
[ { "answer_id": 74484864, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 0, "selected": false, "text": "server.on('connection', c => {\n\n console.log('new connection');\n\n const k = cp.fork('k.js', [],{\n stdio: 'pipe',\n detached: false\n });\n\n\n k.send({handle:true}, c._socket); // <--- here\n\n});\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18970671/" ]
74,484,867
<p>So i need to create a post request that gets login data(name, email, password) from the user, runs validations, encrypts password, then stores data. The problem is that the encryption function takes time to run, and the variable is still not populated by the time i use it. Tried using another promise-await inside but didn't work. How do i wait till encryptedPass is not null?</p> <pre><code>// Bcrypt import, initialize number of rounds of salting saltRounds = 10; router.post('/user/create', bodyPraser.json(), async (req, res) =&gt; { // Some code here that runs validations // Encrypting password var passwordToEncrypt = req.body.password; var encryptedPass; // MongoDB model to store data const encryptedData = new Model({ fullname: req.body.fullname, email: req.body.email, password: encryptedPass }); // Salting function bcrypt.genSalt(saltRounds, function (err, salt) { // Hashing function bcrypt.hash(passwordToEncrypt, salt, function (err, hash) { // Store hash in database here encryptedPass = hash; }); }); // Save, and store data. Sedn success. const dataToSave = await encryptedData.save(); // The password is still null at this point res.status(200).json(dataToSave); console.log(&quot;Data saved&quot;); } catch (error) { res.status(400).json({ message: error.message }); console.log(&quot;Data not saved!&quot;); } }) </code></pre>
[ { "answer_id": 74484864, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 0, "selected": false, "text": "server.on('connection', c => {\n\n console.log('new connection');\n\n const k = cp.fork('k.js', [],{\n stdio: 'pipe',\n detached: false\n });\n\n\n k.send({handle:true}, c._socket); // <--- here\n\n});\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9010857/" ]
74,484,870
<p>I get JSON extracts throughout a day which is executed for different dates.</p> <p>As a preprocess step I would like to combine all JSONs with same date and merge them into common file with date as name.</p> <p>Multiple Json files <pre> tmp/emp1.json tmp/emp2.json tmp/emp3.json tmp/emp4.json tmp/emp5.json tmp/emp6.json </pre></p> <p>Format of each json file is somewhat like below with StartTime mentioned for each row</p> <pre> { "SQLS": [ { "ID": "0001", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q101" }, "ID": "0002", "SQLText": "INSERT INTO sales as Select * from employee where emp department = 'sales'", "Properties": { "Type": "Static", "Source": "sybase", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q102" }, "ID": "0003", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "postgres", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q103" }, "ID": "0004", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q104" } } ] } </pre> <p>I want to read each of these files and put them into respective directory as per the date.</p> <p>Destination directory would belike below</p> <pre> tmp/20221115/ tmp/20221116/ tmp/20221117/ </pre> <p>Let me know if more clarity is required.</p> <p>Appreciate your suggestions on this.</p>
[ { "answer_id": 74485340, "author": "Niko", "author_id": 7100120, "author_profile": "https://Stackoverflow.com/users/7100120", "pm_score": 1, "selected": false, "text": "import json\n\nfilenames = ['emp1', 'emp2']\ndata_list = []\nnew_filenames = []\n\n# Open files and concatenate objects\nfor filename in filenames:\n f = open(f'./data/tmp/{filename}.json')\n data = json.load(f)\n data_list.append(data['SQLS'])\n\n# Find unique different dates contained in objects\n# Process them into new filenames\nfor data in data_list:\n for obj in data:\n date = obj['Properties']['StartTime'].split(' ')[0]\n new_filename = date.replace('-', '')\n if new_filename not in new_filenames:\n new_filenames.append(new_filename)\n\n# Find objects with the right date/filename\ndef find_objects(data, filename):\n new_data = { 'SQLS': [] }\n\n for data in data_list:\n for obj in data:\n date = obj['Properties']['StartTime'].split(' ')[0]\n new_filename = date.replace('-', '')\n if new_filename == filename:\n new_data['SQLS'].append(obj)\n return new_data\n\n# Write new files\nfor filename in new_filenames:\n with open(f'./data/tmp/new_files/{filename}.json', 'w') as outfile:\n data = find_objects(data_list, filename)\n json_data = json.dumps(data, indent = 4) \n outfile.write(json_data)\n" }, { "answer_id": 74485938, "author": "Bhavesh Rathod", "author_id": 19997160, "author_profile": "https://Stackoverflow.com/users/19997160", "pm_score": 2, "selected": false, "text": " import os\n import json\n import glob\n import pandas as pd\n output_dict = {}\n input_dirpath = 'filepath'\n output_dirpath = 'Dir_path'\n def merge_jsons(input_dirpath, output_dirpath):\n all_files = glob.glob(rf'{input_dirpath}/*.json')\n for file in all_files:\n with open(file) as file:\n data = json.loads(file.read())\n\n df = pd.DataFrame(data['SQLS'])\n df['StartTime'] = pd.to_datetime(df['Properties'].apply(lambda x: \n x['StartTime'])).dt.date.astype(str)\n grps = df.groupby('StartTime')\n\n for start_time, data_obj in grps:\n date = start_time.replace('-','')\n data_obj = data_obj.drop('StartTime',axis=1).to_dict('records')\n if date not in output_dict:\n output_dict[date] = data_obj\n else:\n output_dict[date].append(data_obj)\n\n for filename, data in output_dict.items():\n with open(os.path.join(output_dirpath,filename+'.json'),'w') as writer:\n writer.write(json.dumps({'SQLS':data}))\n print('filename: ',os.path.join(output_dirpath,filename+'.json'), 'saved..')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6114709/" ]
74,484,873
<p>original dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">email</th> <th style="text-align: right;">name</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">id1@first.com</td> <td style="text-align: right;">john</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">id2@first.com</td> <td style="text-align: right;">Maike</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">id2@second</td> <td style="text-align: right;">Maike</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">id1@second.com</td> <td style="text-align: right;">john</td> </tr> </tbody> </table> </div> <p>I want to convert to this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">email</th> <th style="text-align: right;">email1</th> <th style="text-align: right;">name</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">id1@first.com</td> <td style="text-align: right;">id1@second.com</td> <td style="text-align: right;">john</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">id2@first.com</td> <td style="text-align: right;">id2@second</td> <td style="text-align: right;">Maike</td> </tr> </tbody> </table> </div> <p>it's only an example, I have very large file and more than 60 columns</p> <p>im using</p> <pre><code>df = spark.read.option(&quot;header&quot;,True) \ .csv(&quot;contatcs.csv&quot;, sep =',') </code></pre> <p>but works to with pyspark.pandas api</p> <pre><code>import pyspark.pandas as ps df = ps.read_csv('contacts.csv', sep=',') df.head() </code></pre> <p>but I prefer spark.read because it's a Lazy Evaluation and the pandas API is not</p>
[ { "answer_id": 74484960, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 1, "selected": false, "text": "collect_set array_sort from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n emails = F.array_sort(F.collect_set('email'))\ndf = df.groupBy('id', 'name').agg(\n emails[0].alias('email0'),\n emails[1].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', '1', 'id1@first.com', 'john'),\n ('2', '2', 'id2@first.com', 'Maike'),\n ('3', '2', 'id2@second', 'Maike'),\n ('4', '1', 'id1@second.com', 'john')],\n ['row_number', 'id', 'email', 'name'])\n emails = F.array_sort(F.collect_set(F.struct(F.col('row_number').cast('long'), 'email')))\ndf = df.groupBy('id', 'name').agg(\n emails[0]['email'].alias('email0'),\n emails[1]['email'].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n from pyspark.sql import Window as W\n\nw = W.partitionBy('id', 'name').orderBy('row_number')\ndf = (df\n .withColumn('_rn', F.row_number().over(w))\n .filter('_rn <= 2')\n .withColumn('_rn', F.concat(F.lit('email'), '_rn'))\n .groupBy('id', 'name')\n .pivot('_rn')\n .agg(F.first('email'))\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email1| email2|\n# +---+-----+-------------+--------------+\n# | 1| john|id1@first.com|id1@second.com|\n# | 2|Maike|id2@first.com| id2@second|\n# +---+-----+-------------+--------------+\n" }, { "answer_id": 74485137, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": true, "text": "from pyspark.sql import functions as F\ndf = spark.createDataFrame([(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], ['id', 'email', 'name'])\n\ndf = df.groupby(\"id\", \"name\").agg(F.collect_list(\"email\").alias(\"email\"))\nmax_len = df.select(F.size(\"email\").alias(\"size\")).collect()[0][\"size\"]\nfor i in range(1, max_len + 1):\n df = df.withColumn(f\"email{i}\", F.when(F.size(\"email\") >= i, F.element_at(\"email\", i)).otherwise(F.lit(\"\")))\ndf = df.drop(\"email\")\n +---+-----+-------------+--------------+\n|id |name |email1 |email2 |\n+---+-----+-------------+--------------+\n|2 |Maike|id2@first.com|id2@second |\n|3 |amy |id3@third.com| |\n|1 |john |id1@first.com|id1@second.com|\n+---+-----+-------------+--------------+\n df = pd.DataFrame(data=[(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], columns=[\"id\",\"email\",\"name\"])\n\ndf = df.groupby(\"id\").agg(email=(\"email\",list), name=(\"name\",pd.unique))\ndf2 = df.apply(lambda row: pd.Series(data={f\"email{i+1}\":v for i,v in enumerate(row[\"email\"])}, dtype=\"object\"), axis=1)\ndf = df.drop(\"email\", axis=1).merge(df2, on=\"id\")\n name email1 email2\nid \n1 john id1@first.com id1@second.com\n2 Maike id2@first.com id2@second\n3 amy id3@third.com NaN\n" }, { "answer_id": 74496774, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2_3@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n\ndf.show()\n\n\n\n+---+---------------+-----+\n| id| email| name|\n+---+---------------+-----+\n| 1| id1@first.com| john|\n| 2| id2@first.com|Maike|\n| 2|id2_3@first.com|Maike|\n| 2| id2@second|Maike|\n| 1| id1@second.com| john|\n new = ( df.groupBy('id','name').agg(collect_set('email').alias('email') )#Collect unique emails\n .withColumn('x',max(size('email')).over(Window.partitionBy()))#Find the group with maximum emails, for use in email column count\n )\n \nnew = (new.withColumn('email',F.struct(*[ F.col(\"email\")[i].alias(f\"email{i+1}\") for i in range(new.select('x').collect()[0][0])]))#Convert email column to struct type\n .selectExpr('x','id','name','email.*') #Select all columns\n )\nnew.show(truncate=False)\n +---+---+-----+-------------+--------------+---------------+\n|x |id |name |email1 |email2 |email3 |\n+---+---+-----+-------------+--------------+---------------+\n|3 |1 |john |id1@first.com|id1@second.com|null |\n|3 |2 |Maike|id2@second |id2@first.com |id2_3@first.com|\n+---+---+-----+-------------+--------------+---------------+\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5104266/" ]
74,484,894
<p>I'm trying to embed some YouTube videos for a portfolio site. I'm using the embed code given by YouTube itself under one of my videos. But when I use it, I get the &quot;Video Unavailable&quot; error message.</p> <p>Here's the embed code</p> <pre><code>&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/9ZIgQFKaK4Y&quot; title=&quot;YouTube video player&quot; frameborder=&quot;0&quot; allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot; allowfullscreen&gt;&lt;/iframe&gt; </code></pre> <p>This is what you get under the share section, so I assumed it would work. Does anyone know how to solve this?</p>
[ { "answer_id": 74484960, "author": "ZygD", "author_id": 2753501, "author_profile": "https://Stackoverflow.com/users/2753501", "pm_score": 1, "selected": false, "text": "collect_set array_sort from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n emails = F.array_sort(F.collect_set('email'))\ndf = df.groupBy('id', 'name').agg(\n emails[0].alias('email0'),\n emails[1].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', '1', 'id1@first.com', 'john'),\n ('2', '2', 'id2@first.com', 'Maike'),\n ('3', '2', 'id2@second', 'Maike'),\n ('4', '1', 'id1@second.com', 'john')],\n ['row_number', 'id', 'email', 'name'])\n emails = F.array_sort(F.collect_set(F.struct(F.col('row_number').cast('long'), 'email')))\ndf = df.groupBy('id', 'name').agg(\n emails[0]['email'].alias('email0'),\n emails[1]['email'].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n from pyspark.sql import Window as W\n\nw = W.partitionBy('id', 'name').orderBy('row_number')\ndf = (df\n .withColumn('_rn', F.row_number().over(w))\n .filter('_rn <= 2')\n .withColumn('_rn', F.concat(F.lit('email'), '_rn'))\n .groupBy('id', 'name')\n .pivot('_rn')\n .agg(F.first('email'))\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email1| email2|\n# +---+-----+-------------+--------------+\n# | 1| john|id1@first.com|id1@second.com|\n# | 2|Maike|id2@first.com| id2@second|\n# +---+-----+-------------+--------------+\n" }, { "answer_id": 74485137, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": true, "text": "from pyspark.sql import functions as F\ndf = spark.createDataFrame([(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], ['id', 'email', 'name'])\n\ndf = df.groupby(\"id\", \"name\").agg(F.collect_list(\"email\").alias(\"email\"))\nmax_len = df.select(F.size(\"email\").alias(\"size\")).collect()[0][\"size\"]\nfor i in range(1, max_len + 1):\n df = df.withColumn(f\"email{i}\", F.when(F.size(\"email\") >= i, F.element_at(\"email\", i)).otherwise(F.lit(\"\")))\ndf = df.drop(\"email\")\n +---+-----+-------------+--------------+\n|id |name |email1 |email2 |\n+---+-----+-------------+--------------+\n|2 |Maike|id2@first.com|id2@second |\n|3 |amy |id3@third.com| |\n|1 |john |id1@first.com|id1@second.com|\n+---+-----+-------------+--------------+\n df = pd.DataFrame(data=[(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], columns=[\"id\",\"email\",\"name\"])\n\ndf = df.groupby(\"id\").agg(email=(\"email\",list), name=(\"name\",pd.unique))\ndf2 = df.apply(lambda row: pd.Series(data={f\"email{i+1}\":v for i,v in enumerate(row[\"email\"])}, dtype=\"object\"), axis=1)\ndf = df.drop(\"email\", axis=1).merge(df2, on=\"id\")\n name email1 email2\nid \n1 john id1@first.com id1@second.com\n2 Maike id2@first.com id2@second\n3 amy id3@third.com NaN\n" }, { "answer_id": 74496774, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 1, "selected": false, "text": "from pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2_3@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n\ndf.show()\n\n\n\n+---+---------------+-----+\n| id| email| name|\n+---+---------------+-----+\n| 1| id1@first.com| john|\n| 2| id2@first.com|Maike|\n| 2|id2_3@first.com|Maike|\n| 2| id2@second|Maike|\n| 1| id1@second.com| john|\n new = ( df.groupBy('id','name').agg(collect_set('email').alias('email') )#Collect unique emails\n .withColumn('x',max(size('email')).over(Window.partitionBy()))#Find the group with maximum emails, for use in email column count\n )\n \nnew = (new.withColumn('email',F.struct(*[ F.col(\"email\")[i].alias(f\"email{i+1}\") for i in range(new.select('x').collect()[0][0])]))#Convert email column to struct type\n .selectExpr('x','id','name','email.*') #Select all columns\n )\nnew.show(truncate=False)\n +---+---+-----+-------------+--------------+---------------+\n|x |id |name |email1 |email2 |email3 |\n+---+---+-----+-------------+--------------+---------------+\n|3 |1 |john |id1@first.com|id1@second.com|null |\n|3 |2 |Maike|id2@second |id2@first.com |id2_3@first.com|\n+---+---+-----+-------------+--------------+---------------+\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536088/" ]
74,484,926
<p>I have a folder containing thousands of files. I plan to read the latest 50 files based on the date created, Java by default reading files created oldest, comparing each file taking lot of time, is there a better way to do this?</p> <p>I have a Folder <code>\usr\documents\archive</code> have 1000 files in it want to read 50 documents in the folder based on the file creation.</p>
[ { "answer_id": 74485909, "author": "Sagar Gandhi", "author_id": 6722664, "author_profile": "https://Stackoverflow.com/users/6722664", "pm_score": 1, "selected": false, "text": " BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);\n FileTime fileTime = attr.creationTime();\n FileTime creationTime = (FileTime) Files.getAttribute(path, \"creationTime\");\n" }, { "answer_id": 74486790, "author": "DevilsHnd", "author_id": 4725875, "author_profile": "https://Stackoverflow.com/users/4725875", "pm_score": 0, "selected": false, "text": "/**\n * Returns a String[] Array of all the files within the supplied directory\n * (folder) in either Ascending or Descending order. By default the full\n * absolute path and the file name are returned, not just the file name.\n * <p>\n * If you want the files list to be sorted in Descending Order the supply\n * <b>1</b> within the optional <b>sortOrder</b> parameter.\n * <p>\n * If you want just the file names within the String[] Array then supply\n * <b>1</b>\n * within the optional <b>fileNamesOnly</b> parameter.\n * <p>\n * <b>Example Usage:</b><pre>\n * {@code String folderPath = \"C:\\\\Log Files\\\\SpecificAppLogsFolder\";\n * String[] logFiles = getFolderFilesInOrder(folderPath);\n * for (String s : logFiles) {\n * System.out.println(s);\n * }\n * }</pre>\n *\n * @param folderPath (String) The full path to the file system directory\n * (folder) in which you want to get the list of files\n * from.<br>\n *\n * @param options (Optional - int):<pre>\n *\n * sortOrder - Default is 0 (Ascending Order) which means the files\n * list will ne returned in ascending sort order (from \n * the oldest files to the newest files). If any\n * value other than 0 (ie: 1) is supplied then the files\n * list will be returned in descending order (from newest\n * files to oldest files).\n *\n * fileNamesOnly - Default is 0 where Path and file name are returned within\n * the String[] Array. If any value other than 0 (ie: 1)\n * is supplied then only the file names itself will be\n * returned within the String[] Array.\n *\n * If an argument is supplied to this optional parameter\n * then something MUST also be supplied to the optional\n * <b>sortOrder</b> parameter (either 0 or 1).</pre>\n *\n * @return (One Dimensional String Array) The files contained within the\n * supplied directory path in the desired sort order based on their\n * Creation (last modified) timestamp.\n */\npublic String[] getFolderFilesInOrder(String folderPath, int... options) {\n File folder = new File(folderPath);\n if (!folder.exists() && !folder.isDirectory()) {\n System.err.println(\"Either the supplied folder doesn't exist \"\n + \"or it is not a directory!\");\n return null;\n }\n int sortOrder = 0; // Default - Ascending Order | any value other than 0 for Descending Order.\n int fileNamesOnly = 0; // Default - Path & file name | any value other than 0 for file names only.\n if (options.length >= 1) {\n sortOrder = options[0];\n if (options.length >= 2) {\n fileNamesOnly = options[1];\n }\n }\n\n File[] folderFilesList = folder.listFiles();\n if (sortOrder == 0) {\n Arrays.sort(folderFilesList, Comparator.comparingLong(File::lastModified));\n }\n else {\n Arrays.sort(folderFilesList, Comparator.comparingLong(File::lastModified).reversed());\n }\n\n List<String> filesList = new ArrayList<>();\n for (File f : folderFilesList) {\n if (f.isFile()) {\n filesList.add(fileNamesOnly == 0 ? f.getAbsolutePath() : f.getName());\n }\n }\n return filesList.toArray(new String[0]);\n}\n /* Get all files (file names only) within the supplied directory path \n (no sub-directories are processed) and sort them in descending order \n (newest to oldest) based on creation (modification) timestamp and \n return them in a String[] Array. */\nString[] allFiles = getFolderFilesInOrder(\"C:/MyLogFilesDirectory\", 1, 1);\n \n// The number of files desired from the directory:\nint numberOfFilesDesired = 50;\n \n/* Just in case (for some reason) the supplied directory path\n does not contain the desired number of files. */\nnumberOfFilesDesired = Math.min(numberOfFilesDesired, allFiles.length);\n \n// Retrieve the number of files we want.\nString[] desiredFiles = new String[numberOfFilesDesired];\nfor (int i = 0; i < numberOfFilesDesired; i++) {\n desiredFiles[i] = allFiles[i];\n \n //You can omit the line below. It's just for demo purposes:\n System.out.println((i+1) + \") \" + desiredFiles[i]);\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6876938/" ]
74,484,930
<p>Before you say that this is a minor problem and was discussed a million times here and on other forums, I want to say that I went through all of them and tried to implement each of their solutions but with no luck. I either missed some very small detail or there is something wrong with my project in general. Hope you might help.</p> <p><strong>The problem:</strong> After I've changed the location of &quot;Info.plist&quot; my project shows black screen.</p> <p>Or I get the following errors:</p> <p><a href="https://i.stack.imgur.com/RwwnZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RwwnZ.png" alt="enter image description here" /></a></p> <p><strong>What I've already tried:</strong></p> <ol> <li>In &quot;Target membership&quot; checked or unchecked the box with the project name</li> <li>In &quot;Targets&quot; - &quot;Build settings&quot; - &quot;Info.plist File&quot; changed location to &quot;Personal Quiz/Supporting files/Info.plist&quot; plus tried all the other possible paths.</li> <li>In &quot;Targets&quot; - &quot;Build Phases&quot; - &quot;Copy Bundle Resources&quot; - deleted and add &quot;Info.plist</li> <li>In File &quot;Info&quot; - &quot;File Inspector&quot; - &quot;Location&quot; changed to &quot;Absolute path&quot;, &quot;Relative to group&quot;, &quot;Relative to project&quot; and mirrored chosen path path to &quot;Build settings&quot;</li> <li>In simulation - &quot;Device&quot; - &quot;Erase all content and settings&quot;</li> <li>&quot;Command + Shift + K&quot; to clean the project</li> <li>Tried to read apple developers book</li> <li>Tried to implement some code</li> <li>Tried some other actions that I can't even recall</li> </ol> <p>As a result I either have a black screen or errors above. What am I doing wrong?</p>
[ { "answer_id": 74486250, "author": "Hassan", "author_id": 19500804, "author_profile": "https://Stackoverflow.com/users/19500804", "pm_score": 1, "selected": false, "text": "Bundle settings Target Open Build Phases Copy Bundle Resources info.plist info.plist file File Inspector Location: Relative to project Bundle settings Build Settings In Packaging Info.plist File" }, { "answer_id": 74490807, "author": "Ram Gandhi", "author_id": 900377, "author_profile": "https://Stackoverflow.com/users/900377", "pm_score": 0, "selected": false, "text": "Derived Data Clean build (CMD + Shift + K) derived data" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20403312/" ]
74,484,938
<p><strong>Program :</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; using namespace std; int main() { int n; // n=3 cin &gt;&gt; n; char a[n]; cin &gt;&gt; a; cout &lt;&lt; a; return 0; } </code></pre> <p><strong>input :</strong></p> <pre class="lang-none prettyprint-override"><code>3 Hello </code></pre> <p><strong>output :</strong></p> <pre class="lang-none prettyprint-override"><code>Hello </code></pre> <p>Why is my output &quot;Hello&quot; instead of &quot;Hel&quot;?</p> <p>Also, if directly assign like <code>char a[3]</code> then I get a error of &quot;stack smashing detected&quot;.</p> <p>Can somebody explain what's going on here?</p>
[ { "answer_id": 74485026, "author": "Sazzad Hissain Khan", "author_id": 1084174, "author_profile": "https://Stackoverflow.com/users/1084174", "pm_score": -1, "selected": false, "text": "int n; // n=3\nchar a[n];\n\ncin >> n;\ncin >> a;\ncout << a;\n" }, { "answer_id": 74485262, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "cin >> n;\nchar a[n];\n new[] std::vector cin >> a;\n operator>> cin.get() operator>> char *a = new char[n+1];\ncin.get(a, n+1);\n...\ndelete[] a;\n std::vector<char> a(n+1);\ncin.get(a.data(), n+1);\n...\n cout << a;\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19959107/" ]
74,484,941
<p>I'm pasting this on vim:</p> <pre><code>&quot;recreation_ground&quot; &quot;retail&quot; &quot;farmyard&quot; &quot;nature_reserve&quot; &quot;scrub&quot; &quot;park&quot; ... </code></pre> <p>If I select these lines as a block, what command(s) may I use:</p> <ol> <li><p>to &quot;flat&quot; their content to a single line,<br /> <code>&quot;recreation_ground&quot;&quot;retail&quot;&quot;farmyard&quot;&quot;nature_reserve&quot;&quot;scrub&quot;&quot;park&quot;</code></p> </li> <li><p>and (it would be perfect), adding a separator between them? <code>&quot;recreation_ground&quot;,&quot;retail&quot;,&quot;farmyard&quot;,&quot;nature_reserve&quot;,&quot;scrub&quot;,&quot;park&quot;</code></p> </li> </ol>
[ { "answer_id": 74485998, "author": "Max Shen", "author_id": 20297231, "author_profile": "https://Stackoverflow.com/users/20297231", "pm_score": 2, "selected": false, "text": "<C-v>G$A,<ESC>\n vGgJ\n :h visual-block\n:h gJ\n" }, { "answer_id": 74487576, "author": "burning_wipf", "author_id": 6736217, "author_profile": "https://Stackoverflow.com/users/6736217", "pm_score": 1, "selected": false, "text": ":norm J gg #(go to the top)\nv #(visual mode entire line)\nGG #(bottom of file)\n :\n '<,'> A, <Enter> V\ngg\nJ #(flatten/join selected section)\n" }, { "answer_id": 74488528, "author": "romainl", "author_id": 546861, "author_profile": "https://Stackoverflow.com/users/546861", "pm_score": 1, "selected": false, "text": ":help :s :'<,'>s/\\n\n :'<,'>s/\\n/,\n$x\n $x :'<,'>s/\\n\"/,\"\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2827181/" ]
74,484,945
<p>I've been following <a href="https://stackoverflow.com/questions/26921544/drawing-sine-wave-with-increasing-amplitude-and-frequency-over-time">this</a> guide, but I'm having trouble understanding/implementing the formula for AM/FM (Amplitude/Frequency Modulation) in my code. This is how they appear:</p> <p><code>f(t) = A(t) * sin(2pi * f * t)</code></p> <p><code>f(t) = sin(2pi * ((f + A(t)) * t))</code></p> <p>According to the guide/wiki, <code>A(t)</code> is the &quot;message signal&quot; and if I'm increasing the amplitude/frequency linearly, then <code>A(t) = t</code>, where t is just the time, so my code looks like this:</p> <pre><code>var time: float = 0.0 var frequency: float = 4.0 var amplitude: float = 200.0 var point = Vector2(50.0, 200.0) func _physics_process(delta): time += delta point.y += amplitude * time * cos(frequency * time) * delta point.x += 100.0 * delta $Line2D.add_point(point) </code></pre> <p>AM:</p> <p><img src="https://i.stack.imgur.com/PeIpQ.png" alt="AM" /></p> <p>I'm able to get the amplitude to increase, however, the frequency increases too. Am I doing this wrong? (I use <code>cos()</code> instead of <code>sin()</code> so I don't have to do 2 * pi)</p> <p>Similarly, I tried doing Frequency Modulation:</p> <pre><code>func _physics_process(delta): time += delta point.y += amplitude * cos((frequency + time) * time) * delta point.x += 100.0 * delta $Line2D.add_point(point) </code></pre> <p>FM:</p> <p><img src="https://i.stack.imgur.com/gQVtx.png" alt="FM" /></p> <p>The frequency increases, but the amplitude decreases.</p> <p>I've seen other posts that describe the frequency increase as a &quot;chirp&quot;, which has the same function as the Frequency Modulation. For reference, this was programmed with GDScript in Godot, which has the (0,0) in the top left, so +X is right and +Y is down.</p>
[ { "answer_id": 74486485, "author": "Spektre", "author_id": 2521214, "author_profile": "https://Stackoverflow.com/users/2521214", "pm_score": 0, "selected": false, "text": "amplitude(time) = 200.0*time y+= y= f0 - min output frequency\nf1 - max output frequency\na0 - min value of input signal\na1 - max value of input signal\nA(t) - input signal you want to modulate with\nB - output amplitude\nt - time\n // constants\nB = 200.0\na0 = 0.0\na1 = amplitude * time_duration\nf0 = 1500.0\nf1 = 2500.0\n---------------------\nt += delta\nA = amplitude*time\nf = f0 + (f1-f0)*(A-a0)/(a1-a0)\npoint.y = B * cos(f * t) * delta\npoint.x += 100.0 * delta\n f <f0,f1>" }, { "answer_id": 74490148, "author": "pm101", "author_id": 2368681, "author_profile": "https://Stackoverflow.com/users/2368681", "pm_score": 2, "selected": true, "text": "2 * PI * F * T extends Control\n\nvar time: float = 0.0\nvar frequency: float = 4.0\n\nvar carrier_amplitude : float = 1.0\nvar carrier_frequency : float = 0.2\n\nconst pixels_per_x = 100; # zoom on x\nconst pixels_per_y = 100; # zoom on y\n\nfunc _physics_process(delta):\n var point : Vector2\n\n time += delta\n\n var _signal = cos(2 * PI * frequency * time)\n var modulating_signal = carrier_amplitude * cos(2 * PI * carrier_frequency * time)\n\n point.y = pixels_per_y * (_signal * modulating_signal)\n point.x = pixels_per_x * (time)\n\n $Line2D.add_point(point)\n extends Control\n\nvar time: float = 0.0\nvar frequency: float = 2\n\nvar modulation_index : float = 4\nvar modulation_frequency : float = 0.2\n\nconst pixels_per_x = 100; # zoom on x\nconst pixels_per_y = 100; # zoom on y\n\nfunc _physics_process(delta):\n var point : Vector2\n\n time += delta\n\n var fm_signal = cos( (2 * PI * frequency * time) + modulation_index*sin(2 * PI * modulation_frequency * time) ) # this is another method that adds offset onto phase\n \n point.y = pixels_per_y * (fm_signal)\n point.x = pixels_per_x * (time)\n\n $Line2D.add_point(point)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20535775/" ]
74,484,951
<p>I have this data:</p> <pre><code>df['profile'] = { 'symbol': 'AAPL', 'price': 150.72, 'beta': 1.246644, 'volAvg': 89576498, 'mktCap': 2397668846469, 'lastDiv': 0.91, 'range': '129.04-182.94', 'changes': 1.93, 'companyName': 'Apple Inc.', 'currency': 'USD', 'cik': '0000320193', 'isin': 'US0378331005', 'cusip': '037833100', 'isFund': False} </code></pre> <p>how do i break this into a dataframe with headers of symbol, price, beta, etc and have the one row with the values?</p>
[ { "answer_id": 74485016, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 2, "selected": false, "text": "df = pd.DataFrame({\n 'ID' : 0, \n 'status' : [{\n 'symbol': 'AAPL', \n 'price': 150.72, \n 'beta': 1.246644, \n 'volAvg': 89576498, \n 'mktCap': 2397668846469, \n 'lastDiv': 0.91, \n 'range': '129.04-182.94', \n 'changes': 1.93, \n 'companyName': 'Apple Inc.', \n 'currency': 'USD', \n 'cik': '0000320193', \n 'isin': 'US0378331005', \n 'cusip': '037833100',\n 'isFund': False}]\n})\nprint(df)\n\n ID status\n0 0 {'symbol': 'AAPL', 'price': 150.72, 'beta': 1....\n status out = df['status'].apply(pd.Series)\nprint(out)\n symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund\n0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False\n" }, { "answer_id": 74485040, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "data = {'symbol': 'AAPL',\n 'price': 150.72,\n 'beta': 1.246644,\n 'volAvg': 89576498,\n 'mktCap': 2397668846469,\n 'lastDiv': 0.91,\n 'range': '129.04-182.94',\n 'changes': 1.93,\n 'companyName': 'Apple Inc.',\n 'currency': 'USD',\n 'cik': '0000320193',\n 'isin': 'US0378331005',\n 'cusip': '037833100',\n 'isFund': False}\n pd.DataFrame([data])\n symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund\n0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11770567/" ]
74,484,969
<p>So basically, the program is a &quot;sales tracker&quot; and we must enter an id, but the id must be only 8 characters long and if it isn't 8 characters long then the program will tell the user so. I've got most of the program done but I cannot seem to get this part of the program done.</p> <p>The user can also change the id in the database and the id still must be 8 characters long.</p> <p>This is the full program</p> <pre><code> import java.util.*; public class CreateSalesperson { public static void main(String[] args) { Salesperson[] salespeople = new Salesperson[20]; int x; int id; int count = 0; String name; double sales; final int QUIT = 999; char option; String message = &quot;&quot;; Scanner input = new Scanner(System.in); System.out.print(&quot;Do you want to (A)dd, or (C)hange a record or (Q)uit &gt;&gt; &quot;); option = input.nextLine().charAt(0); while(option != 'Q') { if(option == 'A') count = addOption(salespeople, count); else if(option == 'C') changeOption(salespeople, count); else System.out.println(&quot;Invalid entry&quot;); System.out.print(&quot;Do you want to (A)dd, or (C)hange a record or (Q)uit &gt;&gt; &quot;); option = input.nextLine().charAt(0); } } public static int addOption(Salesperson[] array, int count) { Scanner input = new Scanner(System.in); int id; double sales; String name; boolean alreadyEntered; if(count == array.length) System.out.println(&quot;Sorry - array is full -- cannot add a record&quot;); else { System.out.print(&quot;Enter name of salesperson &gt;&gt; &quot;); name = input.nextLine(); while(id.length() != 8) { System.out.print(&quot;Enter salesperson ID &gt;&gt; &quot;); id = input.nextInt(); } alreadyEntered = false; for(int x = 0; x &lt; count; ++x) if(array[x].getId() == id) { System.out.println(&quot;Sorry -- ID number already exists&quot;); alreadyEntered = true; } if(!alreadyEntered) { System.out.print(&quot;Enter sales amount &gt;&gt; &quot;); sales = input.nextDouble(); array[count] = new Salesperson(id, sales, name); ++count; } } display(array, count); input.nextLine(); return count; } public static void changeOption(Salesperson[] array, int count) { Scanner keyboard = new Scanner(System.in); int position = 0; int id; double sales; if(count == 0) System.out.println(&quot;Database is empty -- cannot change record&quot;); else { System.out.print(&quot;Enter ID to change &gt;&gt; &quot;); id = keyboard.nextInt(); boolean exists = false; for(int x = 0; x &lt; count; ++x) if(array[x].getId() == id) { exists = true; position = x; } if(!exists) System.out.println(&quot;Sorry - ID number #&quot; + id + &quot; does not exists in the database&quot;); else { System.out.print(&quot;Enter sales &gt;&gt; &quot;); sales = keyboard.nextDouble(); array[position].setSales(sales); } keyboard.nextLine(); display(array, count); } } public static void display(Salesperson[] array, int count) { int a,b; Salesperson temp; int highSubscript = count - 1; for(a = 0; a &lt; highSubscript; ++a) for(b = 0; b &lt; highSubscript; ++b) { if(array[b].getId() != array[b + 1].getId()) { temp = array[b]; array[b] = array[b + 1]; array[b + 1] = temp; } } System.out.println(&quot;\nCurrent database:&quot;); for(a = 0; a &lt; count; ++a) System.out.println(&quot;NAME: &quot;+ array[a].getName() + &quot; ID: #&quot; + array[a].getId() + &quot; Sales Amount: $&quot; + array[a].getSales()); System.out.println(); } } </code></pre> <p>I've tried to do a while loop with id.length != 8, but I keep getting an int cannot be dereferenced error. How can I fix this? Can I fix this? If not, what can I do to make this correct.</p> <pre><code>while(id.length() != 8) { System.out.print(&quot;Enter salesperson ID &gt;&gt; &quot;); id = input.nextInt(); } alreadyEntered = false; </code></pre>
[ { "answer_id": 74485751, "author": "DevilsHnd", "author_id": 4725875, "author_profile": "https://Stackoverflow.com/users/4725875", "pm_score": 0, "selected": false, "text": "String id = \"\";\n while (id.isEmpty()) {\n System.out.print(\"Enter salesperson ID >> \");\n id = input.nextLine().trim();\n \n // Input Validation:\n if (id.length() < 8) {\n System.out.println(\"Invalid ID Supplied (\" + id + \")! ID must be 8 characters long!\");\n id = \"\";\n }\n }\n \n // If we made it to here then the entry was good.\n System.out.println(\"The Salesman ID is: -> \" + id);\n String id = \"\";\nwhile (id.isEmpty()) {\n System.out.print(\"Enter salesperson ID >> \");\n id = input.nextLine().trim();\n \n /* Input Validation: Is the ID 8 characters long and \n are all characters numerical digits? */\n if (id.length() < 8 || !id.matches(\"\\\\d+\")) {\n System.out.println(\"Invalid ID Supplied (\" + id + \")! ID must be 8 Digits in length!\");\n id = \"\";\n }\n}\n \n// If we made it to here then the entry was good.\n \n// Convert the id string to an integer value\nint salesmanID = Integer.parseInt(id);\n \nSystem.out.println(\"The Salesman ID is: -> \" + salesmanID);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536098/" ]
74,484,971
<p>Okay, so im new to Unix and I am trying to learn the basics of Unix. I have a file called adafile that im trying to configure and just toy around with. I basically want to print the digits in the second decimal place for the numbers in column 2 (which is 1,3,5,6,4,6,2,4).</p> <pre><code>File Output: 3.0 .91 7 36 January JAN Wayne Smith 2.8 .83 4 17 February FEB Eric Kittle 5.1 .95 8 15 March MAR Morgan Leach 9.0 .76 7 19 April APR Jane Holder 3.5 .84 4 43 October OCT Victor Carter 5.2 .98 6 13 November NOV Michael John 4.5 .86 2 8 December DEC Harry Kaka 5.7 .96 4 13 September SEP Tim Simple </code></pre> <p>How do I go about getting this done without the use of scripts? I tried using the command: nawk '{print $2}' adafile</p> <pre><code>Output: .91 .83 .95 .76 .84 .98 .86 .96 </code></pre> <ul> <li>but I know it would show all the content in the 2nd column.</li> </ul> <p>Should I be using the nawk command or is there a better command for this?</p> <p>If I could get any help I much appreciate it!</p>
[ { "answer_id": 74485207, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 1, "selected": true, "text": "regex mawk NF=NF FS='^.+[.].| .+$' OFS=\n mawk NF=2 FS='^.+[.].| .+$' \n [ ] 1\n 3\n 5\n 6\n 4\n 8\n 6\n 6\n gawk '$_ = substr($(_+=++_),_+--_,_--)'\nnawk '$-__= substr($(_=NF), _,!__)' FS='^.*[.]'\nmawk '$!NF = substr($(_=NF), _,!__)' FS='^.*[.]' \n 1\n3\n5\n6\n4\n8\n6\n6\n" }, { "answer_id": 74485833, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "AWK file.txt File Output:\n3.0 .91 7 36 January JAN Wayne Smith\n2.8 .83 4 17 February FEB Eric Kittle\n5.1 .95 8 15 March MAR Morgan Leach\n9.0 .76 7 19 April APR Jane Holder\n3.5 .84 4 43 October OCT Victor Carter\n5.2 .98 6 13 November NOV Michael John\n4.5 .86 2 8 December DEC Harry Kaka\n5.7 .96 4 13 September SEP Tim Simple\n awk 'NR>1{print $2*100%10}' file.txt\n 1\n3\n5\n6\n4\n8\n6\n6\n NR>1 100 % 10" }, { "answer_id": 74499424, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "$ cut -c7 file\n1\n3\n5\n6\n4\n8\n6\n6\n $ awk '{print ( match($2,/\\./) ? substr($2,RSTART+2,1)+0 : 0 )}' file\n1\n3\n5\n6\n4\n8\n6\n6\n $ cat file\n3.0 .91 7 36 January JAN Wayne Smith\n2.8 .8 4 17 February FEB Eric Kittle\n5.7 2 4 13 September SEP Tim Simple\n $ awk '{print ( match($2,/\\./) ? substr($2,RSTART+2,1)+0 : 0 )}' file\n1\n0\n0\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536102/" ]
74,484,994
<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>$("button").on("click", function(){ var buttonClicked = $("button").attr("name"); alert("Button CLicked: " + buttonClicked); }) </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;h1 class="titleClass"&gt;jQuery&lt;/h1&gt; &lt;div class="buttonClass"&gt; &lt;button name="up_button" id="upB" class="upDown"&gt;&lt;/button&gt; &lt;button name="left_button" id="leftB" class="leftRight"&gt;&lt;/button&gt; &lt;button name="right_button" id="rightB" class="leftRight"&gt;&lt;/button&gt; &lt;button name="down_button" id="downB" class="upDown"&gt;&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I want to display the name (as alert or console.log) when a button is clicked from the above list</p> <pre><code> $(&quot;button&quot;).on(&quot;click&quot;, function(){ var buttonClicked = $(&quot;button&quot;).attr(&quot;name&quot;); alert(&quot;Button CLicked: &quot; + buttonClicked); }) </code></pre>
[ { "answer_id": 74485043, "author": "Bipin", "author_id": 5892016, "author_profile": "https://Stackoverflow.com/users/5892016", "pm_score": 0, "selected": false, "text": "<body>\n \n <h1 class=\"titleClass\">jQuery</h1>\n <div class=\"buttonClass\">\n <button name=\"up_button\" id=\"upB\" class=\"upDown\">A</button>\n <button name=\"left_button\" id=\"leftB\" class=\"leftRight\">B</button>\n <button name=\"right_button\" id=\"rightB\" class=\"leftRight\">C</button>\n <button name=\"down_button\" id=\"downB\" class=\"upDown\">D</button>\n </div>\n \n\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n <script >\n $(\"button\").on(\"click\", function(e){\n var buttonClicked = $(\"button\").attr(\"name\");\n console.log(e.target.name)\n }) \n </script>\n</body>\n event.target.value" }, { "answer_id": 74485052, "author": "Graciela Fausten Novindri", "author_id": 19696694, "author_profile": "https://Stackoverflow.com/users/19696694", "pm_score": 0, "selected": false, "text": "$(\".buttonClass\").on(\"click\", function (event) {\n var buttonClicked = event.target.name;\n alert(\"Button CLicked: \" + buttonClicked);\n });\n" }, { "answer_id": 74485208, "author": "Stacks Queue", "author_id": 14820590, "author_profile": "https://Stackoverflow.com/users/14820590", "pm_score": 1, "selected": false, "text": "$(\"button\") eventlistener $(\"button\") $(this) var buttonClicked = $(this).attr(\"name\");\n $(\"button\").on(\"click\", function(){\n var buttonClicked = $(this).attr(\"name\");\n alert(\"Button CLicked: \" + buttonClicked);\n}) <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n\n<h1 class=\"titleClass\">jQuery</h1>\n<div class=\"buttonClass\">\n <button name=\"up_button\" id=\"upB\" class=\"upDown\"></button>\n <button name=\"left_button\" id=\"leftB\" class=\"leftRight\"></button>\n <button name=\"right_button\" id=\"rightB\" class=\"leftRight\"></button>\n <button name=\"down_button\" id=\"downB\" class=\"upDown\"></button>\n</div>" }, { "answer_id": 74485276, "author": "Vivekanand Vishvkarma", "author_id": 19443694, "author_profile": "https://Stackoverflow.com/users/19443694", "pm_score": 0, "selected": false, "text": "$(\"button\").on(\"click\", function(){\n var buttonClicked = $(this).attr(\"name\");\n alert(\"Button CLicked: \" + buttonClicked);\n}) \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465069/" ]
74,484,996
<p>I am trying to use an array map for checking if same username and password exist in an object array</p> <pre><code>database.map((obj)=&gt;{ if(values.name === obj.name &amp;&amp; values.password===obj.password){ console.log(&quot;login success&quot;); } else { console.log(&quot;login Failed&quot;); } }); </code></pre>
[ { "answer_id": 74485043, "author": "Bipin", "author_id": 5892016, "author_profile": "https://Stackoverflow.com/users/5892016", "pm_score": 0, "selected": false, "text": "<body>\n \n <h1 class=\"titleClass\">jQuery</h1>\n <div class=\"buttonClass\">\n <button name=\"up_button\" id=\"upB\" class=\"upDown\">A</button>\n <button name=\"left_button\" id=\"leftB\" class=\"leftRight\">B</button>\n <button name=\"right_button\" id=\"rightB\" class=\"leftRight\">C</button>\n <button name=\"down_button\" id=\"downB\" class=\"upDown\">D</button>\n </div>\n \n\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n <script >\n $(\"button\").on(\"click\", function(e){\n var buttonClicked = $(\"button\").attr(\"name\");\n console.log(e.target.name)\n }) \n </script>\n</body>\n event.target.value" }, { "answer_id": 74485052, "author": "Graciela Fausten Novindri", "author_id": 19696694, "author_profile": "https://Stackoverflow.com/users/19696694", "pm_score": 0, "selected": false, "text": "$(\".buttonClass\").on(\"click\", function (event) {\n var buttonClicked = event.target.name;\n alert(\"Button CLicked: \" + buttonClicked);\n });\n" }, { "answer_id": 74485208, "author": "Stacks Queue", "author_id": 14820590, "author_profile": "https://Stackoverflow.com/users/14820590", "pm_score": 1, "selected": false, "text": "$(\"button\") eventlistener $(\"button\") $(this) var buttonClicked = $(this).attr(\"name\");\n $(\"button\").on(\"click\", function(){\n var buttonClicked = $(this).attr(\"name\");\n alert(\"Button CLicked: \" + buttonClicked);\n}) <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>\n\n<h1 class=\"titleClass\">jQuery</h1>\n<div class=\"buttonClass\">\n <button name=\"up_button\" id=\"upB\" class=\"upDown\"></button>\n <button name=\"left_button\" id=\"leftB\" class=\"leftRight\"></button>\n <button name=\"right_button\" id=\"rightB\" class=\"leftRight\"></button>\n <button name=\"down_button\" id=\"downB\" class=\"upDown\"></button>\n</div>" }, { "answer_id": 74485276, "author": "Vivekanand Vishvkarma", "author_id": 19443694, "author_profile": "https://Stackoverflow.com/users/19443694", "pm_score": 0, "selected": false, "text": "$(\"button\").on(\"click\", function(){\n var buttonClicked = $(this).attr(\"name\");\n alert(\"Button CLicked: \" + buttonClicked);\n}) \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74484996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376709/" ]
74,485,029
<p>How can I replace values in <code>df1</code> with var values in <code>df2</code> if they match BOTH code1 and code2, and append non-matches to the bottom <strong>keeping the order of df1 AND indexing whether the line was edited</strong>:</p> <p>Sample data:</p> <pre><code>#create sample df1 df1 &lt;- data.frame(code1=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;,&quot;E&quot;,&quot;A&quot;),code2=c(&quot;C3&quot;,&quot;C1&quot;,&quot;C4&quot;,&quot;C3&quot;,&quot;C5&quot;,&quot;C3&quot;),var1=c(1,2,3,4,5,6),var2=c(&quot;vA&quot;,&quot;vB&quot;,&quot;vC&quot;,&quot;vD&quot;,&quot;vE&quot;,&quot;vF&quot;),ver=1,stringsAsFactors = F) #create sample df2 df2 &lt;- data.frame(code1=c(&quot;E&quot;,&quot;B&quot;,&quot;Z&quot;,&quot;Z&quot;),code2=c(&quot;C3&quot;,&quot;C1&quot;,&quot;C3&quot;,&quot;C5&quot;),var1=c(9,10,1,5),var2=c(&quot;vX&quot;,&quot;vY&quot;,&quot;vD&quot;,&quot;vD&quot;),ver=2,stringsAsFactors = F) </code></pre> <p>I'd like a function that creates the following result df:</p> <pre><code> df_desired &lt;- data.frame(code1=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;,&quot;E&quot;,&quot;A&quot;,&quot;Z&quot;,&quot;Z&quot;),code2=c(&quot;C3&quot;,&quot;C1&quot;,&quot;C4&quot;,&quot;C3&quot;,&quot;C5&quot;,&quot;C3&quot;,&quot;C3&quot;,&quot;C5&quot;),var1=c(1,10,3,9,5,6,1,5),var2=c(&quot;vA&quot;,&quot;vY&quot;,&quot;vC&quot;,&quot;vX&quot;,&quot;vE&quot;,&quot;vF&quot;,&quot;vD&quot;,&quot;vD&quot;),ver=c(1,2,1,2,1,1,2,2),stringsAsFactors = F) </code></pre>
[ { "answer_id": 74485394, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 0, "selected": false, "text": "f <- function(df1, df2) {\n a <- match(df1$code1, df2$code1)\n b <- match(df1$code2, df2$code2)\n is_match <- a == b & !is.na(a) & !is.na(b)\n where_match <- a[is_match]\n \n df1[is_match,] <- df2[where_match,]\n df1$edited <- is_match\n \n bind_rows(df1, df2[1:nrow(df2) %in% where_match,])\n}\n\nf(df1, df2)\n code1 code2 var1 var2 ver edited\n1 A C3 1 vA 1 FALSE\n2 B C1 10 vY 2 TRUE\n3 C C4 3 vC 1 FALSE\n4 E C3 9 vX 2 TRUE\n5 E C5 5 vE 1 FALSE\n6 A C3 6 vF 1 FALSE\n7 E C3 9 vX 2 NA\n8 B C1 10 vY 2 NA\n" }, { "answer_id": 74488583, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 2, "selected": true, "text": "rows_upsert dplyr library(dplyr)\n\ndf1 |>\n rows_upsert(df2, by = c(\"code1\", \"code2\"))\n code1 code2 var1 var2 ver\n1 A C3 1 vA 1\n2 B C1 10 vY 2\n3 C C4 3 vC 1\n4 E C3 9 vX 2\n5 E C5 5 vE 1\n6 A C3 6 vF 1\n7 Z C3 1 vD 2\n8 Z C5 5 vD 2\n ver" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7837376/" ]
74,485,033
<p>I am trying to create an API (either REST or HTTP API) on AWS that points to some lambda function that can then access the Cloudfront HTTP headers described here:</p> <p><a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-cloudfront-headers.html" rel="nofollow noreferrer">Adding the CloudFront HTTP headers</a></p> <p>I have been struggling to get these headers added all day. I have tried the following:</p> <ol> <li>Cloudfront distribution that points to Http API with a lambda function as a route. The cloudfront distribution has an origin request policy as follows:</li> </ol> <p><a href="https://i.stack.imgur.com/Zqkuw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zqkuw.png" alt="enter image description here" /></a></p> <p>When I test this, I have no cloudfront headers appearing in the request (when I print the headers in the lambda function).</p> <ol start="2"> <li>When I try to do the same setup with a REST API, I am able to see the &quot;CloudFront-Viewer-Country&quot; and &quot;CloudFront-Viewer-ASN&quot; but don't see any other cloudfront headers, even with the above origin request policy.</li> </ol>
[ { "answer_id": 74485394, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 0, "selected": false, "text": "f <- function(df1, df2) {\n a <- match(df1$code1, df2$code1)\n b <- match(df1$code2, df2$code2)\n is_match <- a == b & !is.na(a) & !is.na(b)\n where_match <- a[is_match]\n \n df1[is_match,] <- df2[where_match,]\n df1$edited <- is_match\n \n bind_rows(df1, df2[1:nrow(df2) %in% where_match,])\n}\n\nf(df1, df2)\n code1 code2 var1 var2 ver edited\n1 A C3 1 vA 1 FALSE\n2 B C1 10 vY 2 TRUE\n3 C C4 3 vC 1 FALSE\n4 E C3 9 vX 2 TRUE\n5 E C5 5 vE 1 FALSE\n6 A C3 6 vF 1 FALSE\n7 E C3 9 vX 2 NA\n8 B C1 10 vY 2 NA\n" }, { "answer_id": 74488583, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 2, "selected": true, "text": "rows_upsert dplyr library(dplyr)\n\ndf1 |>\n rows_upsert(df2, by = c(\"code1\", \"code2\"))\n code1 code2 var1 var2 ver\n1 A C3 1 vA 1\n2 B C1 10 vY 2\n3 C C4 3 vC 1\n4 E C3 9 vX 2\n5 E C5 5 vE 1\n6 A C3 6 vF 1\n7 Z C3 1 vD 2\n8 Z C5 5 vD 2\n ver" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1763510/" ]
74,485,065
<p>Actually I had a doubt reg. <code>UUID().uuidString</code> is <strong>unique for globally like Android, iOS Swift, java and etc</strong>.</p> <p>UUID is like <code>9297EEEF-FE6D-4758-88BF-4051961B8619</code></p> <p>am generating unique id for each record in internal Database and for api callings. Same thing other teams(android and web) doing. Is that any possible for duplication?</p>
[ { "answer_id": 74485066, "author": "Kathiresan Murugan", "author_id": 2915020, "author_profile": "https://Stackoverflow.com/users/2915020", "pm_score": -1, "selected": false, "text": "String(format: \"%@-IOS-%@\", UUID().uuidString, Date().toString(format: \"ddMMyyyyHHmmss\"))\n" }, { "answer_id": 74485602, "author": "CryptoAlgorithm", "author_id": 13409955, "author_profile": "https://Stackoverflow.com/users/13409955", "pm_score": 0, "selected": false, "text": "UUID().uuidString" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915020/" ]
74,485,114
<p>This is my code below and it is not working</p> <pre><code>LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Pakistan' USE_I18N = True USE_L10N = True USE_TZ = True </code></pre> <p>it is giving me this error</p> <pre><code>A server error occurred. Please contact the administrator. </code></pre>
[ { "answer_id": 74485066, "author": "Kathiresan Murugan", "author_id": 2915020, "author_profile": "https://Stackoverflow.com/users/2915020", "pm_score": -1, "selected": false, "text": "String(format: \"%@-IOS-%@\", UUID().uuidString, Date().toString(format: \"ddMMyyyyHHmmss\"))\n" }, { "answer_id": 74485602, "author": "CryptoAlgorithm", "author_id": 13409955, "author_profile": "https://Stackoverflow.com/users/13409955", "pm_score": 0, "selected": false, "text": "UUID().uuidString" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17513262/" ]
74,485,125
<p>I have two remote reposotories and I want to list out the branches from one of the remote repositories only.</p> <p>git branch -r shows only the branches from the origin .</p>
[ { "answer_id": 74485066, "author": "Kathiresan Murugan", "author_id": 2915020, "author_profile": "https://Stackoverflow.com/users/2915020", "pm_score": -1, "selected": false, "text": "String(format: \"%@-IOS-%@\", UUID().uuidString, Date().toString(format: \"ddMMyyyyHHmmss\"))\n" }, { "answer_id": 74485602, "author": "CryptoAlgorithm", "author_id": 13409955, "author_profile": "https://Stackoverflow.com/users/13409955", "pm_score": 0, "selected": false, "text": "UUID().uuidString" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9851400/" ]
74,485,126
<p>I have my html content as:</p> <pre><code>html = &lt;div&gt;new notes&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;kssd&lt;/li&gt;&lt;/ol&gt;&lt;ul&gt;&lt;li&gt;cds&lt;/li&gt;&lt;li&gt;dsdsk&lt;/li&gt;&lt;/ul&gt;&lt;font color=\&quot;#66717b\&quot;&gt;ndsmnd&lt;/font&gt;&lt;/div&gt; </code></pre> <p>When I convert the above expression to string, it throws error</p> <pre><code>html_str = str(html) </code></pre> <p>I can see the &quot; are already escaped here. do I need to replace /&quot; with //&quot; and then convert to string?</p>
[ { "answer_id": 74485066, "author": "Kathiresan Murugan", "author_id": 2915020, "author_profile": "https://Stackoverflow.com/users/2915020", "pm_score": -1, "selected": false, "text": "String(format: \"%@-IOS-%@\", UUID().uuidString, Date().toString(format: \"ddMMyyyyHHmmss\"))\n" }, { "answer_id": 74485602, "author": "CryptoAlgorithm", "author_id": 13409955, "author_profile": "https://Stackoverflow.com/users/13409955", "pm_score": 0, "selected": false, "text": "UUID().uuidString" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954738/" ]
74,485,127
<p>is the number 1 stored in memory as 00000001 00000000 00000000 00000000?</p> <pre><code>#include &lt;stdio.h&gt; int main() { unsigned int a[3] = {1, 1, 0x7f7f0501}; int *p = a; printf(&quot;%d %p\n&quot;, *p, p); p = (long long)p + 1; printf(&quot;%d %p\n&quot;, *p, p); char *p3 = a; int i; for (i = 0; i &lt; 12; i++, p3++) { printf(&quot;%x %p\n&quot;, *p3, p3); } return 0; } </code></pre> <p>Why is <code>16777216</code> printed in the output:</p> <p><img src="https://i.stack.imgur.com/jWPqi.png" alt="output" /></p>
[ { "answer_id": 74485154, "author": "Özgür Murat Sağdıçoğlu", "author_id": 5106317, "author_profile": "https://Stackoverflow.com/users/5106317", "pm_score": 2, "selected": false, "text": " (long long)p+1\n |\n v\nYour memory: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, ...]\n \n" }, { "answer_id": 74485546, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "p = (long long)p + 1; int * a[] #include <stdio.h>\n#include <stdlib.h>\n\nvoid dump(size_t sz, const void *ptr) {\n const unsigned char *byte_ptr = (const unsigned char *) ptr;\n for (size_t i = 0; i < sz; i++) {\n printf(\"%p %02X\\n\", (void*) byte_ptr, *byte_ptr);\n byte_ptr++;\n }\n}\n\nint main(void) {\n unsigned int a[3] = {1, 1, 0x7f7f0501u};\n dump(sizeof a, a);\n}\n" }, { "answer_id": 74485796, "author": "chqrlie", "author_id": 4593267, "author_profile": "https://Stackoverflow.com/users/4593267", "pm_score": 0, "selected": false, "text": "printf(\"%d %p\\n\", *p, p) p (void *)p printf void * int * void * p = (long long)p + 1 int p p = (void *)((intptr_t)p + 1); p = (void *)((char *)p + 1); int a 1 01 00 00 00 0x7f7f0501 01 05 7f 7f printf(\"%d %p\\n\", *p, p) p a *p 00 00 00 01 1 1 int 16777216 char * char printf(\"%x\\n\", *p3); ffffff80 p3 80 unsigned char *" }, { "answer_id": 74486560, "author": "Erdal Küçük", "author_id": 11867590, "author_profile": "https://Stackoverflow.com/users/11867590", "pm_score": 2, "selected": false, "text": "int #include <stdio.h>\n#include <stdbool.h>\n\ntypedef union byte_rec {\n struct bit_rec {\n bool b0 : 1;\n bool b1 : 1;\n bool b2 : 1;\n bool b3 : 1;\n bool b4 : 1;\n bool b5 : 1;\n bool b6 : 1;\n bool b7 : 1;\n } bits;\n unsigned char value;\n} byte_t;\n\ntypedef union int_rec {\n struct bytes_rec {\n byte_t b0;\n byte_t b1;\n byte_t b2;\n byte_t b3;\n } bytes;\n int value;\n} int_t;\n\nvoid printByte(byte_t *b)\n{\n printf(\n \"%d %d %d %d %d %d %d %d \", \n b->bits.b0,\n b->bits.b1,\n b->bits.b2,\n b->bits.b3,\n b->bits.b4,\n b->bits.b5,\n b->bits.b6,\n b->bits.b7\n );\n}\n\nvoid printInt(int_t *i)\n{\n printf(\"%p: \", i);\n printByte(&i->bytes.b0);\n printByte(&i->bytes.b1);\n printByte(&i->bytes.b2);\n printByte(&i->bytes.b3);\n putchar('\\n');\n}\n\nint main()\n{\n int_t i1, i2;\n \n i1.value = 0x00000001;\n i2.value = 0x80000000;\n\n printInt(&i1);\n printInt(&i2);\n\n return 0;\n}\n 0x7ffea0e30920: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0x7ffea0e30924: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n unsigned char unsigned char _Bool" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536324/" ]
74,485,129
<p>I have a file with two columns separated by tabs as follows:</p> <pre><code>OG0000000 PF03169,PF03169,PF03169,MAC1_004431-T1, OG0000002 PF07690,PF00083,PF00083,PF07690,PF00083, OG0000003 MAC1_000127-T1, OG0000004 PF13246,PF00689,PF00690, OG0000005 PF00012,PF01061,PF12697,PF00012, </code></pre> <p>I just want to remove duplicate strings within the second column, while not changing anything in the first column, so that my final output looks like this:</p> <pre><code>OG0000000 PF03169,MAC1_004431-T1, OG0000002 PF07690,PF00083, OG0000003 MAC1_000127-T1, OG0000004 PF13246,PF00689,PF00690, OG0000005 PF00012,PF01061,PF12697, </code></pre> <p>I tried to start this by using awk.</p> <pre><code>awk 'BEGIN{RS=ORS=&quot;,&quot;} !seen[$0]++' file.txt </code></pre> <p>But my output looks like this, where there are still some duplicates if the duplicated string occurs first.</p> <pre><code>OG0000000 PF03169,PF03169,MAC1_004431-T1, OG0000002 PF07690,PF00083,PF07690, OG0000003 MAC1_000127-T1, OG0000004 PF13246,PF00689,PF00690, OG0000005 PF00012,PF01061,PF12697,PF00012, </code></pre> <p>I realize that the problem is because the first line that awk grabs is everything until the first comma, but I'm still rough with awk commands and couldn't figure out how to fix this without messing up the first column. Thanks in advance!</p>
[ { "answer_id": 74485147, "author": "RavinderSingh13", "author_id": 5866580, "author_profile": "https://Stackoverflow.com/users/5866580", "pm_score": 3, "selected": false, "text": "awk RS ORS , awk '\nBEGIN{ FS=\",\"; OFS=\"\\t\" }\n{\n val=\"\"\n delete arr\n num=split($2,arr,\",\")\n for(i=1;i<=num;i++){\n if(!arr[$i]++){\n val=(val?val \",\":\"\") $i\n }\n }\n print $1,val\n}\n' Input_file\n" }, { "answer_id": 74485577, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 3, "selected": false, "text": "sed $ sed -E ':a;s/([^ \\t]*[ \\t]+)?(([[:alnum:]]+,).*)\\3/\\1\\2/;ta' input_file\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74485625, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 4, "selected": true, "text": "awk awk -F '[\\t,]' '\n{\n printf \"%s\", $1 \"\\t\"\n for (i=2; i<=NF; ++i) {\n if (!seen[$i]++)\n printf \"%s,\", $i\n }\n print \"\"\n delete seen\n}' file\n\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74485684, "author": "David C. Rankin", "author_id": 3422102, "author_profile": "https://Stackoverflow.com/users/3422102", "pm_score": 3, "selected": false, "text": "$2 awk '\n { \n printf \"%s\\t\", $1\n delete seen\n n = split($2,arr,\",\")\n pos = 0\n for (i=1;i<=n;i++) { \n if (! (arr[i] in seen)) { \n printf \"%s%s\", pos ? \",\" : \"\", arr[i]\n seen[arr[i]]=1\n pos++ \n }\n }\n print \"\"\n }\n' file.txt\n file.txt OG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74488703, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 3, "selected": false, "text": "sed -E ':a;s/(\\s+.*(\\b\\S+,).*)\\2/\\1/;ta' file\n" }, { "answer_id": 74491436, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 2, "selected": false, "text": "ruby -ane 'puts \"#{$F[0]}\\t#{$F[1].split(/(?<=.),(?=.)/).uniq.join(\",\")}\"' file\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,PF00012,\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7552213/" ]
74,485,150
<p>I'm wanting make regular toast and a colored toast if possible and wondering of I have too use min engine?</p> <p>I haven't tried much?</p>
[ { "answer_id": 74485147, "author": "RavinderSingh13", "author_id": 5866580, "author_profile": "https://Stackoverflow.com/users/5866580", "pm_score": 3, "selected": false, "text": "awk RS ORS , awk '\nBEGIN{ FS=\",\"; OFS=\"\\t\" }\n{\n val=\"\"\n delete arr\n num=split($2,arr,\",\")\n for(i=1;i<=num;i++){\n if(!arr[$i]++){\n val=(val?val \",\":\"\") $i\n }\n }\n print $1,val\n}\n' Input_file\n" }, { "answer_id": 74485577, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 3, "selected": false, "text": "sed $ sed -E ':a;s/([^ \\t]*[ \\t]+)?(([[:alnum:]]+,).*)\\3/\\1\\2/;ta' input_file\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74485625, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 4, "selected": true, "text": "awk awk -F '[\\t,]' '\n{\n printf \"%s\", $1 \"\\t\"\n for (i=2; i<=NF; ++i) {\n if (!seen[$i]++)\n printf \"%s,\", $i\n }\n print \"\"\n delete seen\n}' file\n\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74485684, "author": "David C. Rankin", "author_id": 3422102, "author_profile": "https://Stackoverflow.com/users/3422102", "pm_score": 3, "selected": false, "text": "$2 awk '\n { \n printf \"%s\\t\", $1\n delete seen\n n = split($2,arr,\",\")\n pos = 0\n for (i=1;i<=n;i++) { \n if (! (arr[i] in seen)) { \n printf \"%s%s\", pos ? \",\" : \"\", arr[i]\n seen[arr[i]]=1\n pos++ \n }\n }\n print \"\"\n }\n' file.txt\n file.txt OG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,\n" }, { "answer_id": 74488703, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 3, "selected": false, "text": "sed -E ':a;s/(\\s+.*(\\b\\S+,).*)\\2/\\1/;ta' file\n" }, { "answer_id": 74491436, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 2, "selected": false, "text": "ruby -ane 'puts \"#{$F[0]}\\t#{$F[1].split(/(?<=.),(?=.)/).uniq.join(\",\")}\"' file\nOG0000000 PF03169,MAC1_004431-T1,\nOG0000002 PF07690,PF00083,PF00083,\nOG0000003 MAC1_000127-T1,\nOG0000004 PF13246,PF00689,PF00690,\nOG0000005 PF00012,PF01061,PF12697,PF00012,\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451297/" ]
74,485,204
<p>I need to clean up a dataframe whose columns come from different sources and have different types. This means that I can have, for example, string columns that contain &quot;nan&quot;, &quot;none&quot;, &quot;NULL&quot;, (as a string instead of a None value).</p> <p>My goal is to find all empty values and replace them with None. This works fine:</p> <pre><code>for column in df.columns: for idx, row in df.iterrows(): if (str(row[column]).lower() == &quot;none&quot;) or if (str(row[column]).lower() == &quot;nan&quot;) or (str(row[column]).lower() == &quot;null&quot;): df.at[row.name, column] = None </code></pre> <p>But it is obviously not the best or fastest way to do it. How can I take advantage of Pandas operations or list comprehensions to do this substitution? Thanks!</p>
[ { "answer_id": 74485247, "author": "Jonny Henly", "author_id": 1241334, "author_profile": "https://Stackoverflow.com/users/1241334", "pm_score": 0, "selected": false, "text": "for column in df.columns:\n for idx, row in df.iterrows():\n col = str(row[column]).lower()\n if (col == \"none\") or if (col == \"nan\") or (col == \"null\"):\n df.at[row.name, column] = None\n row[column] str its_none = ['none', 'nan', 'null']\nfor column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower() in its_none:\n df.at[row.name, column] = None\n for column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower().startswith('n'):\n df.at[row.name, column] = None\n" }, { "answer_id": 74485266, "author": "ArchAngelPwn", "author_id": 17750431, "author_profile": "https://Stackoverflow.com/users/17750431", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n 'name' : ['one', 'two', 'one', 'two'],\n 'A' : ['null', 'none', 'empty', 'Keep']\n})\n\ndf['A'] = np.where(df['A'].isin(['null', 'none', 'empty']), '', df['A'])\ndf\n" }, { "answer_id": 74485307, "author": "ljdyer", "author_id": 17568469, "author_profile": "https://Stackoverflow.com/users/17568469", "pm_score": 2, "selected": true, "text": "for column in df.columns:\n vals_list = df[column].to_list()\n replaced = [None if str(x).lower() in ['nan', 'none', 'null'] else x for x in vals_list]\n df[column] = replaced\n" }, { "answer_id": 74485316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "isin mask df = pd.DataFrame([[1,2,'nan'],\n ['none',3,'NULL']])\n\ndf_clean = df.mask(df.isin([\"nan\", \"none\", \"NULL\"]))\n df[df.isin([\"nan\", \"none\", \"NULL\"])] = float('nan')\n 0 1 2\n0 1 2 NaN\n1 NaN 3 NaN\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2494795/" ]
74,485,215
<p>I have classes <code>Employee</code> and <code>Address</code> as follows:</p> <pre><code>public static class Employee { private List&lt;Address&gt; address; // getters, etc. } public static class Address { private String city; // getters, etc. } </code></pre> <p>I am learning streams, I am trying to iterate over the objects from list of list and create a set of unique values. I was able to get it working by using nested for loop. How can I convert below code to streams?</p> <pre><code>public static Set&lt;String&gt; getCityUniquName(List&lt;Employee&gt; emp){ Set&lt;String&gt; cityUniquName = new HashSet&lt;&gt;(); for(Employee e: emp){ List&lt;Address&gt; addList = e.getAddress(); for(Address add: addList){ cityUniquName.add(add.getCity()); } } return cityUniquName; } </code></pre>
[ { "answer_id": 74485247, "author": "Jonny Henly", "author_id": 1241334, "author_profile": "https://Stackoverflow.com/users/1241334", "pm_score": 0, "selected": false, "text": "for column in df.columns:\n for idx, row in df.iterrows():\n col = str(row[column]).lower()\n if (col == \"none\") or if (col == \"nan\") or (col == \"null\"):\n df.at[row.name, column] = None\n row[column] str its_none = ['none', 'nan', 'null']\nfor column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower() in its_none:\n df.at[row.name, column] = None\n for column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower().startswith('n'):\n df.at[row.name, column] = None\n" }, { "answer_id": 74485266, "author": "ArchAngelPwn", "author_id": 17750431, "author_profile": "https://Stackoverflow.com/users/17750431", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n 'name' : ['one', 'two', 'one', 'two'],\n 'A' : ['null', 'none', 'empty', 'Keep']\n})\n\ndf['A'] = np.where(df['A'].isin(['null', 'none', 'empty']), '', df['A'])\ndf\n" }, { "answer_id": 74485307, "author": "ljdyer", "author_id": 17568469, "author_profile": "https://Stackoverflow.com/users/17568469", "pm_score": 2, "selected": true, "text": "for column in df.columns:\n vals_list = df[column].to_list()\n replaced = [None if str(x).lower() in ['nan', 'none', 'null'] else x for x in vals_list]\n df[column] = replaced\n" }, { "answer_id": 74485316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "isin mask df = pd.DataFrame([[1,2,'nan'],\n ['none',3,'NULL']])\n\ndf_clean = df.mask(df.isin([\"nan\", \"none\", \"NULL\"]))\n df[df.isin([\"nan\", \"none\", \"NULL\"])] = float('nan')\n 0 1 2\n0 1 2 NaN\n1 NaN 3 NaN\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536434/" ]
74,485,227
<p>I am building an app for iOS and Mac Catalyst and have been able to code most of the experience that I want except for functions that use swipe to delete in iOS.</p> <p>The view includes multiple sections, each with a List and ForEach closure. I want to be able to add the EditButton() function to the header of each section and have it apply only to that section's List.</p> <p>I can add an EditButton() function to gain this functionality, however, so far I have only been able to make that work for the entire screen, not for the individual sections.</p> <p>I have tried refactoring the code for each section into functions and into structs (as shown below). In all cases the EditButton() activates the delete icons for ALL list rows, not just the section with the button.</p> <p><a href="https://i.stack.imgur.com/ALP1C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ALP1C.png" alt="enter image description here" /></a></p> <p>I have also tried placing the EditButton() inside the section in the VStack. No difference.</p> <p>Here's a simple example with the latest code attempt:</p> <pre><code>struct ContentView: View { @State private var selectedItem: String? @State private var items = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;, &quot;Five&quot;] @State private var fruits = [&quot;Apple&quot;, &quot;Orange&quot;, &quot;Pear&quot;, &quot;Lemon&quot;, &quot;Grape&quot;] var body: some View { NavigationSplitView { ItemSection(selectedItem: $selectedItem, items: $items) FruitSection(selectedItem: $selectedItem, fruits: $fruits) } detail: { if let selectedItem { ItemDetailView(selectedItem: selectedItem) } else { EmptyView() } }//nav }//body }//struct struct ItemSection: View { @Binding var selectedItem: String? @Binding var items: [String] var body: some View { Section { VStack { List(selection: $selectedItem) { ForEach(items, id: \.self) { item in NavigationLink(value: item) { Text(item) } } .onDelete { items.remove(atOffsets: $0) } } .listStyle(PlainListStyle()) }//v .padding() } header: { HStack { Text(&quot;Section for Items&quot;) Spacer() //uncomment when you have it working //#if targetEnvironment(macCatalyst) EditButton() //#endif }//h .padding(.horizontal, 10) }//section and header }//body }//item section struct FruitSection: View { @Binding var selectedItem: String? @Binding var fruits: [String] var body: some View { Section { VStack { List(selection: $selectedItem) { ForEach(fruits, id: \.self) { fruit in NavigationLink(value: fruit) { Text(fruit) } } .onDelete { fruits.remove(atOffsets: $0) } } .listStyle(PlainListStyle()) }//v .padding() } header: { HStack { Text(&quot;Section for Fruits&quot;) Spacer() }//h .padding(.horizontal, 10) }//section fruit }//body }//fruit section struct ItemDetailView: View { var selectedItem: String var body: some View { VStack { Text(selectedItem) Text(&quot;This is the DetailView&quot;) } } } </code></pre> <p>Any guidance would be appreciated. Xcode 14.0.1 iOS 16</p>
[ { "answer_id": 74485247, "author": "Jonny Henly", "author_id": 1241334, "author_profile": "https://Stackoverflow.com/users/1241334", "pm_score": 0, "selected": false, "text": "for column in df.columns:\n for idx, row in df.iterrows():\n col = str(row[column]).lower()\n if (col == \"none\") or if (col == \"nan\") or (col == \"null\"):\n df.at[row.name, column] = None\n row[column] str its_none = ['none', 'nan', 'null']\nfor column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower() in its_none:\n df.at[row.name, column] = None\n for column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower().startswith('n'):\n df.at[row.name, column] = None\n" }, { "answer_id": 74485266, "author": "ArchAngelPwn", "author_id": 17750431, "author_profile": "https://Stackoverflow.com/users/17750431", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n 'name' : ['one', 'two', 'one', 'two'],\n 'A' : ['null', 'none', 'empty', 'Keep']\n})\n\ndf['A'] = np.where(df['A'].isin(['null', 'none', 'empty']), '', df['A'])\ndf\n" }, { "answer_id": 74485307, "author": "ljdyer", "author_id": 17568469, "author_profile": "https://Stackoverflow.com/users/17568469", "pm_score": 2, "selected": true, "text": "for column in df.columns:\n vals_list = df[column].to_list()\n replaced = [None if str(x).lower() in ['nan', 'none', 'null'] else x for x in vals_list]\n df[column] = replaced\n" }, { "answer_id": 74485316, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "isin mask df = pd.DataFrame([[1,2,'nan'],\n ['none',3,'NULL']])\n\ndf_clean = df.mask(df.isin([\"nan\", \"none\", \"NULL\"]))\n df[df.isin([\"nan\", \"none\", \"NULL\"])] = float('nan')\n 0 1 2\n0 1 2 NaN\n1 NaN 3 NaN\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2698617/" ]
74,485,240
<p>I got a project, where a table widget was used instead of DataTable, So I have been able to pull my JSON data to the table row, but I am having issues showing the header for the table, I can use DataTable to achieve, but I am required to use the table widget.</p> <p>This is what I have done so far</p> <pre><code>SingleChildScrollView( scrollDirection: Axis.horizontal, child: list.isEmpty ? Container( alignment: Alignment.center, child: CircularProgressIndicator()) : Table( columnWidths: const &lt;int, TableColumnWidth&gt;{ 0: FixedColumnWidth(50), 1: FixedColumnWidth(300), 2: FixedColumnWidth(150), 3: FixedColumnWidth(300), 4: FixedColumnWidth(150), 5: FixedColumnWidth(300), 6: FixedColumnWidth(300), }, children: list .map((item) =&gt; _buildTableRow( item, context)) .toList(), ), ) </code></pre> <p>This is my build row function</p> <pre><code>TableRow _buildTableRow(UserModel item, context) { return TableRow(key: ValueKey(item.id), children: [ tablecell(item.name), tablecell(item.email), tablecell(item.phone), ] } </code></pre> <p>The challenge is to add titles to the table.</p>
[ { "answer_id": 74485408, "author": "NehaK", "author_id": 4711030, "author_profile": "https://Stackoverflow.com/users/4711030", "pm_score": 2, "selected": false, "text": "SingleChildScrollView(\n scrollDirection: Axis.horizontal,\n child: list.isEmpty\n ? Container(\n alignment: Alignment.center,\n child: CircularProgressIndicator())\n : _tableWidget(list),\n )\n Widget _tableWidget(list) {\n if (list == null) {\n return Container();\n }\n int rowLength = list.length + 1; //+1 for titles\n List<TableRow> rows = [];\n for (int i = 0; i < rowLength; i++) {\n List<Widget> columns = [];\n bool isHeader = i == 0;\n \n columns.add(tablecell(isHeader ? \"Name\" : list[i - 1].name));\n columns.add(tablecell(isHeader ? \"Email\" : list[i - 1].email));\n columns.add(tablecell(isHeader ? \"Phone\" : list[i - 1].phone));\n \n rows.add(TableRow(\n decoration: isHeader ? _selectedDecoration() : _deselectedDecoration(),\n children: columns,\n ));\n }\n try {\n return Table(\n defaultColumnWidth: IntrinsicColumnWidth(),\n border: null,\n children: rows,\n );\n } catch (e) {\n return Text(e.toString());\n }\n }\n\n\n \n _selectedDecoration() {\n return BoxDecoration(\n borderRadius: BorderRadius.circular(4.0),\n color: Colors.lightBlue,\n );\n }\n \n\n _deselectedDecoration() {\n return BoxDecoration(\n borderRadius: BorderRadius.circular(4.0),\n color: Colors.white,\n );\n }\n" }, { "answer_id": 74485421, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": true, "text": "children:[ \n /// your Header \n ...list.map((item) => _buildTableRow(item, context)).toList(),\n ]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9688779/" ]
74,485,252
<p>So i have this project in Python (Computer Vision), which is seperating text from figures of an image (like a paper news image).</p> <p>My question is what's the best way to detect those figures in the paper ? (in Python).</p> <p>Paper image example : <a href="https://i.stack.imgur.com/JFW4A.jpg" rel="nofollow noreferrer">Paper</a> .</p> <p>Haven't try anything. I have no idea ..</p>
[ { "answer_id": 74485389, "author": "KapBytes Technologies", "author_id": 20518474, "author_profile": "https://Stackoverflow.com/users/20518474", "pm_score": 0, "selected": false, "text": "import cv2\nimport numpy as np\n\n# Read the image\nimage = cv2.imread('paper-news.png')\n\n# Convert to grayscale\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# Blur the image\nblurred = cv2.GaussianBlur(gray, (5, 5), 0)\n\ncanny = cv2.Canny(blurred, 30, 150)\n\n# Find contours in the image\ncontours, hierarchy = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n# Iterate over the contours\nfor contour in contours:\n # Get the rectangle bounding the contour\n # Draw the rectangle\n cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)\n\n# Show the image\ncv2.imshow('Image with Figures Detected', image)\ncv2.waitKey(0)\n" }, { "answer_id": 74486493, "author": "Oghli", "author_id": 5169186, "author_profile": "https://Stackoverflow.com/users/5169186", "pm_score": 2, "selected": true, "text": "pip install layoutparser # Install the base layoutparser library with \npip install \"layoutparser[layoutmodels]\" # Install DL layout model toolkit \npip install \"layoutparser[ocr]\" # Install OCR toolkit\n pip install layoutparser torchvision && pip install \"git+https://github.com/facebookresearch/detectron2.git@v0.5#egg=detectron2\" \n import layoutparser as lp\nimport cv2\n\n# Convert the image from BGR (cv2 default loading style)\n# to RGB\nimage = cv2.imread(\"test.jpg\")\nimage = image[..., ::-1] \n\n# Load the deep layout model from the layoutparser API \n# For all the supported model, please check the Model \n# Zoo Page: https://layout-parser.readthedocs.io/en/latest/notes/modelzoo.html \nmodel = lp.models.Detectron2LayoutModel('lp://PrimaLayout/mask_rcnn_R_50_FPN_3x/config', \n extra_config=[\"MODEL.ROI_HEADS.SCORE_THRESH_TEST\", 0.7],\n label_map={1:\"TextRegion\", 2:\"ImageRegion\", 3:\"TableRegion\", 4:\"MathsRegion\", 5:\"SeparatorRegion\", 6:\"OtherRegion\"})\n \n# Detect the layout of the input image\nlayout = model.detect(image)\n \n# Show the detected layout of the input image\nlp.draw_box(image, layout, box_width=3)\n \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536436/" ]
74,485,288
<p>Here's a fun CSS challenge: I want <code>ol</code> list items spaced horizontally across a <strong>100% screen width (i.e. dynamic/flex)</strong>, with a horizontal line of <strong>border-radius 2px</strong> connecting each list item without introducing html in between <code>&lt;li&gt;</code> items (introducing other html elements would be an accessibility violation as <code>&lt;ol&gt;</code> must only contain <code>&lt;li&gt;</code> children).</p> <pre class="lang-html prettyprint-override"><code>&lt;ol class=&quot;list&quot;&gt; &lt;li class=&quot;listItem&quot;&gt;One&lt;/li&gt; &lt;li class=&quot;listItem&quot;&gt;Two&lt;/li&gt; &lt;li class=&quot;listItem&quot;&gt;Three&lt;/li&gt; &lt;li class=&quot;listItem&quot;&gt;Four&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>How would I implement this?</p> <p>Playground snippet: <a href="https://jsfiddle.net/L5to7rsj/19/" rel="nofollow noreferrer">https://jsfiddle.net/L5to7rsj/19/</a></p> <p>Starting CSS:</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>.list { list-style: none; padding-inline: 0; display: flex; width: 100%; justify-content: space-between; } .listItem { position: relative; padding: 1rem; border: 1px solid; } .listItem:not(:last-child):after { content: ""; display: block; height: 4px; border-radius: 2px; background: blue; top: 50%; position: absolute; width: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ol class="list"&gt; &lt;li class="listItem"&gt;One&lt;/li&gt; &lt;li class="listItem"&gt;Two&lt;/li&gt; &lt;li class="listItem"&gt;Three&lt;/li&gt; &lt;li class="listItem"&gt;Four&lt;/li&gt; &lt;/ol&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74485403, "author": "S M Samnoon Abrar", "author_id": 8188682, "author_profile": "https://Stackoverflow.com/users/8188682", "pm_score": 0, "selected": false, "text": "left: 150%; .listItem .list {\n list-style: none;\n padding-inline: 0;\n display: flex;\n width: 100%;\n justify-content: space-between;\n}\n\n.listItem {\n position: relative;\n padding: 1rem;\n border: 1px solid;\n}\n\n.listItem:not(:last-child):after {\n content: \"\";\n display: block;\n height: 4px;\n border-radius: 2px;\n background: blue;\n top: 50%;\n left: 150%;\n position: absolute;\n width: 100%;\n} <ol class=\"list\">\n <li class=\"listItem\">One</li>\n <li class=\"listItem\">Two</li>\n <li class=\"listItem\">Three</li>\n <li class=\"listItem\">Four</li>\n</ol>" }, { "answer_id": 74486069, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 2, "selected": true, "text": ".list {\n list-style: none;\n padding-inline: 0;\n display: flex;\n width: 100%;\n height: fit-content;\n justify-content: space-between;\n position: relative;\n}\n\n.list::before {\n content: '';\n position: absolute;\n width: 100%;\n height: 100%;\n z-index: -1;\n background-image: linear-gradient(white 0 calc(50% - 2px), blue calc(50% - 2px) calc(50% + 2px), white calc(50% + 2px) 100%);\n background-repeat: no-repeat;\n}\n\n.listItem {\n position: relative;\n padding: 1rem;\n border: 1px solid;\n background: white;\n box-sizing: border-box;\n}\n\n.listItem:not(:first-child)::before,\n.listItem:not(:last-child)::after {\n content: \"\";\n position: absolute;\n height: 4px;\n width: 4px;\n top: calc(50% - 2px);\n z-index: -1;\n}\n\n.listItem:not(:first-child)::before {\n background-image: radial-gradient(blue 0 70%, transparent 70% 100%), linear-gradient(to right, transparent 0 50%, white 50% 100%);\n right: calc(100% + 1px);\n}\n\n.listItem:not(:last-child)::after {\n background-image: radial-gradient(blue 0 70%, transparent 70% 100%), linear-gradient(to left, transparent 0 50%, white 50% 100%);\n left: calc(100% + 1px);\n} <ol class=\"list\">\n <li class=\"listItem\">One</li>\n <li class=\"listItem\">Two</li>\n <li class=\"listItem\">Three</li>\n <li class=\"listItem\">Four</li>\n</ol>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9973558/" ]
74,485,330
<p>How to check if files present under a data lake directory are empty using Azure Data Factory?</p> <p>There are multiple files present in the data lake directory and I want to check if these files are empty or not, If files are empty then I want to store the filenames of these empty files in a CSV File.</p>
[ { "answer_id": 74485403, "author": "S M Samnoon Abrar", "author_id": 8188682, "author_profile": "https://Stackoverflow.com/users/8188682", "pm_score": 0, "selected": false, "text": "left: 150%; .listItem .list {\n list-style: none;\n padding-inline: 0;\n display: flex;\n width: 100%;\n justify-content: space-between;\n}\n\n.listItem {\n position: relative;\n padding: 1rem;\n border: 1px solid;\n}\n\n.listItem:not(:last-child):after {\n content: \"\";\n display: block;\n height: 4px;\n border-radius: 2px;\n background: blue;\n top: 50%;\n left: 150%;\n position: absolute;\n width: 100%;\n} <ol class=\"list\">\n <li class=\"listItem\">One</li>\n <li class=\"listItem\">Two</li>\n <li class=\"listItem\">Three</li>\n <li class=\"listItem\">Four</li>\n</ol>" }, { "answer_id": 74486069, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 2, "selected": true, "text": ".list {\n list-style: none;\n padding-inline: 0;\n display: flex;\n width: 100%;\n height: fit-content;\n justify-content: space-between;\n position: relative;\n}\n\n.list::before {\n content: '';\n position: absolute;\n width: 100%;\n height: 100%;\n z-index: -1;\n background-image: linear-gradient(white 0 calc(50% - 2px), blue calc(50% - 2px) calc(50% + 2px), white calc(50% + 2px) 100%);\n background-repeat: no-repeat;\n}\n\n.listItem {\n position: relative;\n padding: 1rem;\n border: 1px solid;\n background: white;\n box-sizing: border-box;\n}\n\n.listItem:not(:first-child)::before,\n.listItem:not(:last-child)::after {\n content: \"\";\n position: absolute;\n height: 4px;\n width: 4px;\n top: calc(50% - 2px);\n z-index: -1;\n}\n\n.listItem:not(:first-child)::before {\n background-image: radial-gradient(blue 0 70%, transparent 70% 100%), linear-gradient(to right, transparent 0 50%, white 50% 100%);\n right: calc(100% + 1px);\n}\n\n.listItem:not(:last-child)::after {\n background-image: radial-gradient(blue 0 70%, transparent 70% 100%), linear-gradient(to left, transparent 0 50%, white 50% 100%);\n left: calc(100% + 1px);\n} <ol class=\"list\">\n <li class=\"listItem\">One</li>\n <li class=\"listItem\">Two</li>\n <li class=\"listItem\">Three</li>\n <li class=\"listItem\">Four</li>\n</ol>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20054635/" ]
74,485,339
<p>How do we know which container data is present in boost variant? My variant is having any datatype or container. how to access the type of the data from the container?</p> <pre><code>boost::variant&lt;string, int&gt; myvar = 245; if(myvar.type() == typeid(int)){ std::cout&lt;&lt;&quot;integer data type&quot;&lt;&lt; '\n';//I am able to get the type of integer/string } boost::variant&lt;vector&lt;int&gt;, list&lt;string&gt;&gt; v {1,2,3,4};//??? </code></pre>
[ { "answer_id": 74487366, "author": "Klaus", "author_id": 878532, "author_profile": "https://Stackoverflow.com/users/878532", "pm_score": 0, "selected": false, "text": "boost::variant<vector<int>, list<string>> v {1,2,3,4};//??? boost::variant<std::vector<int>, std::list<std::string>> v=std::vector<int> {1,2,3,4};\n boost::variant std::variant using vartype = boost::variant<std::vector<int>, std::list<std::string>>;\nvoid access( vartype& v )\n{\n // this is a very ugly idea, because on every change of the types of your variant, the numbers for the switch are unvalid!\n switch( v.which() )\n { \n case 0: // first type of variant -> here it is vec<int>\n {\n auto& i = boost::get<std::vector<int>>( v ); \n for ( auto& el: i ) { std::cout << el << std::endl; }\n }\n break;\n\n case 1: // second type in variant -> here it is list<string>\n {\n auto& s = boost::get<std::list<std::string>>(v);\n for ( auto& el: s ) { std::cout << el << std::endl; }\n }\n break;\n\n default:\n ;\n } \n}\n\n// the visit method is much easier and better to maintain\nstruct MyVisitor: public boost::static_visitor<>\n{\n void operator()(std::vector<int>& i) { for ( auto& el: i ) { std::cout << el << std::endl; } }\n void operator()(std::list<std::string>& s) { for ( auto& el: s ) { std::cout << el << std::endl; } }\n};\n\n\nint main()\n{\n vartype vint = std::vector<int>{1,2,3,4};\n vartype vstring = std::list<std::string>{\"This\",\"is\",\"easy\"};\n\n access( vint );\n access( vstring );\n\n // or with visitor:\n MyVisitor vis;\n boost::apply_visitor( vis, vint );\n boost::apply_visitor( vis, vstring );\n\n // if you go with STL\n using stltype = std::variant< std::vector<int>, std::list<std::string>>;\n\n stltype si = std::vector<int>{ 5,4,3,2,1 };\n stltype ss = std::list<std::string>{\"That\",\"is\",\"easier\"};\n\n auto lambda = [](auto&& vec){ for ( auto& el: vec ) { std::cout << el << std::endl; }};\n\n std::visit( lambda, si );\n std::visit( lambda, ss );\n}\n" }, { "answer_id": 74489826, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 1, "selected": false, "text": "variant apply_visitor get<T> apply_visitor boost::static_visitor<T> T struct my_visitor : boost::static_visitor<size_t>\n{\n size_t operator()(std::vector<int> vec) const\n {\n for(int i : vec) std::cout << i << ',';\n return vec.size();\n }\n\n size_t operator()(std::list<std::string> list) const\n {\n for(std::string s : list) std::cout << s << ',';\n return list.size();\n }\n};\n size_t size = boost::apply_visitor(my_visitor(), v);\n struct my_visitor : boost::static_visitor<std::size_t>\n{\n template<typename Container>\n std::size_t operator()(Container cont) const\n {\n for(auto s : cont) std::cout << s << ',';\n return cont.size();\n }\n};\n size_t size = apply_visitor(\n [](auto cont){ \n for(auto s : cont) std::cout << s << ',';\n return cont.size();\n }, v\n);\n auto& vec = boost::get<std::vector<int>>(v);\n vec std::vector<int>& std::vector<int> boost::bad_get variant" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19494930/" ]
74,485,360
<p>In PHP, C# and may be other languages, why aren't languages developed to reduce writing code that isn't really necessary?</p> <p>Why for example foreach perform a loop on null array or list?</p> <p>I'm not a professional programmer, but I think this a common sense.</p> <p>Thank you.</p>
[ { "answer_id": 74485521, "author": "PMF", "author_id": 2905768, "author_profile": "https://Stackoverflow.com/users/2905768", "pm_score": 2, "selected": false, "text": "foreach List<string> myList = new List<string>();\n// ... fill list\nforeach(var s in myList)\n{\n // ...\n}\n IEnumerator it = myList.GetEnumerator();\n\nwhile (it.MoveNext())\n{\n string s = it.Current;\n // ...\n}\n myList myList" }, { "answer_id": 74485581, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 1, "selected": false, "text": "null \npublic static class EnumerableExtensionMethods\n{\n public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)\n {\n if (source is null)\n {\n return Enumerable.Empty<T>();\n }\n return source;\n }\n}\n List<string> nullList = null;\nforeach (var entry in nullList.EmptyIfNull())\n{\n // code here\n}\n foreach (var entry in nullList ?? Enumerable.Empty<string>())\n{\n // code here\n}\n foreach null" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7662223/" ]
74,485,362
<p>I have dates of this mixed type, I would like to standardize all of these to the format <code>yyyy-mm-dd</code> and for dates with just the month I would like to use the &quot;average&quot; of the month (e.g. the 15th). For example, <code>October 28, 2021</code> should become <code>2021/10/28</code> and <code>November 2009</code> should become <code>2009/11/15</code>. Also what should I do with the missing dates like with position 979?</p> <p>Here is a reproducible example-</p> <pre><code>[909] &quot;October 28, 2021&quot; &quot;April 7, 2014&quot; &quot;November 2009&quot; &quot;January 17, 2018&quot; [913] &quot;January 2023&quot; &quot;February 2012&quot; &quot;December 2022&quot; &quot;July 1999&quot; [917] &quot;November 2006&quot; &quot;June 2011&quot; &quot;July 2014&quot; &quot;January 2015&quot; [921] &quot;July 1, 2020&quot; &quot;October 15, 2018&quot; &quot;September 27, 2019&quot; &quot;February 14, 2022&quot; [925] &quot;June 28, 2021&quot; &quot;June 2016&quot; &quot;March 2013&quot; &quot;October 2014&quot; [929] &quot;January 2023&quot; &quot;July 6, 2022&quot; &quot;January 2014&quot; &quot;March 22, 2001&quot; [933] &quot;October 10, 2019&quot; &quot;May 1, 2008&quot; &quot;December 2008&quot; &quot;November 2023&quot; [937] &quot;August 2005&quot; &quot;May 1, 2022&quot; &quot;January 8, 2014&quot; &quot;July 2011&quot; [941] &quot;August 15, 2022&quot; &quot;May 2004&quot; &quot;November 2012&quot; &quot;October 1999&quot; [945] &quot;March 2010&quot; &quot;May 2014&quot; &quot;October 2006&quot; &quot;March 1, 2017&quot; [949] &quot;June 25, 2019&quot; &quot;October 2004&quot; &quot;September 2016&quot; &quot;June 10, 2019&quot; [953] &quot;April 4, 2017&quot; &quot;&quot; &quot;August 30, 2018&quot; &quot;July 1, 2017&quot; [957] &quot;November 14, 2019&quot; &quot;November 2006&quot; &quot;September 1, 2022&quot; &quot;April 2007&quot; [961] &quot;July 12, 2013&quot; &quot;August 14, 2015&quot; &quot;March 2013&quot; &quot;January 2014&quot; [965] &quot;March 2013&quot; &quot;June 27, 2019&quot; &quot;April 2008&quot; &quot;July 2007&quot; [969] &quot;February 2007&quot; &quot;May 2013&quot; &quot;April 2011&quot; &quot;December 2007&quot; [973] &quot;July 2007&quot; &quot;December 2008&quot; &quot;May 5, 2017&quot; &quot;December 2007&quot; [977] &quot;February 27, 2007&quot; &quot;February 13, 2018&quot; &quot;&quot; &quot;August 2014&quot; [981] &quot;September 9, 2019&quot; &quot;October 2010&quot; &quot;January 30, 2013&quot; &quot;January 2010&quot; [985] &quot;September 15, 2015&quot; &quot;March 2006&quot; &quot;April 2016&quot; &quot;March 2014&quot; [989] &quot;April 2010&quot; &quot;February 20, 2017&quot; &quot;October 2015&quot; &quot;March 2012&quot; [993] &quot;December 2014&quot; &quot;May 4, 2022&quot; &quot;October 27, 2020&quot; &quot;September 22, 2017&quot; [997] &quot;November 2009&quot; &quot;July 2003&quot; &quot;August 2006&quot; &quot;March 3, 2017&quot; </code></pre>
[ { "answer_id": 74485521, "author": "PMF", "author_id": 2905768, "author_profile": "https://Stackoverflow.com/users/2905768", "pm_score": 2, "selected": false, "text": "foreach List<string> myList = new List<string>();\n// ... fill list\nforeach(var s in myList)\n{\n // ...\n}\n IEnumerator it = myList.GetEnumerator();\n\nwhile (it.MoveNext())\n{\n string s = it.Current;\n // ...\n}\n myList myList" }, { "answer_id": 74485581, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 1, "selected": false, "text": "null \npublic static class EnumerableExtensionMethods\n{\n public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)\n {\n if (source is null)\n {\n return Enumerable.Empty<T>();\n }\n return source;\n }\n}\n List<string> nullList = null;\nforeach (var entry in nullList.EmptyIfNull())\n{\n // code here\n}\n foreach (var entry in nullList ?? Enumerable.Empty<string>())\n{\n // code here\n}\n foreach null" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14122775/" ]
74,485,364
<p>I can't understand the difference between the condition checked in a <code>for</code> loop and an <code>if</code> condition. Do both behave in a different way?</p> <p>When I write:</p> <pre><code>int num = 10; for(int i = 0; i &lt; 15 &amp;&amp; num; i++){ cout &lt;&lt; i &lt;&lt; &quot; &quot;; } </code></pre> <p>It only checks whether <code>i &lt; 15</code> and it doesn't check for <code>i &lt; num</code> and prints all the way from 0 to 14.</p> <p>But at the same time, if I write a <code>if</code> condition like:</p> <pre><code>if(x &lt; 15 &amp;&amp; num) </code></pre> <p>It checks for both <code>x &lt; 15</code> and <code>x &lt; num</code>.</p>
[ { "answer_id": 74485609, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": true, "text": "for while do..while if i < num x < num && for(int i = 0; i < 15 && num; i++) (i < 15) && (num != 0) (i < 15) && true (i < 15) (i < num) for(int i = 0; i < 15 && i < num; i++)\n for(int i = 0; i < min(15,num); i++)\n if(x < 15 && num) (x < 15) && (num != 0) (x < 15) && true (x < 15) (x < num) if(x < 15 && x < num)\n if(x < min(15,num))\n" }, { "answer_id": 74485610, "author": "n. m.", "author_id": 775806, "author_profile": "https://Stackoverflow.com/users/775806", "pm_score": 2, "selected": false, "text": "&& num num num == 12, x == 13 x < 15 x < num if (x < 15 and x < num)\n && if (x < 15 && x < num)\n && and" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536518/" ]
74,485,409
<p>The code is running nicely but I dont't understand where am I get this error.</p> <p>It says:</p> <pre><code>VM428:7 Uncaught TypeError: Cannot read properties of null (reading 'CodeMirror') at &lt;anonymous&gt;:7:17 </code></pre> <p>Any sort of help with this will be appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74485605, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 4, "selected": false, "text": "blackbox react development tool" }, { "answer_id": 74669602, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "CodeMirror null <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.56.0/codemirror.min.js\"></script>\n<script>\n // Your code that uses CodeMirror goes here\n // ...\n</script>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14710594/" ]
74,485,410
<p>I have a div inside reactstrap Modal, I want to call my function which grab's this div's attribute (after it has been rendered). I have tried <code>useEffect</code> on <code>modalShow</code>, I have tried useRef on that div, I have tried calling the function inside the div.</p> <pre><code>&lt;div custom-attribute=&quot;VALUE&quot; ref={modalRef} &gt; {handleModalLoad()} &lt;/div&gt; </code></pre> <p>But the problem is that my function i.e. <code>handleModalLoad()</code> gets executed before the modal is rendered therefore I am unable to grab the value from this attribute.</p>
[ { "answer_id": 74485605, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 4, "selected": false, "text": "blackbox react development tool" }, { "answer_id": 74669602, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "CodeMirror null <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.56.0/codemirror.min.js\"></script>\n<script>\n // Your code that uses CodeMirror goes here\n // ...\n</script>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7377486/" ]
74,485,427
<pre><code>[servername]# su postgres -c 'cd ~; psql -c &quot;SELECT * FROM pg_catalog.pg_user WHERE usename LIKE name;&quot;' ERROR: column &quot;name&quot; does not exist LINE 1: SELECT * FROM pg_catalog.pg_user WHERE usename LIKE name; ^ </code></pre> <p>Tried vary ways but no one of them return the correct response. May be there's a prettier way to do command-line queries?</p>
[ { "answer_id": 74485605, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 4, "selected": false, "text": "blackbox react development tool" }, { "answer_id": 74669602, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "CodeMirror null <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.56.0/codemirror.min.js\"></script>\n<script>\n // Your code that uses CodeMirror goes here\n // ...\n</script>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16933813/" ]
74,485,459
<p>I have two vectors, each containing names of columns in my data.frame, <code>data</code>, that is in wide form, e.g.</p> <pre><code>NSW_cols &lt;- c(&quot;NSW_1&quot;, &quot;NSW_2&quot;) # Columns for two variables from New South Wales AUS_cols &lt;- c(&quot;AUS_1&quot;, &quot;AUS_2&quot;) # Columns for two variables from Australia </code></pre> <pre><code>head(data) date NSW_1 AUS_1 NSW_2 AUS_2 1 2000-01-01 -0.38358623 -1.78824221 0.995984590 1.0744594 2 2001-01-01 -1.95910318 2.03124252 -1.695764903 0.2605978 3 2002-01-01 -0.84170506 -0.70314433 -0.533372143 -0.3142720 4 2003-01-01 1.90354747 0.15816476 -1.372269451 -0.7496301 5 2004-01-01 0.62249393 0.50623480 -2.207919779 -0.8621983 6 2005-01-01 1.99092044 -0.81999511 1.822122519 2.0480403 </code></pre> <p>I need to compute <code>share_i := NSW_i / AUS_i</code> (i.e. row-wise, or by <code>date</code>) for <code>i = 1,2</code>, while referencing my two name vectors above.</p> <p>For example, using <code>data.table</code>, I can do something like:</p> <pre><code>setDT(data) for (i in 1:2) { data[, paste0(&quot;share_&quot;, i) := get(NSW_cols[i]) / get(AUS_cols[i])] } </code></pre> <p>This seems silly for only a few columns, but in reality my application has several thousand columns. Moreover, in my actual application, I need to do more than simply divide one column by the other. Therefore, I am trying to find a solution that will work for any function accepting two numeric vectors as inputs.</p> <p>The data comes to me in a somewhat random form, so the convenient ordering of the columns in this example is also not something I can use.</p> <p><strong>Q: What is the best way to compute on many pairs of columns using vectors of names?</strong></p> <p>Suspicion: Maybe there is a <a href="https://stackoverflow.com/questions/72490154/compute-multiple-new-columns-by-name-pattern-in-r?rq=1">clever way</a> to do this by converting the data to long form? I haven't been able to make it work.</p> <hr /> <p>Example data:</p> <pre><code>structure(list(date = structure(c(10957, 11323, 11688, 12053, 12418, 12784, 13149, 13514, 13879, 14245, 14610, 14975, 15340, 15706, 16071, 16436, 16801, 17167, 17532, 17897), class = &quot;Date&quot;), NSW_1 = c(1.24119982707737, 0.138858419103515, 1.71063158823657, -0.430640974722993, -1.04422958092706, 0.537579524580529, -0.669585987150229, 0.638805611438309, -1.72398983449257, -1.74243008034091, 0.689804173282994, 0.330963177173467, 0.871067708948055, -2.01624558221344, 1.21257910351036, 1.20049469882194, 1.03206832593544, 0.786410256177216, 2.11007351377927, -1.45380984681329 ), AUS_1 = c(-0.58310384813065, 0.409723982550305, -0.806981635414238, 0.0855504408545073, 0.746243168639741, -0.653673061331084, 0.657105983301959, 0.549909235009709, -0.806729358432671, -0.997379717276235, 0.97589063842626, -0.169423180700716, 0.72219177943747, -0.844418606912503, 1.27729368500115, -1.34311054918022, 0.765340668860696, 0.464202569980373, 0.267993278040529, 0.667522687135242), NSW_2 = c(0.398467283863779, -0.638071030930068, -0.267712904023511, 0.359879564885712, -1.31286609394071, -0.883969609668706, 2.07709479458465, -2.09922563220098, -1.23850596532828, 0.990433089664036, 1.08866186319808, 0.839852254188259, 0.0568586386833875, 0.32387805118027, -0.904668667590953, -0.65218384837012, -0.262454637960949, -0.934662840905703, 0.821161212634175, -1.62425917345994), AUS_2 = c(-1.03040366948029, -1.261929311973, 0.39218462589648, -1.13143826165372, 0.544144484008162, 1.17660893473457, 0.0252285692390373, 0.515133169692034, -0.654109760017422, 0.503641990827566, -1.2721192223284, -0.0767711536986575, -1.34531937567941, -0.266317560246187, 1.08756299501947, 0.700567795415207, -0.4427595146404, -0.78851996588786, -0.856775709774438, -0.746419014623393)), class = &quot;data.frame&quot;, row.names = c(NA, -20L)) </code></pre>
[ { "answer_id": 74485754, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 2, "selected": true, "text": "lapply library(data.table)\nsetDT(data)\n\ni <- sub(\".*(\\\\d+$)\", \"\\\\1\", NSW_cols)\nshares <- paste(\"share\", i, sep = \"_\")\n\ndata[, (shares) := lapply(seq_along(NSW_cols), \\(i) get(NSW_cols[i])/get(AUS_cols[i]))]\nhead(data)\n#> date NSW_1 AUS_1 NSW_2 AUS_2 share_1 share_2\n#> 1: 2000-01-01 1.2411998 -0.58310385 0.39846728 -1.03040367 -2.1286085 -0.38670988\n#> 2: 2001-01-01 0.1388584 0.40972398 -0.63807103 -1.26192931 0.3389072 0.50563136\n#> 3: 2002-01-01 1.7106316 -0.80698164 -0.26771290 0.39218463 -2.1197900 -0.68261958\n#> 4: 2003-01-01 -0.4306410 0.08555044 0.35987956 -1.13143826 -5.0337669 -0.31807265\n#> 5: 2004-01-01 -1.0442296 0.74624317 -1.31286609 0.54414448 -1.3993154 -2.41271598\n#> 6: 2005-01-01 0.5375795 -0.65367306 -0.88396961 1.17660893 -0.8223982 -0.75128582\n" }, { "answer_id": 74490901, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "tidyverse library(dplyr)\nlibrary(purrr)\nlibrary(magrittr)\n\nmap_dfc(\n seq_along(NSW_cols),\n ~ {\n (data[[NSW_cols[.x]]] / data[[AUS_cols[.x]]]) %>%\n list() %>%\n set_names(paste0(\"share_\", .x))\n }\n) %>%\n bind_cols(data, .)\n library(dplyr)\nlibrary(purrr)\nlibrary(magrittr)\n\nmutate(\n data,\n map_dfc(\n seq_along(NSW_cols),\n ~ {\n (data[[NSW_cols[.x]]] / data[[AUS_cols[.x]]]) %>%\n list() %>%\n set_names(paste0(\"share_\", .x))\n }\n )\n)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10366237/" ]
74,485,465
<p>Why when I switch page using Get(()=&gt; Page2 of getX package, the app go back to default theme colors? I have a custom theme with yellow color, but then it goes back to the flutter blue default color. Am I missing something?</p> <p><strong>my code</strong></p> <pre><code>appBar: AppBar( title: Text('Profile'), actions: [ IconButton( icon: Icon(Icons.edit_note_outlined), onPressed: () { setState(() { /*isVisible= !isVisible; isReadOnly = !isReadOnly;*/ }); Get.to( AddNewProduct(), duration: Duration(milliseconds: 300), transition: Transition.fade ); }, ), ], ), </code></pre> <p><strong>my main</strong></p> <pre><code> Future&lt;void&gt; main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(GetMaterialApp( home: const MyApp(),) ); } </code></pre> <p><strong>my custom theme</strong></p> <pre><code>@override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter app', theme: ThemeData( primarySwatch: Colors.amber, buttonTheme: ButtonTheme.of(context).copyWith( textTheme: ButtonTextTheme.primary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0) ), ) ), home: const MyHomePage(title: 'Home'), ); } </code></pre> <p><a href="https://i.stack.imgur.com/zCzfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zCzfg.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/59RGF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/59RGF.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74486000, "author": "powerman23rus", "author_id": 6163011, "author_profile": "https://Stackoverflow.com/users/6163011", "pm_score": 2, "selected": true, "text": "main GetMaterialApp runApp(const MyApp(),);\n MaterialApp GetMaterialApp @override\nWidget build(BuildContext context) {\n return GetMaterialApp(\n title: 'Flutter app',\n theme: ThemeData(\n primarySwatch: Colors.amber,\n buttonTheme: ButtonTheme.of(context).copyWith(\n textTheme: ButtonTextTheme.primary,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(25.0)\n ),\n )\n ),\n home: const MyHomePage(),\n );\n }\n GetMaterialApp\n Builder (context1)\n MaterialApp <-- here you are setup your theme\n Scaffold\n AppBar\n Navigator.of(context1).push(MaterialPageRoute(builder: (_) => AddNewProduct()));\n body: ...\n runApp(GetMaterialApp(home: Builder(builder: (context) {\n return MaterialApp(\n title: 'Flutter app',\n theme: ThemeData(\n primarySwatch: Colors.amber,\n buttonTheme: ButtonTheme.of(context).copyWith(\n textTheme: ButtonTextTheme.primary,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(25.0)),\n )),\n home: const HomeWidget(),\n );\n })));\n class HomeWidget extends StatelessWidget {\n const HomeWidget({\n Key? key,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Profile'),\n actions: [\n IconButton(\n icon: Icon(Icons.edit_note_outlined),\n onPressed: () {\n Navigator.of(context)\n .push(MaterialPageRoute(builder: (_) => AddNewProduct()));\n },\n ),\n ],\n ),\n body: ... your content here...\n }\n}\n" }, { "answer_id": 74486508, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 1, "selected": false, "text": "MaterialApp GetMaterialApp GetMaterialApp GetMaterialApp MaterialApp Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n runApp(GetMaterialApp(\n title: 'Flutter app',\n theme: ThemeData(\n primarySwatch: Colors.amber,\n buttonTheme: ButtonTheme.of(context).copyWith(\n textTheme: ButtonTextTheme.primary,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(25.0)\n ),\n )\n ),\n home: const MyHomePage(title: 'Home'), );\n}\n\n MyApp MaterialApp MyApp GetMaterialApp runApp(const MyApp());\n" }, { "answer_id": 74487033, "author": "Dev", "author_id": 1834941, "author_profile": "https://Stackoverflow.com/users/1834941", "pm_score": 0, "selected": false, "text": " Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n runApp(GetMaterialApp(\n home: const MyApp(),)\n );\n}\n Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n runApp(GetMaterialApp(\ntheme: ThemeData(\n primarySwatch: Colors.amber,\n buttonTheme: ButtonTheme.of(context).copyWith(\n textTheme: ButtonTextTheme.primary,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(25.0)\n ),\n )\n ),\n home: const MyApp(),)\n );\n}\n *GetMaterialApp(* Scaffold" }, { "answer_id": 74488954, "author": "moxa patel", "author_id": 20498098, "author_profile": "https://Stackoverflow.com/users/20498098", "pm_score": 0, "selected": false, "text": "runApp(const MyApp(),);\n @override\nWidget build(BuildContext context) {\n return GetMaterialApp(\n title: 'Flutter app',\n theme: ThemeData(\n primarySwatch: Colors.amber,\n buttonTheme: ButtonTheme.of(context).copyWith(\n textTheme: ButtonTextTheme.primary,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(25.0)\n ),\n )\n ),\n home: const MyHomePage(),\n );\n }\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11069440/" ]
74,485,538
<p>I got 3 external images and a div, I need that when I place the mouse over any of the 3 images that image gets to be the backgroundImage of the div and when I mouse out of the div I need the div to get it's original background.</p> <p>My CodePen</p> <p><a href="https://i.stack.imgur.com/WUx1F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WUx1F.png" alt="enter image description here" /></a></p> <p>That's how far I could get but my code only shows the first of the three images and I know it's because of the index 0 but I just don't know how to solve it. Please guys help me out I beg you!</p>
[ { "answer_id": 74485576, "author": "Adan Ali", "author_id": 10810733, "author_profile": "https://Stackoverflow.com/users/10810733", "pm_score": -1, "selected": false, "text": ".div1:hover{\n background-image : 'url/path'\n}\n\n.div2:hover{\n background-image : 'url/path'\n}\n\n.div3:hover{\n background-image : 'url/path'\n}\n" }, { "answer_id": 74486285, "author": "DShadrin", "author_id": 6694219, "author_profile": "https://Stackoverflow.com/users/6694219", "pm_score": 0, "selected": false, "text": "let source = previewPic.getAttribute('src');\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536596/" ]
74,485,583
<p>I am trying to put a series of multiplications inside a list, I am using the code below:</p> <pre><code>listx = [] for i in range (2): list = [(3*i)] listx.append(list) </code></pre> <p>The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list.</p>
[ { "answer_id": 74485576, "author": "Adan Ali", "author_id": 10810733, "author_profile": "https://Stackoverflow.com/users/10810733", "pm_score": -1, "selected": false, "text": ".div1:hover{\n background-image : 'url/path'\n}\n\n.div2:hover{\n background-image : 'url/path'\n}\n\n.div3:hover{\n background-image : 'url/path'\n}\n" }, { "answer_id": 74486285, "author": "DShadrin", "author_id": 6694219, "author_profile": "https://Stackoverflow.com/users/6694219", "pm_score": 0, "selected": false, "text": "let source = previewPic.getAttribute('src');\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20050294/" ]
74,485,597
<p>So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the first one again?</p> <pre><code>while True: try: first = int(input(&quot;First: &quot;)) second = int(input(&quot;Second: &quot;)) sum = first + second print(f&quot;Sum: {sum}&quot;) break except ValueError: print(&quot;I didn't understand that&quot;) </code></pre> <p>I tried this but it just asked for the second variable then restarted the program</p> <pre><code>while True: try: first = int(input(&quot;First: &quot;)) second = int(input(&quot;Second: &quot;)) sum = first + second print(f&quot;Sum: {sum}&quot;) break except ValueError: print(&quot;I didn't understand that&quot;) int(input(&quot;Second: &quot;)) </code></pre>
[ { "answer_id": 74485630, "author": "thedemons", "author_id": 13253010, "author_profile": "https://Stackoverflow.com/users/13253010", "pm_score": 1, "selected": false, "text": "def GetNumberInput(text: str) -> int:\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n \n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n First: 123\nSecond: aaa\nI didn't understand that\nSecond: 456\nSum: 579\n" }, { "answer_id": 74485634, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 3, "selected": true, "text": "def get_input(prompt, cast_to=int):\n while True:\n try:\n return cast_to(input(prompt))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = get_input(\"First: \")\nsecond = get_input(\"Second: \")\nsum = first + second\nprint(f\"Sum {sum}\")\n" }, { "answer_id": 74485709, "author": "yum", "author_id": 12805063, "author_profile": "https://Stackoverflow.com/users/12805063", "pm_score": 1, "selected": false, "text": "try-except def take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n num = take_input(\"Input: \") def take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n return" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20513809/" ]
74,485,608
<p>I am creating an application where I need to have 3 heirarchy for email folders and notes like this: <a href="https://i.stack.imgur.com/vNFNE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vNFNE.png" alt="Diagram" /></a> Now I'm not able to get the list of documents under the <strong>folder</strong> collection.</p> <p>I have tried this till now:</p> <pre><code>var collection = FirebaseFirestore.instance .collection('user') .doc(widget.email) .collection('folder2'); await collection.get().then((snap) { data = snap.size; print(data); }); </code></pre> <p>But this is just giving me 0 in the console, but showing all the entries for the notes collection so what should I do?</p>
[ { "answer_id": 74485630, "author": "thedemons", "author_id": 13253010, "author_profile": "https://Stackoverflow.com/users/13253010", "pm_score": 1, "selected": false, "text": "def GetNumberInput(text: str) -> int:\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n \n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n First: 123\nSecond: aaa\nI didn't understand that\nSecond: 456\nSum: 579\n" }, { "answer_id": 74485634, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 3, "selected": true, "text": "def get_input(prompt, cast_to=int):\n while True:\n try:\n return cast_to(input(prompt))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = get_input(\"First: \")\nsecond = get_input(\"Second: \")\nsum = first + second\nprint(f\"Sum {sum}\")\n" }, { "answer_id": 74485709, "author": "yum", "author_id": 12805063, "author_profile": "https://Stackoverflow.com/users/12805063", "pm_score": 1, "selected": false, "text": "try-except def take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n num = take_input(\"Input: \") def take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n return" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16973338/" ]
74,485,619
<p>I have a dataframe of 1000 rows. Of which I have removed 20 rows. Now I want to reindex the df to (0-979) rows.</p> <p>in_val = list(range(30,50)) # no of rows dropped df.drop(in_val, inplace=True)</p> <p>The the df is with 980 rows, but the index is not 0-979. How can I do it?</p>
[ { "answer_id": 74485657, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "df.drop(in_val).reset_index(drop=True)\n" }, { "answer_id": 74485688, "author": "Python29", "author_id": 8725260, "author_profile": "https://Stackoverflow.com/users/8725260", "pm_score": 0, "selected": false, "text": "df.reset_index(inplace=True)" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15347574/" ]
74,485,654
<p>I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's. I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.</p> <p>The code I have been using for json object is</p> <pre><code> obj = parser.parse(new FileReader(&quot;path of json&quot;)); jsonObject = (JSONObject) obj; String jsonString = jsonObject.toJSONString(); Map&lt;String, String&gt; body = new ObjectMapper().readValue(jsonString, HashMap.class); response = RestAssuredExtension.PostOpsWithBody(url, body); </code></pre> <p>This code gives class cast exception at jsonObject = (JSONObject) obj; when I pass a json array.</p> <p>Kindly help me with the same This is the JSON Array</p> <pre><code>[ { &quot;findingId&quot;: &quot;20177044&quot;, &quot;unsupressAfterDuration&quot;: 1669968369043, &quot;developer&quot;: &quot;manan.girdhar@armorcode.io&quot;, &quot;kbIds&quot;: [], &quot;ticketConfigurationId&quot;: &quot;3350&quot;, &quot;customFields&quot;: [] } ] </code></pre>
[ { "answer_id": 74485965, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 1, "selected": false, "text": "obj = parser.parse(new FileReader(\"path of json\"));\nif (obj instanceof JSONObject) {\n jsonObject = (JSONObject) obj;\n String jsonString = jsonObject.toJSONString();\n Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);\n response = RestAssuredExtension.PostOpsWithBody(url, body);\n} else {\n throw new Exception(\"We do not know how to handle non-objects like \" + obj.getClass().getName());\n // replace this with list-handling code\n}\n" }, { "answer_id": 74488297, "author": "Manan Girdhar", "author_id": 19630533, "author_profile": "https://Stackoverflow.com/users/19630533", "pm_score": 0, "selected": false, "text": "JSONArray array1 = new JSONArray();\n data1.put(\"findingId\", findingIdFinal);\n data1.put(\"unsupressAfterDuration\", \"1669968369043\");\n data1.put(\"developer\",\"manan.girdhar@armorcode.io\");\n data1.put(\"kbIds\",array1);\n data1.put(\"ticketConfigurationId\", jiraId);\n data1.put(\"customFields\",array1);\n array.put(data1);\n String jsonString = array.toString();\n List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);\n response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630533/" ]
74,485,687
<p>After joined 2 tables and the results as following. I would like to remove some extra rows. <a href="https://i.stack.imgur.com/LmPHR.png" rel="nofollow noreferrer">enter image description here</a></p> <p>For example: Id a13b has status2 = Error and Success, I need to remove the row where ID = a13b and status2 = Success same as ID a15b and a16c from the table.</p> <p>This is the result I am looking for and would like to know what's the correct query to get this result. <a href="https://i.stack.imgur.com/JBJt5.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Thank you in advance!</p>
[ { "answer_id": 74485852, "author": "Motif", "author_id": 19424533, "author_profile": "https://Stackoverflow.com/users/19424533", "pm_score": 1, "selected": false, "text": "SELECT ... FROM \n....\nWHERE (ID NOT IN ('a13b', 'a15b', 'a16c') AND (status2 LIKE 'Success'))\nAND (ID NOT IN 'a13b' AND Status2 IN ('Error','Success'))\n" }, { "answer_id": 74486178, "author": "Manuel1234", "author_id": 16974715, "author_profile": "https://Stackoverflow.com/users/16974715", "pm_score": 1, "selected": true, "text": "\n select * from dbo.table1 t1 \n inner join dbo.table2 t2 \n on t1.id = t2.Id2 \n and t1.id not in \n (\n select id2 \n \n from dbo.table1 t1 \n inner join dbo.table2 t2 \n on t1.id = t2.Id2 \n and status2 ='error'\n ) \n\n union\n\n select * from dbo.table1 t1 \n inner join dbo.table2 t2 \n on t1.id = t2.Id2 \n and t2.status2 = 'error'; \n\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532168/" ]
74,485,692
<p>I need to simplify two lists using LINQ keeping their index and removing pairs that might have a null/empty partner. Or if I could combine them into a dictionary of key-value pairs (int and decimal) that will also be great.</p> <pre><code>list1=[&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;] list2=[&quot;20.20&quot;,&quot;&quot;,&quot;&quot;,50.0,&quot;&quot;] </code></pre> <p>to</p> <pre><code>list1=[&quot;1&quot;,&quot;5&quot;] list2=[&quot;20.20&quot;,&quot;50.0&quot;] </code></pre> <p>I get the lists from a form collection of paymentcategory and amounts. The categories and amounts are dynamically generated.</p>
[ { "answer_id": 74485810, "author": "Kiran Joshi", "author_id": 9760311, "author_profile": "https://Stackoverflow.com/users/9760311", "pm_score": 2, "selected": false, "text": " var data = new Dictionary<int, decimal>()\n if(lis1.Count==list2.Count)\n {\n for (var i = 0; i < list1.Length; i++)\n {\n if (!string.IsNullOrEmpty(list1[i])&&!string.IsNullOrEmpty(list2[i]))\n data.Add(Convert.ToInt32(list1[i]),Convert.ToDecimal(list2[i]));\n }\n }\n data Dictionary int decimal IndexOutOfRange" }, { "answer_id": 74485905, "author": "Yong Shun", "author_id": 8017690, "author_profile": "https://Stackoverflow.com/users/8017690", "pm_score": 3, "selected": true, "text": "Enumerable.Zip() using System.Linq;\n\nvar combineList = list1.Zip(list2, \n (a, b) => new { a = a?.ToString(), b = b?.ToString() })\n .Where(x => !String.IsNullOrEmpty(x.a)\n && !String.IsNullOrEmpty(x.b))\n .ToList();\n \nlist1 = combineList.Select(x => x.a).ToList();\nlist2 = combineList.Select(x => (object)x.b).ToList();\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066567/" ]
74,485,726
<p>I have created a API in WSO2 studio integrator like below:</p> <p>curl --location --request POST 'http://localhost:8290/internal/send-messages' <br /> --header 'accept: text/plain' <br /> --header 'Content-Type: application/json' <br /> --data-raw '{ &quot;bankName&quot;: &quot;heere&quot;, &quot;uniqueIdentifier&quot;: &quot;445334564&quot; }'</p> <p>To pass the requests (which received from this API) toward the endpoint, I need to add two following parameters into API Header</p> <p>--header 'MasterName: TOMSON' <br /> --header 'clientName: TOM' \</p> <p>TOMSON value is unique(static) and would NOT change for any user. However TOM would be change based on application username given from API Manager (there is OATH2 authentication).</p> <ol> <li><p>How can I add a static header (Like MasterName) to a API while sending toward the endpoint</p> </li> <li><p>How can I understand the username of application ??</p> </li> </ol>
[ { "answer_id": 74486012, "author": "usuario", "author_id": 7502800, "author_profile": "https://Stackoverflow.com/users/7502800", "pm_score": 0, "selected": false, "text": "<header name=\"miCustomHeader\" value=\"ThisIsTheWay\" scope=\"transport\"/>\n\n<send>\n <endpoint>\n <address uri=\"https://someRandomURL\"/>\n </endpoint>\n</send>\n" }, { "answer_id": 74486553, "author": "Lakshitha", "author_id": 11414612, "author_profile": "https://Stackoverflow.com/users/11414612", "pm_score": 1, "selected": false, "text": "<header name=\"MasterName\" value=\"TOMSON\" scope=\"transport\"/> http://wso2.org/claims/applicationname" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20135571/" ]
74,485,735
<p>I have a set of files with similar naming pattern. I am trying to get the total row count of all the files combined sans the header in a go. But I am having trouble with the commands.</p> <p>I have tried:</p> <p><code>sed '1d' IN-Pass-30* | wc -l</code></p> <p>and</p> <p><code>awk 'END {print NR-1}' IN-Pass-30*</code></p> <p>But each time it only subtracts the header count from just one file. What am I doing wrong here?</p>
[ { "answer_id": 74486405, "author": "Dominique", "author_id": 4279155, "author_profile": "https://Stackoverflow.com/users/4279155", "pm_score": 1, "selected": false, "text": "Prompt> find ./ -maxdepth 1 -name \"IN-Pass-30*\" | wc -l\n53\nPrompt> cat IN-Pass-30* | wc -l\n1418549\nPrompt> echo $(($(cat IN-Pass-30* | wc -l) - $(find ./ -maxdepth 1 -name \"IN-Pass-30*\" | wc -l)))\n1418496\n Prompt> find ./ -maxdepth 1 -name \"IN-Pass-30*\" | wc -l\n// find all files inside that directory without checking subdirectories.\n// once they are found, count them.\n\nPrompt> cat IN-Pass-30* | wc -l\n// use `cat` to concatenate all files' content.\n// at the end, count the amount of lines.\n\nPrompt> echo $$(a - b))\n// calculate the difference between a and b.\n\nPrompt> echo $(command)\n// show (or do whatever with it) the result of a command\n" }, { "answer_id": 74490973, "author": "Cole Tierney", "author_id": 2820422, "author_profile": "https://Stackoverflow.com/users/2820422", "pm_score": 3, "selected": true, "text": "for f in IN-Pass-30*; do sed '1d' \"$f\"; done | wc -l\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15260613/" ]
74,485,774
<p>I am creating a customer model for my API and I've set my 'Name' and 'Email' fields as required. But when we leave those fields empty while creating a new customer, we got a built-in error from EF core , instead I want to show my own error message...how can I do that.</p> <p>I've tried to add validations by code in my post method but It doesn't work...can anyone help me with that?...Thanks in advance</p>
[ { "answer_id": 74485925, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 0, "selected": false, "text": " public class Movie\n{\n public int ID { get; set; }\n\n [Required(ErrorMessage = \"Name is required\")]\n public string Name{ get; set; }\n}\n var builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddControllers(options =>\n{\n options.ModelMetadataDetailsProviders.Add(new NewtonsoftJsonValidationMetadataProvider());\n}).AddNewtonsoftJson();\n" }, { "answer_id": 74487062, "author": "Binnaz Cabuk", "author_id": 11232255, "author_profile": "https://Stackoverflow.com/users/11232255", "pm_score": 1, "selected": false, "text": "public class UserRegisterValidator : AbstractValidator<User>\n{\n public UserRegisterValidator()\n {\n RuleFor(r => r.email).NotEmpty().WithMessage(\"Email address cannot be empty.\");\n .\n .\n .\n }\n}\n UserRegisterValidator v = new UserRegisterValidator();\nValidationResult result = v.Validate(usr);\n\nif (!result.IsValid) return StatusCode(StatusCodes.Status400BadRequest, result.Errors); //Returns the specified error message\nif (result.IsValid)\n{\n //If there is no error, the necessary actions are here\n}\n \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536829/" ]
74,485,777
<p>I am looking to avoid multiple <code>if-else</code> conditions. Is there a more concise way of writing the below code?</p> <pre><code>private Set&lt;String&gt; getValues(Optional&lt;String&gt; one, Optional&lt;String&gt; two) { if (one.isPresent() &amp;&amp; two.isPresent()) { return ImmutableSet.of(one.get(), two.get()); } else if (one.isPresent()) { return ImmutableSet.of(one.get()); } else { return two.isPresent() ? ImmutableSet.of(two.get()) : ImmutableSet.of(); } } </code></pre>
[ { "answer_id": 74485888, "author": "Beri", "author_id": 4086177, "author_profile": "https://Stackoverflow.com/users/4086177", "pm_score": 4, "selected": true, "text": " private Set<String> getValuesJdk9(Optional<String> one, Optional<String> two) {\n return Stream.concat(one.stream(), two.stream())\n .collect(Collectors.toUnmodifiableSet());\n }\n private Set<String> getValuesJdk8(Optional<String> one, Optional<String> two) {\n return Stream.of(one, two)\n .filter(Optional::isPresent)\n .map(Optional::get)\n .collect(Collectors.toUnmodifiableSet());\n }\n private Set<String> getAllValues(Optional<String>... options) {\n return Arrays.stream(options).flatMap(Optional::stream)\n .collect(Collectors.toUnmodifiableSet());\n }\n" }, { "answer_id": 74505508, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "Collectors.toSet() Set HashSet Set ImmutableSet Collector ImmutableSet.toImmutableSet() Optional Optional Optional Optional Supplier Optional foo() bar() Optional getValues(Supplier<Optional<T>> first, Supplier<Optional<T>> second)\n getValues(x::foo, y::bar) ImmutableSet.toImmutableSet() 21.0 Collector ImmutableSet.toImmutableSet() @SafeVarargs\nprivate static <T> Set<T> getValues(Supplier<Optional<T>>... suppliers) {\n\n return Arrays.stream(suppliers)\n .map(Supplier::get)\n .filter(Optional::isPresent)\n .map(Optional::get)\n .collect(ImmutableSet.toImmutableSet());\n}\n toUnmodifiableSet() @SafeVarargs\nprivate static <T> Set<T> getValues(Supplier<Optional<T>>... suppliers) {\n\n return Arrays.stream(suppliers)\n .map(Supplier::get)\n .filter(Optional::isPresent)\n .map(Optional::get)\n .collect(Collectors.toUnmodifiableSet());\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042646/" ]
74,485,779
<p>I'm trying to create a button like this:<br /> <a href="https://i.stack.imgur.com/2CsYM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2CsYM.png" alt="enter image description here" /></a><br /> This needs to be done in pure css.</p> <p>I tried to do, nothing happened, it does not work correctly:</p> <pre><code>display: inline-block; width: 165px; text-align: center; color: #fff; background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%); border-radius: 5px; border: 1px solid #ffffff; font-family: Arial; font-weight: normal; border-left: 2px solid #e5ccaf; border-image: linear-gradient(to bottom, #ffd400,rgba(0, 0, 0, 0)) 0 100%; border-top: 1px solid #ffd400; </code></pre> <p><img src="https://i.stack.imgur.com/nhY8Q.png" alt="enter image description here](https://i.stack.imgur.com/nhY8Q.png)" /> <br /> How can I do that?!</p>
[ { "answer_id": 74485825, "author": "S M Samnoon Abrar", "author_id": 8188682, "author_profile": "https://Stackoverflow.com/users/8188682", "pm_score": 2, "selected": false, "text": "text-decoration: none; .pure_css_button {\n display: inline-block;\n width: 165px;\n text-align: center;\n color: #fff;\n text-decoration: none;\n background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);\n border-radius: 5px;\n border: 1px solid #ffffff;\n font-family: Arial;\n font-weight: normal;\n border-left: 2px solid #e5ccaf;\n border-image: linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) 0 100%;\n border-top: 1px solid #ffd400;\n} <a href=\"#\" class=\"pure_css_button\">\nButton</a>" }, { "answer_id": 74486181, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 2, "selected": true, "text": "button {\n cursor: pointer;\n font-size: x-large;\n padding: 0.6rem 2rem;\n font-weight: bold;\n overflow: hidden;\n color: #fff;\n background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);\n border:0;\n border-radius: .3rem;\n position: relative;\n border-top: 2px solid hsl(24, 49%, 15%);\n border-bottom: 2px solid hsl(24, 49%, 15%);\n }\n button::after,button::before{\n content: '';\n height: 100%;\n width: .15rem;\n position: absolute;\n top:0;\n background:linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) ;\n }\n button::before{\n left: 0;\n }\n button::after{\n right: 0;\n } <button>\n Pure Css</button>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20025013/" ]
74,485,791
<p><a href="https://i.stack.imgur.com/pLi7T.png" rel="nofollow noreferrer">Problem Statement</a></p> <p>Edit: I have transcribed the image as suggested although I think some terms are better shown in the picture if anything is unclear here;</p> <p>This function takes in a positive integer n and returns the sum of the following series Sn, as long as the absolute value of each term is larger than stop.</p> <blockquote> <p>Sn= 1 − 1/2 + 1/3 − 1/4 + ... + (−1)<sup>n+1</sup>/n + ...</p> </blockquote> <p>You can assume that stop is a float value and 0 &lt; stop &lt; 1.</p> <p>You need not round the output.</p> <p>For example, if stop = 0.249, then Sn is evaluated with only four terms.</p> <blockquote> <p>Sn = 1 − 1/2 + 1/3 − 1/4</p> </blockquote> <p>For example, if stop = 0.199, then Sn is evaluated with only five terms.</p> <blockquote> <p>Sn = 1 − 1/2 + 1/3 − 1/4 + 1/5</p> </blockquote> <p>The built-in function abs() is useful. You should use a while loop.</p> <p>Test cases:</p> <pre><code>print( alternating_while(0.249) ) print( alternating_while(0.199) ) </code></pre> <p>gives:</p> <pre class="lang-none prettyprint-override"><code>0.5833333333333333 0.7833333333333332 </code></pre> <p>Now for this question, I want to get the sum of this series based on the conditions stipulated in the question.</p> <p>My problem is I don't understand how to type the formula given in the question because I'm not familiar with how the while-loop works. Can someone instruct me on how to?</p> <pre><code>def alternating_while(stop): total = 0 n = 1 term = 1 while abs(term) &gt; stop: total= (-1) ** (n + 1) / n + alternating_while(n - 1) return total </code></pre>
[ { "answer_id": 74485825, "author": "S M Samnoon Abrar", "author_id": 8188682, "author_profile": "https://Stackoverflow.com/users/8188682", "pm_score": 2, "selected": false, "text": "text-decoration: none; .pure_css_button {\n display: inline-block;\n width: 165px;\n text-align: center;\n color: #fff;\n text-decoration: none;\n background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);\n border-radius: 5px;\n border: 1px solid #ffffff;\n font-family: Arial;\n font-weight: normal;\n border-left: 2px solid #e5ccaf;\n border-image: linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) 0 100%;\n border-top: 1px solid #ffd400;\n} <a href=\"#\" class=\"pure_css_button\">\nButton</a>" }, { "answer_id": 74486181, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 2, "selected": true, "text": "button {\n cursor: pointer;\n font-size: x-large;\n padding: 0.6rem 2rem;\n font-weight: bold;\n overflow: hidden;\n color: #fff;\n background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);\n border:0;\n border-radius: .3rem;\n position: relative;\n border-top: 2px solid hsl(24, 49%, 15%);\n border-bottom: 2px solid hsl(24, 49%, 15%);\n }\n button::after,button::before{\n content: '';\n height: 100%;\n width: .15rem;\n position: absolute;\n top:0;\n background:linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) ;\n }\n button::before{\n left: 0;\n }\n button::after{\n right: 0;\n } <button>\n Pure Css</button>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20530453/" ]
74,485,803
<p>I need to detect if the axios request (with async/await) is in loading phase. Because, I need to disable a button if the request is loading.</p> <p>So, this is the line of code:</p> <pre><code>const response = await API.get(&quot;/url&quot;, options); </code></pre> <p>Now, I need to disable a certain button if this request is in loading phase. But, I'm stuck on how to solve this issue.</p>
[ { "answer_id": 74485822, "author": "Mohammed Shahed", "author_id": 19067773, "author_profile": "https://Stackoverflow.com/users/19067773", "pm_score": 3, "selected": true, "text": "setState(true) //to initiate loading\nconst response = await API.get(\"/url\", options);\nsetState(false) //to turn off loading\n try{\nsetState(true) //to initiate loading\nconst response = await API.get(\"/url\", options);\n}\ncatch(err){}\nfinally{\nsetState(false) //to turn off loading\n}\n" }, { "answer_id": 74485932, "author": "monim", "author_id": 16632344, "author_profile": "https://Stackoverflow.com/users/16632344", "pm_score": 1, "selected": false, "text": "isLoading false const [isloading, setIsloading] = useState(false);\n const fetchingData = async () => {\n try {\n setIsloading(true); // Set loading before sending API request\n const response = await API.get(\"/url\", options);\n ....\n setIsloading(false); // Stop loading\n } catch (error) {\n setIsloading(false); // Stop loading in case of error\n console.error(error);\n }\n}\n <button disabled={isloading ? true : false}> button disabled while fetching data</button>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19987252/" ]
74,485,856
<p>So far the in my html file I have a canvas and a div tag. The div tag contains four paragraph tags which I'm trying to set at the top of the screen, in the middle, and inline. The problem arises when I set them inline and try to add some padding to it. The the third paragraph suddenly just drops to under the first paragraph. Heres the css and html right now.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { width: 100%; height: 100%; border: 1px solid azure; } canvas { display: block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; user-select: none; background-color:rgb(33, 96, 33); border: 1px solid azure; } div { position: absolute; font-size: 130%; color:azure; } p { transition: opacity 0.3s ease-in-out; color:azure; border: 1px solid azure; display: inline; padding-right: 10%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas1"&gt;&lt;/canvas&gt; &lt;div id="Events"&gt; &lt;p id="clicks"&gt;Clicks:&lt;/p&gt; &lt;p id="dbClicks"&gt;Double Clicks:&lt;/p&gt; &lt;p id="mouseLeft"&gt;Mouse Left:&lt;/p&gt; &lt;p id="keyPress"&gt;Key Presses:&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I tried getting rid of all the margin and padding so I did</p> <p>margin: 0; padding: 0;</p>
[ { "answer_id": 74485913, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 0, "selected": false, "text": "body {\nwidth: 100%;\nheight: 100%;\nborder: 1px solid azure;\n}\n\ncanvas {\ndisplay: block;\nposition: absolute;\ntop: 0;\nleft: 0;\nright: 0;\nbottom: 0;\nwidth: 100%;\nheight: 100%;\nuser-select: none;\n\nborder: 1px solid azure;\n} <canvas id=\"canvas1\"></canvas>\n<div id=\"Events\" style=\"text-align: center;\">\n <p id=\"clicks\">Clicks:</p>\n <p id=\"dbClicks\">Double Clicks:</p>\n <p id=\"mouseLeft\">Mouse Left:</p>\n <p id=\"keyPress\">Key Presses:</p>\n</div>" }, { "answer_id": 74486011, "author": "pierpy", "author_id": 7353417, "author_profile": "https://Stackoverflow.com/users/7353417", "pm_score": 0, "selected": false, "text": "canvas {\ndisplay: flex;\njustify-content: center; \n div { position: relative; [...] }" }, { "answer_id": 74486088, "author": "George Chond", "author_id": 17730652, "author_profile": "https://Stackoverflow.com/users/17730652", "pm_score": 0, "selected": false, "text": "display:inline-block; display:inline; margin:0; <p> <p> width:100%; .div body {\n width: 100%;\n height: 100%;\n border: 1px solid azure;\n}\n\ncanvas {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n user-select: none;\n background-color:rgb(33, 96, 33);\n border: 1px solid azure;\n}\n\ndiv {\n position: absolute;\n font-size: 130%;\n color:azure;\n}\n\np {\n transition: opacity 0.3s ease-in-out;\n color:azure;\n border: 1px solid azure;\n display: inline-block;\n margin: 0;\n padding-right: 10%;\n} <canvas id=\"canvas1\"></canvas>\n<div id=\"Events\">\n <p id=\"clicks\">Clicks:</p>\n <p id=\"dbClicks\">Double Clicks:</p>\n <p id=\"mouseLeft\">Mouse Left:</p>\n <p id=\"keyPress\">Key Presses:</p>\n</div>" }, { "answer_id": 74486251, "author": "John", "author_id": 11111119, "author_profile": "https://Stackoverflow.com/users/11111119", "pm_score": 0, "selected": false, "text": "Events events body {\n width: 100%;\n height: 100%;\n border: 1px solid azure;\n}\n\ncanvas {\n width: 100%;\n height: 100%;\n user-select: none;\n background-color:rgb(33, 96, 33);\n border: 1px solid azure;\n}\n\n#Events{\n position: absolute;\n font-size: 130%;\n color:azure;\n width: 100%;\n top: 0;\n}\n\np {\n transition: opacity 0.3s ease-in-out;\n color:azure;\n border: 1px solid azure;\n display: inline-block;\n padding-right: 10%;\n}\n\n#container {\n position: relative;\ntext-align: center;\n} <div id=\"container\">\n<canvas id=\"canvas1\"></canvas>\n<div id=\"Events\">\n <p id=\"clicks\">Clicks:</p>\n <p id=\"dbClicks\">Double Clicks:</p>\n <p id=\"mouseLeft\">Mouse Left:</p>\n <p id=\"keyPress\">Key Presses:</p>\n</div>\n</div> div p body {\n width: 100%;\n height: 100%;\n border: 1px solid azure;\n}\n\ncanvas {\n width: 100%;\n height: 100%;\n user-select: none;\n background-color:rgb(33, 96, 33);\n border: 1px solid azure;\n}\n\n#Events{\n position: absolute;\n font-size: 130%;\n color:azure;\n width: 100%;\n top: 0;\n}\n\n#Events div{\n transition: opacity 0.3s ease-in-out;\n color:azure;\n border: 1px solid azure;\n display: inline-block;\n padding-right: 10%;\n word-wrap: none;\n \n}\n\n#container {\n position: relative;\ntext-align: center;\n} <div id=\"container\">\n<canvas id=\"canvas1\"></canvas>\n<div id=\"Events\">\n <div id=\"clicks\">Clicks:</div>\n <div id=\"dbClicks\">Double Clicks:</div>\n <div id=\"mouseLeft\">Mouse Left:</div>\n <div id=\"keyPress\">Key Presses:</div>\n</div>\n</div>" }, { "answer_id": 74486318, "author": "Shreyansh Gupta", "author_id": 18046485, "author_profile": "https://Stackoverflow.com/users/18046485", "pm_score": 0, "selected": false, "text": "body {\n width: 100%;\n height: 100%;\n border: 1px solid azure;\n}\n\ncanvas {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n user-select: none;\n background-color:rgb(33, 96, 33);\n border: 1px solid azure;\n}\n\ndiv {\n position: absolute;\n font-size: 130%;\n color:azure;\n width:100%;\n}\n\np {\n transition: opacity 0.3s ease-in-out;\n color:azure;\n border: 1px solid azure;\n display: inline-block;\n padding-right: 10%;\n} <canvas id=\"canvas1\"></canvas>\n<div id=\"Events\">\n <p id=\"clicks\">Clicks:</p>\n <p id=\"dbClicks\">Double Clicks:</p>\n <p id=\"mouseLeft\">Mouse Left:</p>\n <p id=\"keyPress\">Key Presses:</p>\n</div>" }, { "answer_id": 74486603, "author": "butayarou", "author_id": 5917834, "author_profile": "https://Stackoverflow.com/users/5917834", "pm_score": 2, "selected": true, "text": "<p> display: inline-block; width: 100vw; body {\n width: 100%;\n height: 100%;\n border: 1px solid azure;\n }\n\n canvas {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n user-select: none;\n background-color: rgb(33, 96, 33);\n border: 1px solid azure;\n }\n\n div {\n position: absolute;\n font-size: 130%;\n color: azure;\n width: 100vw;\n }\n\n p {\n transition: opacity 0.3s ease-in-out;\n color: azure;\n border: 1px solid azure;\n display: inline-block;\n padding-right: 10%;\n } <canvas id=\"canvas1\"></canvas>\n<div id=\"Events\">\n <p id=\"clicks\">Clicks:</p>\n <p id=\"dbClicks\">Double Clicks:</p>\n <p id=\"mouseLeft\">Mouse Left:</p>\n <p id=\"keyPress\">Key Presses:</p>\n</div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536941/" ]
74,485,862
<p>** I AM NEW TO PYTHON **</p> <p>I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper().</p> <p>Example Outputs:</p> <blockquote> <p>1st String: lol</p> <p>2nd String: Hilol</p> <p>True</p> </blockquote> <blockquote> <p>1st String: IDK</p> <p>2nd String: whatidk</p> <p>True</p> </blockquote> <p>My code:</p> <pre><code>a1 = str(input(&quot;first string: &quot;)) a2 = str(input(&quot;second string: &quot;)) if a2 in a1: print(True) else: print(False) </code></pre> <p>It outputs:</p> <blockquote> <p>1st String: lol</p> <p>2nd String: lol</p> <p>True</p> </blockquote> <blockquote> <p>1st String: lol</p> <p>2nd String: HIlol</p> <p>False #This should be true, IDK why it is false.</p> </blockquote> <p>I only came this far with my code (I KNOW IT LACKS A LOT FROM THE INSTRUCTION). Hoping someone could teach me what to do. Thank you!</p> <p>EDIT: I FOUND OUT THAT, MY CODE SHOULD HAVE BEEN:</p> <pre><code>a1 = str(input(&quot;Enter the first string: &quot;)) a2 = str(input(&quot;Enter the second string: &quot;)) if a1 in a2: print(True) else: print(False) </code></pre> <p>But now, how do I make it not case sensitive?</p>
[ { "answer_id": 74485981, "author": "Nineteendo", "author_id": 13454049, "author_profile": "https://Stackoverflow.com/users/13454049", "pm_score": 2, "selected": true, "text": "string_1 = input(\"first string: \")\nstring_2 = input(\"second string: \")\n\nif string_1.lower() in string_2.lower(): \n print(True)\nelse:\n print(False)\n def check_occuring(substring, string):\n if substring.lower() in string.lower(): \n return True\n else:\n return False\n\nstring_1 = input(\"first string: \")\nstring_2 = input(\"second string: \")\nprint(check_occuring(string_1, string_2)) \n substring.lower() in string.lower()" }, { "answer_id": 74485988, "author": "Hellow2", "author_id": 16804841, "author_profile": "https://Stackoverflow.com/users/16804841", "pm_score": 0, "selected": false, "text": "substring = input(\"substring: \").lower()\ntext = input(\"text: \").lower()\n in >>> \"lol\" in \"HIlol\"\nTrue\n substring = input(\"substring: \").lower()\ntext = input(\"text: \").lower()\n\nprint(substring in text)\n <str> in <str>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20066675/" ]
74,485,866
<p>Recently, I try to migrate to Jetpack compose.</p> <p>So, I want to show 'card' where has 'indicator' while loading but I can't change 'indicator' size in 'SubcomposeAsyncImage'</p> <pre><code>@Composable private fun SponsorDialogContent( imgUrl: String, ) { Card( modifier = Modifier .width(300.dp) .wrapContentHeight(), elevation = CardDefaults.cardElevation(0.dp), shape = RoundedCornerShape(10.dp) ) { Box() { SubcomposeAsyncImage( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .heightIn(min = 200.dp), model = imgUrl, contentDescription = null, loading = { CircularProgressIndicator(modifier = Modifier.size(30.dp).align(Alignment.Center), progress = 1f) }, alignment = Alignment.Center, contentScale = ContentScale.FillWidth ) CircularProgressIndicator(1f, Modifier.width(30.dp).align(Alignment.Center)) } } } </code></pre> <p>So. I have try the code below</p> <pre><code>@Composable private fun SponsorDialogContent( imgUrl: String, ) { Card( modifier = Modifier .width(300.dp) .wrapContentHeight(), elevation = CardDefaults.cardElevation(0.dp), shape = RoundedCornerShape(10.dp) ) { Box() { SubcomposeAsyncImage( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .heightIn(min = 200.dp), model = imgUrl, contentDescription = null, loading = { Box(contentAlignment = Alignment.Center) { CircularProgressIndicator() } }, alignment = Alignment.Center, contentScale = ContentScale.FillWidth ) } } } </code></pre> <p>Then, works well, but I don't know why Does anyone know why?</p> <p>I tried to find how to work this code but failed</p> <p><a href="https://i.stack.imgur.com/jLQJy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jLQJy.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74487846, "author": "Jan Bína", "author_id": 2801938, "author_profile": "https://Stackoverflow.com/users/2801938", "pm_score": 2, "selected": false, "text": "SubcomposeAsyncImage BoxWithConstraints(\n modifier = modifier, // this is the modifier you passed to SubcomposeAsyncImage\n contentAlignment = alignment,\n propagateMinConstraints = true,\n) {\n // image or your loading content based on state\n}\n heightIn(min = 200.dp) Box propagateMinConstraints = true" }, { "answer_id": 74491759, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 3, "selected": true, "text": "propagateMinConstraints = true propagateMinConstraints = true Surface(\n modifier = Modifier.size(200.dp),\n onClick = {}) {\n Column(\n modifier = Modifier\n .size(50.dp)\n .background(Color.Red, RoundedCornerShape(6.dp))\n ) {}\n}\n\nSpacer(modifier = Modifier.height(20.dp))\n\nSurface(\n modifier = Modifier.size(200.dp),\n onClick = {}) {\n Column(\n modifier = Modifier\n .size(50.dp)\n .background(Color.Red, RoundedCornerShape(6.dp))\n ) {\n Column(\n modifier = Modifier\n .size(50.dp)\n .background(Color.Green, RoundedCornerShape(6.dp))\n ) {}\n\n }\n}\n\nSpacer(modifier = Modifier.height(20.dp))\n\nBox(\n modifier = Modifier.size(200.dp)\n) {\n Column(\n modifier = Modifier\n .size(50.dp)\n .background(Color.Red, RoundedCornerShape(6.dp))\n ) {\n Column(\n modifier = Modifier\n .size(50.dp)\n .background(Color.Green, RoundedCornerShape(6.dp))\n ) {}\n\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19082714/" ]
74,485,875
<p>instead of using <code>try and catch</code>, there is any other solution for these <strong>sytnx</strong></p> <pre><code>const { person, children, total } = response.data // what i looking for </code></pre> <p>in case the person response is null , so i got an error <strong>cannot read properties null</strong>. in other case i only know using <strong>elvis operator</strong> <em>data?.data</em>. thats mean <code>response.data?.person</code> but i want the above code works with <strong>null safety</strong>, its possible ? .</p> <p><strong>response</strong></p> <pre><code>data: { person: null, // these array of object children: { data: 'x', ... ... }, total: 1 } </code></pre>
[ { "answer_id": 74485976, "author": "Pompedup", "author_id": 12239272, "author_profile": "https://Stackoverflow.com/users/12239272", "pm_score": 0, "selected": false, "text": "const response = {}\n\nconst { person, children, total } = response.data || {}\n\nconsole.log(person, children, total)" }, { "answer_id": 74486005, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": -1, "selected": false, "text": "response.data.person if-else ternary && const {person} = response.data;\n\nif(person){\n // do something if person is available\n} else {\n // do something if person is not available\n}\n\n\n// ternary operator\nperson ? /* do something if person is available */ : /* do something if person is not available */\n\n// && operator (less recommended)\nperson && /* do something if person is available */\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8122500/" ]
74,485,910
<p><strong>My creation view redirect to blog main page well after creation but</strong></p> <p><strong>i can't find any post's been created in the posts or admin page posts, can anyone help please</strong></p> <p><strong>here is my view</strong></p> <pre><code>@login_required def add_post(request): if request.method == 'POST': post_form = PostForm(request.POST, request.FILES, instance=request.user) snippet_form = SnippetForm(request.POST) if post_form.is_valid() and snippet_form.is_valid(): post = post_form.save(commit=False) snpt = snippet_form.save(commit=False) post.creator = request.user snpt.id = post.id post.save() and snpt.save() return redirect('blog:index') else: post_form = PostForm() snippet_form = SnippetForm() return render(request, 'blog/add_post.html', {'post': post_form, 'snpt': snippet_form}) </code></pre> <p><strong>what's wrong in this view cause i been able to save new post from admin add new post but from client it doesn't save anything</strong></p> <p><strong>Do I need to use model create() method here or what?</strong></p> <p>*<em>Any required snippet i will provide but the problem is in this snippet</em> <strong>any help is really appreciable</strong></p> <p><a href="https://i.stack.imgur.com/UZwa9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UZwa9.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/MSjJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MSjJS.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/zf1BM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zf1BM.png" alt="enter image description here" /></a></p> <p><strong>Update:</strong></p> <p>my Post model</p> <pre><code>class Post(models.Model): ... creator = models.OneToOneField(settings.AUTH_USER_MODEL... snippet = models.OneToOneField(Snippet,... ... </code></pre>
[ { "answer_id": 74485976, "author": "Pompedup", "author_id": 12239272, "author_profile": "https://Stackoverflow.com/users/12239272", "pm_score": 0, "selected": false, "text": "const response = {}\n\nconst { person, children, total } = response.data || {}\n\nconsole.log(person, children, total)" }, { "answer_id": 74486005, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": -1, "selected": false, "text": "response.data.person if-else ternary && const {person} = response.data;\n\nif(person){\n // do something if person is available\n} else {\n // do something if person is not available\n}\n\n\n// ternary operator\nperson ? /* do something if person is available */ : /* do something if person is not available */\n\n// && operator (less recommended)\nperson && /* do something if person is available */\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11448846/" ]
74,485,928
<p>I would like to understand how to extract all links (starting with <code>www</code> and ending with <code>.com</code>) from a text body such as below. Multiple occurrences may or may not occur per line.</p> <pre><code>cat body.txt text more-text url=&quot;http://www.link1.com&quot;&gt;textblabla textbla=textblabla url=&quot;http://www.link2.com&quot;&gt;textblabla textblabla=textblabla textblabla url=&quot;http://www.link3.com&quot;&gt; textblabla textblablabla=bla </code></pre> <p>Desired output:</p> <pre><code>www.link1.com www.link2.com www.link3.com </code></pre>
[ { "answer_id": 74486482, "author": "Lasha Dolenjashvili", "author_id": 13385741, "author_profile": "https://Stackoverflow.com/users/13385741", "pm_score": 2, "selected": false, "text": "myStr='text more-text url=\"http://www.link1.com\">textblabla textbla=textblabla url=\"http://www.link2.com\">textblabla textblabla=textblabla textblabla url=\"http://www.link3.com\"> textblabla textblablabla=bla';\n\nfor aString in ${myStr[@]}; do\n if [[ ${aString} =~ www.*?com ]]; then\n echo ${BASH_REMATCH[0]}\n fi\ndone\n" }, { "answer_id": 74489174, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 2, "selected": true, "text": "grep $ grep -o 'www\\.[^.]*\\.com' input_file\nwww.link1.com\nwww.link2.com\nwww.link3.com\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8910187/" ]
74,485,929
<p>I don't think my question is a duplicate because I am not asking how to convert Lists in to CSVs. But: <br/> I am trying to convert a list into a comma-delimited csv file.<br/> However, some fields contain commas and semicolons.<br/> A column will be split into at least two columns when there is a comma.<br/> <br/> <strong>My codes:</strong></p> <pre><code>public void SaveToCsv&lt;T&gt;(List&lt;T&gt; listToBeConverted) { var lines = new List&lt;string&gt;(); IEnumerable&lt;PropertyDescriptor&gt; props = TypeDescriptor.GetProperties(typeof(T)).OfType&lt;PropertyDescriptor&gt;(); //Get headers var header = string.Join(&quot;,&quot;, props.ToList().Select(x =&gt; x.Name)); //Add all headers lines.Add(header); //LinQ to get all row data and add commas to serperate them var valueLines = listToBeConverted.Select(row =&gt; string.Join(&quot;,&quot;, header.Split(',').Select(a =&gt; row.GetType().GetProperty(a).GetValue(row, null)))); //add row data to List lines.AddRange(valueLines); ... } </code></pre> <p>How do I modify the LinQ statment to add double quotes to the start and the end of the string when it is <code>System.String</code>?</p>
[ { "answer_id": 74486179, "author": "Sasha Leonov", "author_id": 14897052, "author_profile": "https://Stackoverflow.com/users/14897052", "pm_score": 3, "selected": true, "text": "void SaveToCsv<T>(List<T> listToBeConverted)\n{\n var lines = new List<string>();\n IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();\n //Get headers\n var header = string.Join(\",\", props.ToList().Select(x => x.Name));\n //Add all headers\n lines.Add(header);\n //LinQ to get all row data and add commas to serperate them\n var valueLines = listToBeConverted.Select(row => string.Join(\",\", props.Select(x =>\n {\n var property = row.GetType().GetProperty(x.Name);\n if (property.PropertyType == typeof(string))\n return $\"\\\"{property.GetValue(row, null)}\\\"\";\n return property.GetValue(row, null);\n })));\n //add row data to List\n lines.AddRange(valueLines);\n ...\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14806791/" ]
74,485,941
<p>I want to change the background color of the td when I checked the checkbox. But I don't know how to make it done. Please help me.</p> <p>Each tr will consist a row of data. And each data part will have a checkbox which allow user to check it to highlight those specific data only.</p> <p><a href="https://i.stack.imgur.com/srDGQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/srDGQ.png" alt="This is the example of the image" /></a></p> <p>I want to make it look like this.<a href="https://i.stack.imgur.com/aARyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aARyA.png" alt="Only the first 2 td background change" /></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-js lang-js prettyprint-override"><code>//The script is empty because I don't know how to write</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { width: 100%; border-collapse: collapse; } th { width: 10%; } td { text-align: center; border: 1px solid black; } .selected { background: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link type="text/css" rel="stylesheet" href="views/css/index.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="myTable"&gt; &lt;tr&gt; &lt;th&gt;1&lt;/th&gt; &lt;th&gt;2&lt;/th&gt; &lt;th&gt;3&lt;/th&gt; &lt;th&gt;4&lt;/th&gt; &lt;th&gt;5&lt;/th&gt; &lt;th&gt;6&lt;/th&gt; &lt;th&gt;7&lt;/th&gt; &lt;th&gt;8&lt;/th&gt; &lt;th&gt;9&lt;/th&gt; &lt;/tr&gt; &lt;% for(let a = 0; a &lt; 10; a ++){ %&gt; &lt;tr&gt; &lt;td id="first"&gt;X&lt;/td&gt; &lt;td id="first"&gt;X&lt;/td&gt; &lt;td id="first"&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;X&lt;/td&gt; &lt;td&gt;X&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;X&lt;/td&gt; &lt;td&gt;X&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74486179, "author": "Sasha Leonov", "author_id": 14897052, "author_profile": "https://Stackoverflow.com/users/14897052", "pm_score": 3, "selected": true, "text": "void SaveToCsv<T>(List<T> listToBeConverted)\n{\n var lines = new List<string>();\n IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();\n //Get headers\n var header = string.Join(\",\", props.ToList().Select(x => x.Name));\n //Add all headers\n lines.Add(header);\n //LinQ to get all row data and add commas to serperate them\n var valueLines = listToBeConverted.Select(row => string.Join(\",\", props.Select(x =>\n {\n var property = row.GetType().GetProperty(x.Name);\n if (property.PropertyType == typeof(string))\n return $\"\\\"{property.GetValue(row, null)}\\\"\";\n return property.GetValue(row, null);\n })));\n //add row data to List\n lines.AddRange(valueLines);\n ...\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375246/" ]
74,485,945
<p>I have a Dictionary here:</p> <pre><code>test_dict = {'gfg': ['One', 'six', 'three'], 'is': ['seven', 'eight', 'nine'], 'best': ['ten', 'six']} </code></pre> <p>I tried:</p> <pre><code>for i in range(len(test_dict)): values = list(test_dict.values()) keys = list(test_dict) value_sorted_list = values[i] value_sorted_list = keys[i] keys_sorted_list = random.shuffle(value_sorted_list) test_dict.update({f&quot;{keys_sorted_list}&quot;:value_sorted_list}) </code></pre> <p>I want to sort the keys alphabetically while the value list by length Something like this:</p> <pre><code>test_dict = {'best': ['six', 'ten'], 'gfg': ['One', 'six', 'three'], 'is': ['nine', 'eight', 'seven]} </code></pre> <p>I also want another function similar to the one i mentioned above but if the elements are similar length, to sort them randomly.</p> <p>As well as another function to sort value list randomly.</p>
[ { "answer_id": 74486179, "author": "Sasha Leonov", "author_id": 14897052, "author_profile": "https://Stackoverflow.com/users/14897052", "pm_score": 3, "selected": true, "text": "void SaveToCsv<T>(List<T> listToBeConverted)\n{\n var lines = new List<string>();\n IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();\n //Get headers\n var header = string.Join(\",\", props.ToList().Select(x => x.Name));\n //Add all headers\n lines.Add(header);\n //LinQ to get all row data and add commas to serperate them\n var valueLines = listToBeConverted.Select(row => string.Join(\",\", props.Select(x =>\n {\n var property = row.GetType().GetProperty(x.Name);\n if (property.PropertyType == typeof(string))\n return $\"\\\"{property.GetValue(row, null)}\\\"\";\n return property.GetValue(row, null);\n })));\n //add row data to List\n lines.AddRange(valueLines);\n ...\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17248521/" ]
74,485,957
<p>I have a problem. How can I check which emoji the user reacted with? That did not work for me <a href="https://stackoverflow.com/questions/63171531/how-do-you-check-if-a-specific-user-reacts-to-a-specific-message-discord-py">How do you check if a specific user reacts to a specific message [discord.py]</a></p> <p>I want to check if the reaction is <code>✅</code> or <code>❌</code></p> <p>folder structure</p> <pre><code>├── main.py ├── cogs │ ├── member.py </code></pre> <p>The problem is that I don't get an error message. Nothing happens. As soon as I react with an emoji, nothing happens.</p> <p>member.py</p> <pre class="lang-py prettyprint-override"><code>import discord from discord.ext import commands from datetime import datetime class command(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): ... ... for emoji in emojis: await msg.add_reaction(emoji) await message.author.send('Send me that ✅ reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '✅' res = await self.bot.wait_for( &quot;reaction_add&quot;, check=check, timeout=None ) print(res.emoji) if res.content.lower() == &quot;✅&quot;: await message.author.send(&quot;Got it&quot;) else: await message.author.send(&quot;Thanks&quot;) confirmation = await self.bot.wait_for(&quot;reaction_add&quot;, check=check) await message.author.send(&quot;You responded with {}&quot;.format(reaction.emoji)) async def setup(bot): await bot.add_cog(command(bot)) </code></pre> <pre class="lang-py prettyprint-override"><code>import asyncio import os from dotenv import load_dotenv import discord from discord.ext import commands from discord.ext.commands import has_permissions load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') import discord from discord.utils import get class MyBot(commands.Bot): def __init__(self): intents = discord.Intents.default() intents.message_content = True super().__init__(command_prefix=commands.when_mentioned_or('-'), intents=intents, max_messages=1000) async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') async def setup_hook(self): for file in os.listdir(&quot;./cogs&quot;): if file.endswith(&quot;.py&quot;): extension = file[:-3] try: await self.load_extension(f&quot;cogs.{extension}&quot;) print(f&quot;Loaded extension '{extension}'&quot;) except Exception as e: exception = f&quot;{type(e).__name__}: {e}&quot; print(f&quot;Failed to load extension {extension}\n{exception}&quot;) bot = MyBot() bot.run(TOKEN) </code></pre>
[ { "answer_id": 74488641, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 1, "selected": false, "text": "check self.<name> (..., check=self.check\n" }, { "answer_id": 74563706, "author": "JesterIsHere", "author_id": 18872613, "author_profile": "https://Stackoverflow.com/users/18872613", "pm_score": 0, "selected": false, "text": "@commands.Cog.listener() accept = '✅'\ndecline = ''\n\ndef check(reaction, user):\n return user == author\n\nmesssage = await ctx.send(\"test\")\nawait message.add_reaction(accept)\nawait message.add_reaction(decline)\n\nreaction = await self.bot.wait_for(\"reaction_add\", check=check)\n\nif str(reaction[0]) == accept:\n await ctx.send(\"Accepted\")\nelif str(reaction[0]) == decline:\n await ctx.send(\"Denied\") \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17136258/" ]
74,485,961
<pre><code>const human = { name: &quot;asdasd&quot;, mouth: { sayName(){ console.log(this.name) } } } human.mouth.sayName() // undefined </code></pre> <p>HELLO! I need the name field to be taken from the parent object THANK YOU!</p>
[ { "answer_id": 74488641, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 1, "selected": false, "text": "check self.<name> (..., check=self.check\n" }, { "answer_id": 74563706, "author": "JesterIsHere", "author_id": 18872613, "author_profile": "https://Stackoverflow.com/users/18872613", "pm_score": 0, "selected": false, "text": "@commands.Cog.listener() accept = '✅'\ndecline = ''\n\ndef check(reaction, user):\n return user == author\n\nmesssage = await ctx.send(\"test\")\nawait message.add_reaction(accept)\nawait message.add_reaction(decline)\n\nreaction = await self.bot.wait_for(\"reaction_add\", check=check)\n\nif str(reaction[0]) == accept:\n await ctx.send(\"Accepted\")\nelif str(reaction[0]) == decline:\n await ctx.send(\"Denied\") \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12106806/" ]
74,485,968
<p>One <code>DropdownItem</code> contains a search <code>Input</code> so when the user clicks on it, I need the drop down menu to remain open so that he types what he needs to search:</p> <pre><code>import React, { Component } from &quot;react&quot;; import { connect } from &quot;react-redux&quot;; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem, } from &quot;reactstrap&quot;; import SearchBar from &quot;./SearchBar&quot;; export class AddToCollectionButton extends Component { constructor(props) { super(props); this.state = { dropdownOpen: false, }; this.toggle = this.toggle.bind(this); } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } render() { return ( &lt;Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle} // color=&quot;default&quot; className=&quot;div-inline float-right ml-1&quot; direction=&quot;left&quot; &gt; &lt;DropdownToggle tag=&quot;span&quot; onClick={this.toggle} data-toggle=&quot;dropdown&quot; aria-expanded={this.state.dropdownOpen} color=&quot;danger&quot; &gt; &lt;span className=&quot;badge badge-danger cursor-pointer-no-color&quot;&gt; &lt;i class=&quot;fa fa-plus&quot; aria-hidden=&quot;true&quot; /&gt;{&quot; &quot;} &lt;/span&gt; &lt;/DropdownToggle&gt; &lt;DropdownMenu className=&quot;dropdown-danger scrollable-drop-down-menu&quot;&gt; &lt;DropdownItem onClick={(e) =&gt; { // e.preventDefault(); // e.stopPropagation(); // this.setState({ // dropdownOpen: true, // }); }} &gt; &lt;SearchBar /&gt; &lt;/DropdownItem&gt; &lt;/DropdownMenu&gt; &lt;/Dropdown&gt; ); } } const mapStateToProps = (state) =&gt; ({}); const mapDispatchToProps = {}; export default connect( mapStateToProps, mapDispatchToProps )(AddToCollectionButton); </code></pre> <p>I tried different things as you can see inside the <code>onClick</code> and other things mentioned on similar questions on SO but nothing worked.</p>
[ { "answer_id": 74488140, "author": "André", "author_id": 13970434, "author_profile": "https://Stackoverflow.com/users/13970434", "pm_score": 1, "selected": false, "text": "autoClose={false}" }, { "answer_id": 74615429, "author": "Zahnstochermann", "author_id": 5794180, "author_profile": "https://Stackoverflow.com/users/5794180", "pm_score": 0, "selected": false, "text": "<DropdownItem toggle={false} >\n <SearchBar />\n</DropdownItem>\n" }, { "answer_id": 74670379, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 0, "selected": false, "text": "stopPropagation <SearchBar /> input or div <SearchBar />" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8965420/" ]
74,485,982
<p>I am trying to load favicon from assets in nuxt 3 but it does not work except if I hardcode _nuxt in front of it. My config looks like this and this works:</p> <pre class="lang-js prettyprint-override"><code> export default defineNuxtConfig({ app: { head: { link: [{ rel: 'icon', type: 'image/png', href: '_nuxt/assets/favicon.png' }] } }, </code></pre> <p>But according to documentation it should be something like this:</p> <pre class="lang-js prettyprint-override"><code> ~assets/favicon.png </code></pre> <p>or</p> <pre class="lang-js prettyprint-override"><code> ~/assets/favicon.png </code></pre> <p>but both don't work.<br /> Any way to do it as documented or is this a bug?</p> <p>AddOn Info: If using the links in a vue component it works and the favicon loads correctly if I show it on the page.</p>
[ { "answer_id": 74486516, "author": "BZC", "author_id": 2144818, "author_profile": "https://Stackoverflow.com/users/2144818", "pm_score": 0, "selected": false, "text": "export default {\n static: {\n prefix: false\n }\n}\n export default {\n build: {\n publicPath: 'https://cdn.nuxtjs.org'\n }\n}\n" }, { "answer_id": 74509670, "author": "sadeq shahmoradi", "author_id": 17023430, "author_profile": "https://Stackoverflow.com/users/17023430", "pm_score": 2, "selected": true, "text": "_nuxt export default defineNuxtConfig({\n app: {\n buildAssetsDir: '/something/',\n head: {\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n link: [{ rel: 'icon', type: 'image/png', href: \"/something/assets/images/logo.png\" }]\n },\n },\n})\n _nuxt export default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }]\n }\n },\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74485982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505748/" ]
74,486,033
<p>I am trying to update an object inside of an array in mongoDB. But what happens is -- it returns the correct updated result, BUT it does not update the actual document in DB.</p> <p>It is weird, I am using this query from past so many months and it is behaving weirdly of sudden.</p> <p><strong>Schema:</strong></p> <pre><code>{ name: String, donations: [ { assigned: Boolean } ] } </code></pre> <p><strong>My Query:</strong></p> <pre><code>const updated = await DonationModel.findOneAndUpdate( { _id:'document Object Id', 'donations._id': 'Object Id of donation Object' }, { 'donations.$.assigned': true, }, { new: true } ); // Here I get the updated result // But this is NOT updated in DB. console.log(updated); </code></pre>
[ { "answer_id": 74486516, "author": "BZC", "author_id": 2144818, "author_profile": "https://Stackoverflow.com/users/2144818", "pm_score": 0, "selected": false, "text": "export default {\n static: {\n prefix: false\n }\n}\n export default {\n build: {\n publicPath: 'https://cdn.nuxtjs.org'\n }\n}\n" }, { "answer_id": 74509670, "author": "sadeq shahmoradi", "author_id": 17023430, "author_profile": "https://Stackoverflow.com/users/17023430", "pm_score": 2, "selected": true, "text": "_nuxt export default defineNuxtConfig({\n app: {\n buildAssetsDir: '/something/',\n head: {\n htmlAttrs: { dir: 'rtl', lang: 'fa' },\n link: [{ rel: 'icon', type: 'image/png', href: \"/something/assets/images/logo.png\" }]\n },\n },\n})\n _nuxt export default defineNuxtConfig({\n app: {\n head: {\n link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }]\n }\n },\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14780215/" ]
74,486,054
<p>I'm trying to create a program where a user copy pastes a list of names seperated by spaces &amp; python saves it as a list.</p> <p>However, while using list.extend it splits every name into alphabets. How can I fix it so it saves each name as a string.</p> <p>How can I solve it.</p>
[ { "answer_id": 74486176, "author": "cheesy_serj", "author_id": 20537253, "author_profile": "https://Stackoverflow.com/users/20537253", "pm_score": 1, "selected": false, "text": "import re\ninput = \"program where a user copy pastes a list of names seperated\"\noutput = re.split(\" \", input)\n ['program', 'where', 'a', 'user', 'copy', 'pastes', 'a', 'list', 'of', 'names', 'seperated']\n" }, { "answer_id": 74486291, "author": "Bastian Venthur", "author_id": 2881414, "author_profile": "https://Stackoverflow.com/users/2881414", "pm_score": 0, "selected": false, "text": "split s = \"foo bar baz\"\ns.split()\n['foo', 'bar', 'baz']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537157/" ]
74,486,070
<p>I want to make script run only from a specific usb drive. I want to make variable $drive which has output of get-disk command, and the, if $drive contains my usb serial - make some function.</p> <p>$drive=get-disk -SerialNumber &quot;980D06056030&quot; | ft SerialNumber</p> <p>if ( &quot;980D06056030&quot; -eq $drive ) {Write-Host &quot;Yes&quot;}</p> <p>This doesn`t work =(</p>
[ { "answer_id": 74486176, "author": "cheesy_serj", "author_id": 20537253, "author_profile": "https://Stackoverflow.com/users/20537253", "pm_score": 1, "selected": false, "text": "import re\ninput = \"program where a user copy pastes a list of names seperated\"\noutput = re.split(\" \", input)\n ['program', 'where', 'a', 'user', 'copy', 'pastes', 'a', 'list', 'of', 'names', 'seperated']\n" }, { "answer_id": 74486291, "author": "Bastian Venthur", "author_id": 2881414, "author_profile": "https://Stackoverflow.com/users/2881414", "pm_score": 0, "selected": false, "text": "split s = \"foo bar baz\"\ns.split()\n['foo', 'bar', 'baz']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537104/" ]
74,486,132
<blockquote> <p>how can i make like this? <a href="https://i.stack.imgur.com/lbkIS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lbkIS.png" alt="enter image description here" /></a></p> </blockquote> <blockquote> <p>I use Expansion Tiles My Code :</p> </blockquote> <pre><code>Container( child: Stack( children: [ Padding( padding: const EdgeInsets.only(right: 20, left: 30), child: Column( children: [ Row( children: [ Flexible( child: Text( 'Jhon Doe', ), ), Flexible( child: Container( height: 22, width: 70, decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), color: const Color(0XFF00B383), ), child: Center( child: Padding( padding: const EdgeInsets.only(bottom: 1), child: Flexible( child: Text( 'User', ), ), ), ), ), ) ], ), Text( 'Level', ), Row( children: [ const Icon( Icons.level, size: 18, color: Color(0XFF3F414E), ), const SizedBox( width: 5, ), Text( 'Boss', ), ], ), InkWell( onTap: () { }, child: const Text( 'Detailed', ), ), const SizedBox( height: 15, ), ExpansionTile( title: const Text('Phone'), children: List.generate(state.user.boss.length, (index) { return Card( child: Text('+91 84785783458') ); } ) ], ), ), Container( color: Colors.red, width: 20, height: , child: const Text('data'), ) ], ), ); </code></pre> <blockquote> <p>I am using ExpansionTile, how can I create it? , I am using ExpansionTile, how can I create it? I am using ExpansionTile, how can I create it? I am using ExpansionTile, how can I create it? I am using ExpansionTile, how can I create it? I am using ExpansionTile, how can I create it?</p> </blockquote>
[ { "answer_id": 74486350, "author": "Jungwon", "author_id": 15134376, "author_profile": "https://Stackoverflow.com/users/15134376", "pm_score": 3, "selected": true, "text": "Container Container Container(\n width: 200,\n height: 100,\n alignment: Alignment.centerRight,\n decoration: BoxDecoration(\n color: Color(0xFFD50000),\n borderRadius: BorderRadius.circular(8),\n ),\n child: Container(\n width: 190,\n height: 100,\n decoration: BoxDecoration(\n borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomRight: Radius.circular(8)),\n color: Colors.redAccent,\n ),\n child: Column(\n children: <Widget>[\n ///Implements your Designed\n ],\n ),\n ),\n ),\n" }, { "answer_id": 74486506, "author": "Sabahat Hussain Qureshi", "author_id": 17901132, "author_profile": "https://Stackoverflow.com/users/17901132", "pm_score": 0, "selected": false, "text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatefulWidget(),\n ),\n );\n }\n}\n\nclass MyStatefulWidget extends StatefulWidget {\n const MyStatefulWidget({super.key});\n\n @override\n State<MyStatefulWidget> createState() => _MyStatefulWidgetState();\n}\n\nclass _MyStatefulWidgetState extends State<MyStatefulWidget> {\n @override\n Widget build(BuildContext context) {\n return Container(\n width: 300,\n height: 100,\n color: Colors.red,\n alignment: Alignment.centerRight,\n child: Container(\n width: 260,\n height: 100,\n color: Colors.red.shade200,\n child: ExpansionTile(\n leading: Icon(Icons.people, color: Colors.white, size: 30),\n iconColor: Colors.white,\n title: Text('Jhon Dee', style: TextStyle(color: Colors.white),),\n children: <Widget>[\n ListTile(title: Text('+91 999 000 1111', style: TextStyle(color: Colors.white),)),\n ],\n ),\n ),\n );\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19646043/" ]
74,486,185
<p>im working on shopify project to develop the android app. Currently im facing issue when creating customer. im tried to solve it if someone know about this please help me out!</p> <p><strong>Create customer mutation query</strong></p> <pre><code>const query= `mutation customerCreate($input: CustomerCreateInput!) { customerCreate(input: $input) { customer { acceptsMarketing email firstName lastName password phone } customerUserErrors { field message code } variables: { &quot;input&quot;: { &quot;acceptsMarketing&quot;: true, &quot;email&quot;: &quot;johnsmith@shopify.com&quot;, &quot;firstName&quot;: &quot;John&quot;, &quot;lastName&quot;: &quot;Smith&quot;, &quot;password&quot;: &quot;5hopify&quot;, &quot;phone&quot;: &quot;111111111111&quot; } }, } }`; async function apiCall(query) { return fetch('https://storename.myshopify.com/api/graphql.json', { method: 'POST', headers: { 'Content-Type': 'application/graphql', 'Access-Control-Origin': '*', 'X-Shopify-Storefront-Access-Token': token, }, body: query, }) .then(response =&gt; response.json()) .then(response =&gt; console.log('response: ', response)) .catch(error =&gt; console.log('error: ', error.message)); </code></pre> <p>}</p> <p><strong>facing the below error</strong></p> <pre><code>{&quot;errors&quot;: [{&quot;locations&quot;: [Array], &quot;message&quot;: &quot;Parse error on \&quot;{\&quot; (LCURLY) at [16, 20]&quot;}]} </code></pre>
[ { "answer_id": 74486280, "author": "nchopra", "author_id": 6314773, "author_profile": "https://Stackoverflow.com/users/6314773", "pm_score": 0, "selected": false, "text": ": variables" }, { "answer_id": 74489099, "author": "ijaz bacha", "author_id": 12519010, "author_profile": "https://Stackoverflow.com/users/12519010", "pm_score": 2, "selected": true, "text": "mutation {\n customerCreate(\n input: {\n firstName: \"dave\",\n lastName: \"smith\",\n email: \"someone@gmail.com\",\n password: \"12345\"\n acceptsMarketing: true,\n \n }\n ) {\n customer {\n id\n firstName\n lastName\n email\n }\n userErrors {\n field\n message\n }\n customer {\n id\n \n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12519010/" ]
74,486,253
<p>In my code every time a page loads, it grabs the departments that page is related to from the WordPress taxonomy and builds an array that is sent to a datalayer variable in tag manager. for example:</p> <p>in PHP</p> <pre class="lang-php prettyprint-override"><code>$department = [&quot;accounting&quot;, &quot;sales&quot;, &quot;support&quot;]; </code></pre> <p>and in JS</p> <pre class="lang-js prettyprint-override"><code>window.dataLayer = window.dataLayer || []; dataLayer.push({ 'department': '&lt;?php echo $department; ?&gt;' }); </code></pre> <p>in GTM, I want to create a pageview trigger called sales_pageview which fires a tag every time a page loads where &quot;department&quot; contains &quot;sales&quot; and I am not sure how to parse that array in GTM to look for that array element.</p> <p>Any suggestions anyone? I added some screenshots for reference:</p> <p><a href="https://i.stack.imgur.com/PUeU9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PUeU9.jpg" alt="tag config" /></a> <a href="https://i.stack.imgur.com/zToig.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zToig.jpg" alt="trigger config" /></a> <a href="https://i.stack.imgur.com/joQVn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/joQVn.jpg" alt="variable config" /></a> <a href="https://i.stack.imgur.com/Q2zIG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q2zIG.jpg" alt="datalayer push code" /></a> <a href="https://i.stack.imgur.com/IqG5j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqG5j.jpg" alt="GTM Assistant Output 1" /></a> <a href="https://i.stack.imgur.com/1B82x.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1B82x.jpg" alt="GTM Assistant Output 2" /></a> <a href="https://i.stack.imgur.com/IIUXK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IIUXK.jpg" alt="GTM Assistant Output 3" /></a> <a href="https://i.stack.imgur.com/SIlVN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SIlVN.jpg" alt="GTM Assistant Output 4" /></a> <a href="https://i.stack.imgur.com/XLHZE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XLHZE.jpg" alt="Dev Console Messages" /></a></p>
[ { "answer_id": 74486280, "author": "nchopra", "author_id": 6314773, "author_profile": "https://Stackoverflow.com/users/6314773", "pm_score": 0, "selected": false, "text": ": variables" }, { "answer_id": 74489099, "author": "ijaz bacha", "author_id": 12519010, "author_profile": "https://Stackoverflow.com/users/12519010", "pm_score": 2, "selected": true, "text": "mutation {\n customerCreate(\n input: {\n firstName: \"dave\",\n lastName: \"smith\",\n email: \"someone@gmail.com\",\n password: \"12345\"\n acceptsMarketing: true,\n \n }\n ) {\n customer {\n id\n firstName\n lastName\n email\n }\n userErrors {\n field\n message\n }\n customer {\n id\n \n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11372387/" ]
74,486,262
<p>I am using Ansible to create a distributed cluster, which requires multiple data disks and mount directories.</p> <p>I am trying to complete requirement by defining the below variables, in my inventory:</p> <pre class="lang-ini prettyprint-override"><code>[all:vars] minio_plate = [ { &quot;disk_dirve&quot;: [&quot;/dev/sdb&quot;,&quot;/dev/sdc&quot;,&quot;/dev/sdd&quot;], &quot;minio_data_dir&quot;: [&quot;/minio/disk1&quot;,&quot;/minio/disk2&quot;,&quot;/minio/disk3&quot;] } ] </code></pre> <p>This is my playbook:</p> <pre class="lang-yaml prettyprint-override"><code>- hosts: 10.102.26.31 tasks: - name: Mount DVD read-only mount: path: &quot;{{item.minio_data_dir}}&quot; src: &quot;{{item.disk_dirve}}&quot; opts: defaults,noatime dump: &quot;0&quot; passno: &quot;2&quot; fstype: xfs state: present with_items: - &quot;{{minio_plate}}&quot; </code></pre> <p>Results of the task in <code>/etc/fstab</code> (reduced to the relevant part of the file):</p> <pre class="lang-none prettyprint-override"><code>['/dev/sdb',\040'/dev/sdc',\040'/dev/sdd'] ['/minio/disk1',\040'/minio/disk2',\040'/minio/disk3'] xfs defaults,noatime 0 2 </code></pre> <p>The result I do expect would be that <code>/etc/fstab</code> contains:</p> <pre class="lang-none prettyprint-override"><code>/dev/sdb /minio/disk1 xfs defaults,noatime 0 2 /dev/sdc /minio/disk2 xfs defaults,noatime 0 2 /dev/sdd /minio/disk3 xfs defaults,noatime 0 2 </code></pre>
[ { "answer_id": 74486280, "author": "nchopra", "author_id": 6314773, "author_profile": "https://Stackoverflow.com/users/6314773", "pm_score": 0, "selected": false, "text": ": variables" }, { "answer_id": 74489099, "author": "ijaz bacha", "author_id": 12519010, "author_profile": "https://Stackoverflow.com/users/12519010", "pm_score": 2, "selected": true, "text": "mutation {\n customerCreate(\n input: {\n firstName: \"dave\",\n lastName: \"smith\",\n email: \"someone@gmail.com\",\n password: \"12345\"\n acceptsMarketing: true,\n \n }\n ) {\n customer {\n id\n firstName\n lastName\n email\n }\n userErrors {\n field\n message\n }\n customer {\n id\n \n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14150358/" ]
74,486,305
<p>I am trying to use the combineLatest with reactive form's valueChanges method in NgOnInIt hook. My use case is below.</p> <p>I want to show the name which received from Observable1$ in the form using patchValue() from Reactive forms. This name field is editable which means when user wants to edit the name which is already shown in the form, I want to check if the name is not the same and if it is not then I want to enable the button to call PUT method. Hence, I want to use combineLatest from RxJS to handle this behavior but I am not able to do that so. Below errors I am getting.</p> <p>Actual Behaviours:</p> <ol> <li>I get error saying that Maximum call stack size exceeded because of updateValueAndValidity() as it goes into infinite loop.</li> <li>I did add {emitEvent: false} in patchValue() but when I tried to edit the field, due to this {emitEvent: false}, nothing is emitting anymore.</li> </ol> <p>Expected behaviour:</p> <p>Formfield should show the data which I received from observable1$ (ex: testName). When I want to edit this field (ex: testNameE), valueChanges method should emit {description: testNameE} value.</p> <p>How I am trying to achieve this.</p> <p>form-component.ts</p> <pre><code> ngOnInit() { combineLatest([ this.observable1$.pipe(startWith(null)), - provides name this.form.valueChanges.pipe(startWith(null)), - wants to get the input from the user when he tried to change the name ]).pipe( tap(([name, formData]) =&gt; { if (name) { this.patchValue(name); } if (formData) { // check the name is different than received from observable1$, // if yes, enable button } }), ).subscribe(); } patchValue(name: string) { this.form.patchValue({ name: name, }); this.form.updateValueAndValidity(); } </code></pre> <p>Can someone please tell me what I am doing wrong here. Any kind of help is appreciated.</p> <p>Below is the link for stackblitz. <a href="https://stackblitz.com/edit/angular-ivy-zjpwxb?file=src/app/app.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-zjpwxb?file=src/app/app.component.ts</a></p>
[ { "answer_id": 74488421, "author": "Nico", "author_id": 4183699, "author_profile": "https://Stackoverflow.com/users/4183699", "pm_score": 1, "selected": false, "text": "import { Component, OnInit } from '@angular/core';\nimport { AbstractControl, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms';\nimport { delay, Observable, of } from 'rxjs';\n\n@Component({\n selector: 'app-temp',\n templateUrl: './temp.component.html',\n styleUrls: ['./temp.component.scss']\n})\nexport class TempComponent implements OnInit {\n\n nameFromService?: String;\n nameForm?: FormGroup;\n \n constructor(private formBuilder: FormBuilder) { }\n\n ngOnInit(): void {\n this.nameForm = this.formBuilder.group({\n name: ['', [Validators.required, this.checkNameIsServiceName] ]\n });\n\n this.setNameFromService();\n }\n\n checkNameIsServiceName = (control: AbstractControl): ValidationErrors | null => {\n if(this.nameFromService == control.value) return {forbiddenName: {value: control.value}};\n else return null;\n }\n\n setNameFromService(){\n // TODO GET name from service that returns an observale\n let obsStringName: Observable<String> = of('TEST').pipe(delay(1000));\n\n obsStringName.subscribe(result => {\n // set variable value and form field value\n this.nameFromService = result;\n this.nameForm?.patchValue({name: result});\n });\n }\n\n onSubmit(){\n // PUT request\n }\n}\n <div *ngIf=\"nameForm && nameFromService\">\n <form [formGroup]=\"nameForm\">\n <input type=\"text\" placeholder=\"Enter username\" formControlName=\"name\" />\n\n <button type=\"submit\" \n (click)=\"onSubmit()\"\n [disabled]=\"!nameForm.valid\">\n Put User\n </button>\n </form>\n</div>\n" }, { "answer_id": 74489088, "author": "Andrew Allen", "author_id": 4711754, "author_profile": "https://Stackoverflow.com/users/4711754", "pm_score": 3, "selected": true, "text": "observable1$ tap \n ngOnInit() {\n // patch name to form\n this.observable1$.pipe(\n filter(v => !!v),\n takeUntil(this.destroyed$)\n ).subscribe(name => this.patchValue(name))\n\n // for use with a async pipe\n this.showSaveButton$ = combineLatest([this.observable1$, this.form.valueChanges])\n .pipe(\n filter(([name, _]) => !!name)\n map(([name, formData]) => {\n // check different\n return name !== formData.name\n }),\n takeUntil(this.destroyed$),\n startWith(false)\n )\n }\n \n patchValue(name: string) {\n this.form.patchValue({\n name: name,\n });\n this.form.updateValueAndValidity();\n }\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043093/" ]
74,486,315
<p>Say I have 2 list columns like below:</p> <pre><code>group1 = [['John', 'Mark'], ['Ben', 'Johnny'], ['Sarah', 'Daniel']] group2 = [['Aya', 'Boa'], ['Mab', 'Johnny'], ['Sarah', 'Peter']] df = pd.DataFrame({'group1':group1, 'group2':group2}) </code></pre> <p>I want to compare the two list columns and remove the list elements from <code>group1</code> if they are present in <code>group2</code>. So expected results for above:</p> <pre><code> group1 group2 ['John', 'Mark'] ['Aya', 'Boa'] ['Ben'] ['Mab', 'Johnny'] ['Daniel'] ['Sarah', 'Peter'] </code></pre> <p>How can I do this? I have tried this:</p> <pre><code>df['group1'] = [[name for name in df['group1'] if name not in df['group2']]] </code></pre> <p>But got errror:</p> <pre><code>TypeError: unhashable type: 'list' </code></pre> <p>Please help.</p>
[ { "answer_id": 74486357, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "zip set df['group1'] = [[x for x in a if x not in S]\n for a, S in zip(df['group1'], df['group2'].apply(set))]\n group1 group2\n0 [John, Mark] [Aya, Boa]\n1 [Ben] [Mab, Johnny]\n2 [Daniel] [Sarah, Peter]\n" }, { "answer_id": 74486452, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "df['group1']=df[['group1','group2']].apply(lambda x: [i for i in x['group1'] if i not in x['group2']],axis=1)\nprint(df)\n'''\n group1 group2\n0 [John, Mark] [Aya, Boa]\n1 [Ben] [Mab, Johnny]\n2 [Daniel] [Sarah, Peter]\n'''\n" }, { "answer_id": 74486510, "author": "Mykola Zotko", "author_id": 8973620, "author_profile": "https://Stackoverflow.com/users/8973620", "pm_score": 2, "selected": false, "text": "df.apply(lambda x: set(x['group1']).difference(x['group2']), axis=1)\n 0 {John, Mark}\n1 {Ben}\n2 {Daniel}\ndtype: object\n .apply(list)" }, { "answer_id": 74492870, "author": "AI ML Team", "author_id": 18541221, "author_profile": "https://Stackoverflow.com/users/18541221", "pm_score": 0, "selected": false, "text": "grp1=[]\nfor i,j in zip(df1,df2):\n group1 = [name for name in i if name not in j]\n grp1.append(group1)\n Group1 : [['John', 'Mark'], ['Ben'], ['Daniel']]\n Group2 : [['Aya', 'Boa'], ['Mab', 'Johnny'], ['Sarah', 'Peter']]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16799744/" ]
74,486,364
<pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main() { string s; s.reserve(5); cout &lt;&lt; s.capacity() &lt;&lt; endl; } </code></pre> <p>The reserve is a std::string's function that sets the capacity. The capacity function shows the space size of c_string in the std::string.</p> <p>But, the result is not 5, but 15. I don't know why.</p>
[ { "answer_id": 74486454, "author": "Adrian Shum", "author_id": 395202, "author_profile": "https://Stackoverflow.com/users/395202", "pm_score": 3, "selected": false, "text": "reserve" }, { "answer_id": 74486622, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 3, "selected": true, "text": "int main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n s.reserve(5);\n std::cout << s.capacity() << \"\\n\";\n}\n 15 #include <iostream>\n#include <string>\n\nint main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n std::cout << sizeof(std::string) << \"\\n\";\n std::cout << sizeof(char) << \"\\n\";\n std::cout << sizeof(char*) << \"\\n\";\n std::cout << sizeof(size_t) << \"\\n\";\n}\n 15\n32\n1\n8\n8\n std::string char* size_t size() std::string reserve(n) n n reserve" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20182123/" ]
74,486,393
<p>So in the if-statement, I want to print a message if the player doesn't input the correct things. The problem is that when I start up the code and type something random, it jumps to the first if where it checks yes and moves on. It even replied to the next function for me. Is there a way to fix this?</p> <pre><code>import time yes_no = ['yes', 'y', 'no', 'n'] directions = ['north', 'n', 'south', 's', 'east', 'e', 'west', 'w'] else_msg = &quot;Invalid command&quot; def start(): print(&quot;-------------------------------&quot;) print(&quot;Welcome to Haunted Funhouse&quot;) print(&quot;Do you want to proceed? (y/n)&quot;) cmd = input(&quot;&gt;&quot;) if cmd in yes_no: if cmd == &quot;yes&quot; or &quot;y&quot;: time.sleep(1) print(&quot;\n------------------&quot;) print(&quot;Get ready&quot;) print(&quot;--------------------\n&quot;) starting_room() elif cmd == &quot;no&quot; or &quot;n&quot;: time.sleep(1) print(&quot;Okay, shutting down&quot;) quit() else: print(else_msg) def starting_room(): print(&quot;-----------Start-----------&quot;) print(&quot;You stand in a octagon room&quot;) print( &quot;There are windows to the northwest, northeast, southeast, southwest&quot;) print(&quot;There are doors to the:\n- North\n- South\n- East\n- West&quot;) print(&quot;---------------------------------------------------------&quot;) print(&quot;Where do you want to go? (n/s/e/w)&quot;) cmd = input(&quot;&gt;&quot;) if cmd in directions: if cmd == &quot;north&quot; or &quot;n&quot;: time.sleep(1) print(&quot;You enter through the north door&quot;) elif cmd == &quot;south&quot; or &quot;s&quot;: time.sleep(1) print(&quot;You go through the south door&quot;) elif cmd == &quot;west&quot; or &quot;w&quot;: time.sleep(1) print(&quot;You enter through the west door&quot;) elif cmd == &quot;east&quot; or &quot;e&quot;: time.sleep(1) print(&quot;You enter through the east door&quot;) else: print(else_msg) start() </code></pre> <p>I've tried changing '''if cmd not in yes_no''' to '''if cmd in yes_no''', but it didn't work. I ran it through Thonny and the code checker said it was fine</p>
[ { "answer_id": 74486454, "author": "Adrian Shum", "author_id": 395202, "author_profile": "https://Stackoverflow.com/users/395202", "pm_score": 3, "selected": false, "text": "reserve" }, { "answer_id": 74486622, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 3, "selected": true, "text": "int main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n s.reserve(5);\n std::cout << s.capacity() << \"\\n\";\n}\n 15 #include <iostream>\n#include <string>\n\nint main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n std::cout << sizeof(std::string) << \"\\n\";\n std::cout << sizeof(char) << \"\\n\";\n std::cout << sizeof(char*) << \"\\n\";\n std::cout << sizeof(size_t) << \"\\n\";\n}\n 15\n32\n1\n8\n8\n std::string char* size_t size() std::string reserve(n) n n reserve" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537373/" ]
74,486,450
<p>on mysql I see this error but can fix it. Anyone can help please?</p> <pre><code> select * from ( (select a.* from sessions as a) join ( select b.customer_id, min(b.timestamp), b.marketing_source as first_touch_source, b.marketing_medium as first_touch_medium from sessions as b group by b.customer_id ) on a.customer_id = b=customer_id ) as T </code></pre>
[ { "answer_id": 74486454, "author": "Adrian Shum", "author_id": 395202, "author_profile": "https://Stackoverflow.com/users/395202", "pm_score": 3, "selected": false, "text": "reserve" }, { "answer_id": 74486622, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 3, "selected": true, "text": "int main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n s.reserve(5);\n std::cout << s.capacity() << \"\\n\";\n}\n 15 #include <iostream>\n#include <string>\n\nint main()\n{\n std::string s;\n std::cout << s.capacity() << \"\\n\";\n std::cout << sizeof(std::string) << \"\\n\";\n std::cout << sizeof(char) << \"\\n\";\n std::cout << sizeof(char*) << \"\\n\";\n std::cout << sizeof(size_t) << \"\\n\";\n}\n 15\n32\n1\n8\n8\n std::string char* size_t size() std::string reserve(n) n n reserve" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585629/" ]
74,486,451
<p>Protobuf definations are like that:</p> <pre class="lang-protobuf prettyprint-override"><code>syntax = &quot;proto3&quot; message HugeMessage { // omitted } message Request { string name = 1; HugeMessage payload = 2; } </code></pre> <p>In a situation I received a <code>HugeMessage</code> from somebody, and I want to pack it with additional fields, and then transmit the message to someone else. So that I have to <em>Unmarshal</em> the <code>HugeMessage</code> binary into Go structure, pack it into <code>Request</code>, and <em>Marshal</em> again. Due to the hgue size for <code>HugeMessage</code>, the cost for <em>Unmarshal</em> and <em>Marshal</em> are unaffordable. so could I reuse the <code>HugeMessage</code> binary without change the protobuf definations?</p> <pre class="lang-golang prettyprint-override"><code>func main() { // receive it from file or network, not important. bins, _ := os.ReadFile(&quot;hugeMessage.dump&quot;) var message HugeMessage _ = proto.Unmarshal(bins, &amp;message) // slow request := Request{ name: &quot;xxxx&quot;, payload: message, } requestBinary, _ := proto.Marshal(&amp;request) // slow // send it. os.WriteFile(&quot;request.dump&quot;, requestBinary, 0644) } </code></pre>
[ { "answer_id": 74522288, "author": "nj_", "author_id": 5993518, "author_profile": "https://Stackoverflow.com/users/5993518", "pm_score": 2, "selected": true, "text": "HugeMessage Request message Request {\n string name = 1;\n HugeMessage payload = 2;\n}\n message Request {\n string name = 1;\n bytes payload = 2;\n}\n payload Marshal(...) HugeMessage syntax = \"proto3\";\n\nmessage HugeMessage {\n bytes field1 = 1;\n string field2 = 2;\n int64 field3 = 3;\n}\n\nmessage Request {\n string name = 1;\n HugeMessage payload = 2;\n}\n\nmessage RawRequest {\n string name = 1;\n bytes payload = 2;\n}\n req1, err := proto.Marshal(&pb.Request{\n Name: \"name\",\n Payload: &pb.HugeMessage{\n Field1: []byte{1, 2, 3},\n Field2: \"test\",\n Field3: 948414,\n },\n})\nif err != nil {\n panic(err)\n}\n\nhuge, err := proto.Marshal(&pb.HugeMessage{\n Field1: []byte{1, 2, 3},\n Field2: \"test\",\n Field3: 948414,\n})\nif err != nil {\n panic(err)\n}\n\nreq2, err := proto.Marshal(&pb.RawRequest{\n Name: \"name\",\n Payload: huge,\n})\nif err != nil {\n panic(err)\n}\n\nfmt.Printf(\"equal? %t\\n\", bytes.Equal(req1, req2))\n equal? true RawRequest Request" }, { "answer_id": 74674152, "author": "NutwallTinker", "author_id": 15243282, "author_profile": "https://Stackoverflow.com/users/15243282", "pm_score": 0, "selected": false, "text": "HugeMessage Request 2:{${HugeMessageBinary}} func binaryEmbeddingImplementation(messageBytes []byte, name string) (requestBytes []byte, err error) {\n // 1. create a request with all ready except the payload. and marshal it.\n request := protodef.Request{\n Name: name,\n }\n requestBytes, err = proto.Marshal(&request)\n if err != nil {\n return nil, err\n }\n // 2. manually append the payload to the request, by protowire.\n requestBytes = protowire.AppendTag(requestBytes, 2, protowire.BytesType) // embedded message is same as a bytes field, in wire view.\n requestBytes = protowire.AppendBytes(requestBytes, messageBytes)\n return requestBytes, nil\n}\n\n func commonImplementation(messageBytes []byte, name string) (requestBytes []byte, err error) {\n // receive it from file or network, not important.\n var message protodef.HugeMessage\n _ = proto.Unmarshal(messageBytes, &message) // slow\n request := protodef.Request{\n Name: name,\n Payload: &message,\n }\n return proto.Marshal(&request) // slow\n}\n $ go test -bench=a -benchtime 10s ./pkg/ \ngoos: darwin\ngoarch: arm64\npkg: pbembedding/pkg\nBenchmarkCommon-8 49 288026442 ns/op\nBenchmarkEmbedding-8 201 176032133 ns/op\nPASS\nok pbembedding/pkg 80.196s\n\n package pkg\n\nimport (\n \"github.com/stretchr/testify/assert\"\n \"golang.org/x/exp/rand\"\n \"google.golang.org/protobuf/proto\"\n \"pbembedding/pkg/protodef\"\n \"testing\"\n)\n\nvar hugeMessageSample = receiveHugeMessageFromSomewhere()\n\nfunc TestEquivalent(t *testing.T) {\n requestBytes1, _ := commonImplementation(hugeMessageSample, \"xxxx\")\n requestBytes2, _ := binaryEmbeddingImplementation(hugeMessageSample, \"xxxx\")\n // They are not always equal int bytes. you should compare them in message view instead of binary from\n // due to: https://developers.google.com/protocol-buffers/docs/encoding#implications\n // I'm Lazy.\n assert.NotEmpty(t, requestBytes1)\n assert.Equal(t, requestBytes1, requestBytes2)\n var request protodef.Request\n err := proto.Unmarshal(requestBytes1, &request)\n assert.NoError(t, err)\n assert.Equal(t, \"xxxx\", request.Name)\n}\n\n// actually mock one.\nfunc receiveHugeMessageFromSomewhere() []byte {\n buffer := make([]byte, 1024*1024*1024)\n _, _ = rand.Read(buffer)\n message := protodef.HugeMessage{\n Data: buffer,\n }\n res, _ := proto.Marshal(&message)\n return res\n}\n\nfunc BenchmarkCommon(b *testing.B) {\n b.ResetTimer()\n for i := 0; i < b.N; i++ {\n _, err := commonImplementation(hugeMessageSample, \"xxxx\")\n if err != nil {\n panic(err)\n }\n }\n}\n\nfunc BenchmarkEmbedding(b *testing.B) {\n b.ResetTimer()\n for i := 0; i < b.N; i++ {\n _, err := binaryEmbeddingImplementation(hugeMessageSample, \"xxxx\")\n if err != nil {\n panic(err)\n }\n }\n}\n\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15243282/" ]
74,486,457
<p>I have a requirement in SQL Server to get the 2 dates inside the brackets</p> <p>Example: Billing for(1 Aug 2020 - 30 Oct 2020)</p> <p>Expected to have this in two columns:</p> <pre><code>Fromdate Todate 01/08/2020 30/10/2020 </code></pre> <p>Select substring to get the value but not sure how to do both in one query.</p>
[ { "answer_id": 74487054, "author": "Gustav", "author_id": 3527297, "author_profile": "https://Stackoverflow.com/users/3527297", "pm_score": 1, "selected": false, "text": "Convert Concat Select *, \nConcat(\n 'Billing for(', \n Convert(VarChar(50), Fromdate, 106), \n ' - ', \n Convert(VarChar(50), Todate, 106),\n ')') As Period \n\nFrom YourTable\n Select \n Convert(DateTime, SubString([Field Name], PatIndex('%(%', [Field Name]) + 1, 11)) As Fromdate,\n Convert(DateTime, SubString([Field Name], PatIndex('%)%', [Field Name]) - 11, 11)) As Todate\n" }, { "answer_id": 74494541, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 0, "selected": false, "text": "CONCAT_WS() CONCAT() <root>\n <r>1</r>\n <r>Aug</r>\n <r>2020</r>\n <r>-</r>\n <r>30</r>\n <r>Oct</r>\n <r>2020</r>\n</root>\n DECLARE @input VARCHAR(100) = 'Billing for(1 Aug 2020 - 30 Oct 2020)'\n , @separator CHAR(1) = SPACE(1);\n\n;WITH rs AS\n(\n SELECT @input AS input\n , CHARINDEX('(', @input) AS [start]\n , CHARINDEX(')', @input) AS [end]\n)\nSELECT rs.input, c\n , TRY_CAST(CONCAT_WS('-'\n , c.value('(/root/r[3]/text())[1]', 'CHAR(4)')\n , c.value('(/root/r[2]/text())[1]', 'CHAR(3)')\n , c.value('(/root/r[1]/text())[1]', 'CHAR(2)')) AS DATE) AS FromDate\n , TRY_CAST(CONCAT_WS('-'\n , c.value('(/root/r[7]/text())[1]', 'CHAR(4)')\n , c.value('(/root/r[6]/text())[1]', 'CHAR(3)')\n , c.value('(/root/r[5]/text())[1]', 'CHAR(2)')) AS DATE) AS ToDate\nFROM rs\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(SUBSTRING(input, [start]+1, [end] - [start]-1), @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t(c);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537437/" ]
74,486,470
<p>I don't understand how can I autofill a formula that is on a cell to a new column added on the left. Let's make an example: <a href="https://i.stack.imgur.com/WcV5c.png" rel="nofollow noreferrer">[Example](https://i.stack.imgur.com/ufCvH.png)</a> I have on cell &quot;B2&quot; a date that is &quot;B1+180&quot;, when I add a new column on the left of &quot;B2&quot;, the new &quot;B2&quot; does not contain the formula. How can it autofill the formula when adding new column on the left?</p> <p>Thanks.</p> <p>I'm expecting that when I add a new column on the left of &quot;B2&quot;, the new B2 will autofill the formula &quot;B1+180&quot;.</p>
[ { "answer_id": 74487054, "author": "Gustav", "author_id": 3527297, "author_profile": "https://Stackoverflow.com/users/3527297", "pm_score": 1, "selected": false, "text": "Convert Concat Select *, \nConcat(\n 'Billing for(', \n Convert(VarChar(50), Fromdate, 106), \n ' - ', \n Convert(VarChar(50), Todate, 106),\n ')') As Period \n\nFrom YourTable\n Select \n Convert(DateTime, SubString([Field Name], PatIndex('%(%', [Field Name]) + 1, 11)) As Fromdate,\n Convert(DateTime, SubString([Field Name], PatIndex('%)%', [Field Name]) - 11, 11)) As Todate\n" }, { "answer_id": 74494541, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 0, "selected": false, "text": "CONCAT_WS() CONCAT() <root>\n <r>1</r>\n <r>Aug</r>\n <r>2020</r>\n <r>-</r>\n <r>30</r>\n <r>Oct</r>\n <r>2020</r>\n</root>\n DECLARE @input VARCHAR(100) = 'Billing for(1 Aug 2020 - 30 Oct 2020)'\n , @separator CHAR(1) = SPACE(1);\n\n;WITH rs AS\n(\n SELECT @input AS input\n , CHARINDEX('(', @input) AS [start]\n , CHARINDEX(')', @input) AS [end]\n)\nSELECT rs.input, c\n , TRY_CAST(CONCAT_WS('-'\n , c.value('(/root/r[3]/text())[1]', 'CHAR(4)')\n , c.value('(/root/r[2]/text())[1]', 'CHAR(3)')\n , c.value('(/root/r[1]/text())[1]', 'CHAR(2)')) AS DATE) AS FromDate\n , TRY_CAST(CONCAT_WS('-'\n , c.value('(/root/r[7]/text())[1]', 'CHAR(4)')\n , c.value('(/root/r[6]/text())[1]', 'CHAR(3)')\n , c.value('(/root/r[5]/text())[1]', 'CHAR(2)')) AS DATE) AS ToDate\nFROM rs\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(SUBSTRING(input, [start]+1, [end] - [start]-1), @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t(c);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20166362/" ]
74,486,476
<p>The code provides the data and the functions required for ggplot drawing, but the drawn bar chart y-axis is not equidistant, which makes me confused. Please scholars answer.</p> <pre><code>col1 &lt;- c('SO','MO','EO','YO','RO') col2 &lt;- c('J','J','J','J','J', 'F','F','F','F','F', 'M','M','M','M','M', 'G','G','G','G','G') col3 &lt;- c('0.92966','0.94522','0.93311','0.995222', '0.966463','0.975725','0.976464','0.9635321', '0.980223','0.9124456','0.991678','0.973444', '0.910789','0.922','0.993444','0.956555', '0.923132','0.987222','0.900556','0.932228') data &lt;- data.frame(col1,col2,col3) library(ggplot2) ggplot(data, aes(x=col1, y=col3,fill=col2)) + labs(x = &quot;col1&quot;, y = &quot;col3&quot;)+ geom_bar(stat = 'identity', position=position_dodge())+ scale_fill_discrete( breaks = c(&quot;J&quot;,&quot;F&quot;,&quot;M&quot;,'G'))+ theme(legend.title = element_text( size=12, face=&quot;bold&quot;), legend.text = element_text(size =12), axis.title.x = element_text(size = 13, face=&quot;bold&quot;), axis.title.y = element_text(size = 13, face=&quot;bold&quot;), axis.text.x = element_text(size = 12, face=&quot;bold&quot;), axis.text.y = element_text(size = 12,face=&quot;bold&quot;))+ scale_x_discrete(limits = c('SO','MO','EO','YO','RO')) </code></pre> <p>How to draw a bar chart with y-axis range of 0.9-1 and equal spacing?</p>
[ { "answer_id": 74486685, "author": "R18", "author_id": 6930388, "author_profile": "https://Stackoverflow.com/users/6930388", "pm_score": 1, "selected": false, "text": "col3 data$col3 <- as.numeric(data$col3)\n scale_y_continuous(breaks = seq(0, 1, 0.1))\n" }, { "answer_id": 74486990, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 3, "selected": true, "text": "coord_cartesian ylim library(ggplot2)\nggplot(data, aes(x=col1, y=as.numeric(col3), fill=col2)) + \n labs(x = \"col1\", y = \"col3\")+\n geom_bar(stat = 'identity', position=position_dodge())+\n scale_fill_discrete(\n breaks = c(\"J\",\"F\",\"M\",'G'))+\n theme(legend.title = element_text( size=12, face=\"bold\"),\n legend.text = element_text(size =12),\n axis.title.x = element_text(size = 13, face=\"bold\"),\n axis.title.y = element_text(size = 13, face=\"bold\"),\n axis.text.x = element_text(size = 12, face=\"bold\"),\n axis.text.y = element_text(size = 12,face=\"bold\"))+\n scale_x_discrete(limits = c('SO','MO','EO','YO','RO')) +\n coord_cartesian(ylim = c(0.9, 1)) +\n scale_y_continuous(expand = c(0, 0))\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17418925/" ]
74,486,499
<pre><code>category_tag = soup.find_all('div' , {'class': '_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8'}) </code></pre> <p>Output of category_tag:</p> <pre><code>&lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318158031&quot;&gt;Action &amp;amp; Adventure&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318052031&quot;&gt;Arts, Film &amp;amp; Photography&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318064031&quot;&gt;Biographies, Diaries &amp;amp; True Accounts&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318068031&quot;&gt;Business &amp;amp; Economics&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318073031&quot;&gt;Children's &amp;amp; Young Adult&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318104031&quot;&gt;Comics &amp;amp; Mangas&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318105031&quot;&gt;Computing, Internet &amp;amp; Digital Media&lt;/a&gt;&lt;/div&gt;, &lt;div class=&quot;_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8&quot; role=&quot;treeitem&quot;&gt;&lt;a href=&quot;/gp/bestsellers/books/1318118031&quot;&gt;Crafts, Home &amp;amp; Lifestyle&lt;/a&gt;&lt;/div&gt;, </code></pre> <p>Now the problem is, I am not able to extract <code>href</code> from ''. It keeps showing error.</p> <p>I have already tried:</p> <pre><code>category_url_tag = category_tag.find('a')['href'] </code></pre> <p>But it keeps showing an error.</p> <pre><code>category_url = [] for tag in category_tag: category_url.append(tag.get('href')) print(category_url) </code></pre> <p>This printed a list containing <code>None</code>.</p>
[ { "answer_id": 74486926, "author": "HedgeHog", "author_id": 14460824, "author_profile": "https://Stackoverflow.com/users/14460824", "pm_score": 2, "selected": true, "text": "id tag soup.select('#zg-left-col a')\n soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')\n list lis comprehension ['https://www.amazon.in'+a.get('href') for a in soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')]\n dict comprehension import requests\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(requests.get('https://www.amazon.in/gp/bestsellers/books/').text)\n\n\n{'https://www.amazon.in'+a.get('href'):a.text for a in soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')}\n {'https://www.amazon.in/gp/bestsellers/books/1318158031': 'Action & Adventure',\n 'https://www.amazon.in/gp/bestsellers/books/1318052031': 'Arts, Film & Photography',\n 'https://www.amazon.in/gp/bestsellers/books/1318064031': 'Biographies, Diaries & True Accounts',\n 'https://www.amazon.in/gp/bestsellers/books/1318068031': 'Business & Economics',\n 'https://www.amazon.in/gp/bestsellers/books/1318073031': \"Children's & Young Adult\",\n 'https://www.amazon.in/gp/bestsellers/books/1318104031': 'Comics & Mangas',\n 'https://www.amazon.in/gp/bestsellers/books/1318105031': 'Computing, Internet & Digital Media',\n 'https://www.amazon.in/gp/bestsellers/books/1318118031': 'Crafts, Home & Lifestyle',\n 'https://www.amazon.in/gp/bestsellers/books/1318161031': 'Crime, Thriller & Mystery',\n 'https://www.amazon.in/gp/bestsellers/books/22960344031': 'Engineering',...}\n" }, { "answer_id": 74486975, "author": "Nazmul Hasan", "author_id": 3077037, "author_profile": "https://Stackoverflow.com/users/3077037", "pm_score": 0, "selected": false, "text": "category_tag = soup.find_all('div' , {'class': '_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8'})\ncategories = [(cat.find('a').text, cat.find('a')['href']) for cat in category_tag[1:]]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20370549/" ]
74,486,529
<p>I used Eloquent query to extract the below table</p> <pre><code>**$ user = User::all() ** id q1 q2 q3 q4 q5 q6 q7 0 0.01 0.8 null 0.9 null 0.9 0.1 1 0.8 null null 1 null 1 null 2 null null null 0.03 null 0.03 null 3 0.04 0.4 null 0.9 null 0.5 null 4 null 0.67 null 0.8 null 9 0.8 5 0.07 0.9 null 0.6 null 10 null 6 1 null null 1 null 0.05 null </code></pre> <pre><code>The final table should look like this id q1 q2 q4 q6 q7 0 0.01 0.8 0.9 0.9 0.1 1 0.8 null 1 1 null 2 null null 0.03 0.03 null 3 0.04 0.4 0.9 0.5 null 4 null 0.67 0.8 9 0.8 5 0.07 0.9 0.6 10 null 6 1 null 1 0.05 null </code></pre> <p>I need to query the model in the laravel by removing the column that has only null values. Any help would be appreciated.</p>
[ { "answer_id": 74486926, "author": "HedgeHog", "author_id": 14460824, "author_profile": "https://Stackoverflow.com/users/14460824", "pm_score": 2, "selected": true, "text": "id tag soup.select('#zg-left-col a')\n soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')\n list lis comprehension ['https://www.amazon.in'+a.get('href') for a in soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')]\n dict comprehension import requests\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(requests.get('https://www.amazon.in/gp/bestsellers/books/').text)\n\n\n{'https://www.amazon.in'+a.get('href'):a.text for a in soup.select('#zg-left-col a[href^=\"/gp/bestsellers/books\"]')}\n {'https://www.amazon.in/gp/bestsellers/books/1318158031': 'Action & Adventure',\n 'https://www.amazon.in/gp/bestsellers/books/1318052031': 'Arts, Film & Photography',\n 'https://www.amazon.in/gp/bestsellers/books/1318064031': 'Biographies, Diaries & True Accounts',\n 'https://www.amazon.in/gp/bestsellers/books/1318068031': 'Business & Economics',\n 'https://www.amazon.in/gp/bestsellers/books/1318073031': \"Children's & Young Adult\",\n 'https://www.amazon.in/gp/bestsellers/books/1318104031': 'Comics & Mangas',\n 'https://www.amazon.in/gp/bestsellers/books/1318105031': 'Computing, Internet & Digital Media',\n 'https://www.amazon.in/gp/bestsellers/books/1318118031': 'Crafts, Home & Lifestyle',\n 'https://www.amazon.in/gp/bestsellers/books/1318161031': 'Crime, Thriller & Mystery',\n 'https://www.amazon.in/gp/bestsellers/books/22960344031': 'Engineering',...}\n" }, { "answer_id": 74486975, "author": "Nazmul Hasan", "author_id": 3077037, "author_profile": "https://Stackoverflow.com/users/3077037", "pm_score": 0, "selected": false, "text": "category_tag = soup.find_all('div' , {'class': '_p13n-zg-nav-tree-all_style_zg-browse-item__1rdKf _p13n-zg-nav-tree-all_style_zg-browse-height-large__1z5B8'})\ncategories = [(cat.find('a').text, cat.find('a')['href']) for cat in category_tag[1:]]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478590/" ]
74,486,545
<p>I have learned that what is the Equatable and how can I use it. But I just wonder that why should I use it?</p> <p>I have found some reasons. One of them, when we wants to compare 2 or more same object from any class, it will use. they aren't same even if they properties same because of hash code. But equatable compares each other without hash code.</p> <p>But I really wonder that where I will use in real life scenario?</p> <p>Many Thanks..</p>
[ { "answer_id": 74486620, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "user class User extends Equatable {\n final String fullName;\n final int phone;\n const User({\n required this.fullName,\n required this.phone,\n });\n\n @override\n List<Object?> get props => [fullName, phone];\n}\n var myUser = User(fullName: 'Amir', phone: 123456);\nList<User> users = [\n User(fullName: 'Amir', phone: 123456),\n User(fullName: 'Amir 2', phone: 5353453),\n User(fullName: 'Amir 3', phone: 78978978),\n];\n users myUser users.remove(myUser);\n Equatable User" }, { "answer_id": 74486671, "author": "powerman23rus", "author_id": 6163011, "author_profile": "https://Stackoverflow.com/users/6163011", "pm_score": 2, "selected": true, "text": "equals hasCode equals hashCode Set Map HashTables equivalency dart" }, { "answer_id": 74486763, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": "class Bar {\n final int a = 2;\n}\n\nprint(Bar() == Bar()); //false\n class Foo extends Equatable {\n final int a = 2;\n\n @override\n List<Object?> get props => [a];\n}\n\n print(Foo() == Foo()); //true\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18849295/" ]
74,486,617
<p>I have this injection VB script that I use for altering C# source code. This is my current regex match rule I use currently to find code rows with classes in the files:</p> <pre><code>(public|protected|internal|private|static|abstract)\b\W+(class)\b </code></pre> <p>It works and detects class rows, but the problem is it detects all cases in the examples below, while only the first one should be valid.</p> <pre><code>public class &lt;-- is valid match //this is a public class comment &lt;-- Should not be valid as match &quot;This is just a string talking about a public class&quot; &lt;-- Should not be valid match </code></pre> <p>To me, what is missing is to have this match rule work is, only allow what is matched by allowed words, and make any other extra a non valid match. Well, a blank space should be the only type that should be allowed.</p> <p>How to update the current regex to only match the first line of the three examples I just gave?</p>
[ { "answer_id": 74486876, "author": "VvdL", "author_id": 15589010, "author_profile": "https://Stackoverflow.com/users/15589010", "pm_score": 3, "selected": true, "text": "^\\s* ^\\s*(public|protected|internal|private|static|abstract)\\b\\W+(class)\\b" }, { "answer_id": 74486922, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "(public|protected|internal|private|static|abstract)\\b\\W+(class)\\b\\s*[\\r\\n]{0,2}\\s*{\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/955379/" ]
74,486,686
<p>We have a develop to make some things with bank cards. One og them is validate the PIN (we have PAN, PIN, Pinlenght and PINBLOCK); and we have a HSM THALES to validate the PIN.</p> <p>But, how do we connect whith THLALES appliance? I thought that using a library, nugget o similar, but there are no many documentation in internet.</p> <p>I know the command to send to HSM, expected response, and similar. But.. i can't find documentation about how to connect whit Hardare module.</p> <p>Any documentation, connection interface, library o similar.</p>
[ { "answer_id": 74486876, "author": "VvdL", "author_id": 15589010, "author_profile": "https://Stackoverflow.com/users/15589010", "pm_score": 3, "selected": true, "text": "^\\s* ^\\s*(public|protected|internal|private|static|abstract)\\b\\W+(class)\\b" }, { "answer_id": 74486922, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "(public|protected|internal|private|static|abstract)\\b\\W+(class)\\b\\s*[\\r\\n]{0,2}\\s*{\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537566/" ]
74,486,720
<p>In short, the statement <code>GRANT SELECt ON KEYSPACE AAA TO user;</code> not take effect when executing <code>LIST ALL PERMISSIONS OF user;</code>.</p> <p>I find nothing when I google this.</p>
[ { "answer_id": 74489983, "author": "Madhavan", "author_id": 10410162, "author_profile": "https://Stackoverflow.com/users/10410162", "pm_score": 2, "selected": false, "text": "AAA SELECT user cqlsh> GRANT SELECT ON \"AAA\" TO user;\n user data_reader SELECT AAA user cqlsh> LIST ALL PERMISSIONS OF user;\n" }, { "answer_id": 74570342, "author": "Erick Ramirez", "author_id": 4269535, "author_profile": "https://Stackoverflow.com/users/4269535", "pm_score": 0, "selected": false, "text": "ROLE admin@cqlsh> CREATE KEYSPACE stackoverflow \\\n WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};\n admin@cqlsh> CREATE ROLE zhang WITH LOGIN = true ;\n SELECT admin@cqlsh> GRANT SELECT ON KEYSPACE stackoverflow TO zhang;\n admin@cqlsh> LIST ALL PERMISSIONS OF zhang;\n\n role | username | resource | permission\n-------+----------+--------------------------+------------\n zhang | zhang | <keyspace stackoverflow> | SELECT\n USER admin@cqlsh> CREATE USER ming WITH PASSWORD 'password';\n SELECT admin@cqlsh> GRANT SELECT ON KEYSPACE stackoverflow TO ming;\n admin@cqlsh> LIST ALL PERMISSIONS OF ming;\n\n role | username | resource | permission\n------+----------+--------------------------+------------\n ming | ming | <keyspace stackoverflow> | SELECT\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13328556/" ]
74,486,785
<p>(NOW SOLVED by changing to VS Code instead, works like a charm. :) )</p> <p>I am quite a beginner in coding, trying to complete a programming assignment focused on Python. I followed along with Tech with Tim's YouTube video about &quot;Python Website Full Tutorial - Flask, Authentication, Databases &amp; More&quot;. Link: <a href="https://www.youtube.com/watch?v=dam0GPOAvVI" rel="nofollow noreferrer">https://www.youtube.com/watch?v=dam0GPOAvVI</a></p> <p>I have followed the code exactly up until 13:36, where he accesses the website url (<a href="http://127.0.0.1:5000" rel="nofollow noreferrer">http://127.0.0.1:5000</a>). I have tried this, yet I got a 127.0.0.1 refused to connect error.</p> <p><a href="https://i.stack.imgur.com/KMbii.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KMbii.jpg" alt="enter image description here" /></a></p> <p>I have tried to follow many different tutorials on how to fix this error, but to no avail. I tried:</p> <ul> <li>flushing the dns</li> <li>disabling the firewall (real pain)</li> <li>browser HSTS settings</li> </ul> <p>I would have tried asking my teacher, but she already got lost when I tried to explain about front-end and back-end and claimed that I was &quot;too advanced&quot;. I can't ask the other groups either as it seems they might not have started coding yet at all, and my own group does not specialize in coding, more on simple interface designing. In canva.</p> <p>I am now starting to suspect that it might be a problem with the website I am using to code. I am using codecademy's workspaces since we are only allowed to code online because my teacher does not want to download any files on her computer. Should I perhaps change to another one instead?</p> <p>I have downloaded pip yesterday and made sure I downloaded all of the necessary modules, but it doesn't help the problem.</p> <p>This is the fourth day that I have been stuck on this on, and now I've really hit a brick wall. I'm stuck, and I'm not sure what to do next. I am no programmer, I don't think that I can even be classified as a decent one just yet. I'm simply a student who is forced to learn by myself because I can't rely on my own class to teach me.</p>
[ { "answer_id": 74489983, "author": "Madhavan", "author_id": 10410162, "author_profile": "https://Stackoverflow.com/users/10410162", "pm_score": 2, "selected": false, "text": "AAA SELECT user cqlsh> GRANT SELECT ON \"AAA\" TO user;\n user data_reader SELECT AAA user cqlsh> LIST ALL PERMISSIONS OF user;\n" }, { "answer_id": 74570342, "author": "Erick Ramirez", "author_id": 4269535, "author_profile": "https://Stackoverflow.com/users/4269535", "pm_score": 0, "selected": false, "text": "ROLE admin@cqlsh> CREATE KEYSPACE stackoverflow \\\n WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};\n admin@cqlsh> CREATE ROLE zhang WITH LOGIN = true ;\n SELECT admin@cqlsh> GRANT SELECT ON KEYSPACE stackoverflow TO zhang;\n admin@cqlsh> LIST ALL PERMISSIONS OF zhang;\n\n role | username | resource | permission\n-------+----------+--------------------------+------------\n zhang | zhang | <keyspace stackoverflow> | SELECT\n USER admin@cqlsh> CREATE USER ming WITH PASSWORD 'password';\n SELECT admin@cqlsh> GRANT SELECT ON KEYSPACE stackoverflow TO ming;\n admin@cqlsh> LIST ALL PERMISSIONS OF ming;\n\n role | username | resource | permission\n------+----------+--------------------------+------------\n ming | ming | <keyspace stackoverflow> | SELECT\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20530863/" ]
74,486,800
<p>I want to check if an id already exists or not in local-storage, because I want to display specific button if it does. How can I achieve that?</p> <p><a href="https://i.stack.imgur.com/ecnHb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ecnHb.png" alt="enter image description here" /></a></p> <p>here is my code</p> <pre><code>export class FoodPageComponent implements OnInit { buttonShow = false; food!: Food; constructor( activatedRoute: ActivatedRoute, foodService: FoodService, private cartService: CartService, private router: Router ) { activatedRoute.params.subscribe((params) =&gt; { if(params.id) this.food = foodService.getFoodById(params.id); }) } ngOnInit(): void { } addToCart() { this.cartService.addToCart(this.food); this.router.navigateByUrl('/cart-page'); } } </code></pre>
[ { "answer_id": 74486853, "author": "no_modules", "author_id": 19835828, "author_profile": "https://Stackoverflow.com/users/19835828", "pm_score": 1, "selected": false, "text": "const id = 5 id === 5 const items = JSON.parse(localStorage.getItem(\"item\"))\nlet exists = false\n\nfor (const item of items) {\n if (item?.food?.id === id) {\n exists = true\n break\n }\n}\n" }, { "answer_id": 74486890, "author": "Abdul Basith", "author_id": 12706311, "author_profile": "https://Stackoverflow.com/users/12706311", "pm_score": 1, "selected": true, "text": " ngOnInit(): void {\n let storageItems = localStorage.getItem('item');\n if(storageItems) {\n const items = JSON.Parse(items);\n const requiredItem = items.filter((item)=> item.id == yourId);\n if(requiredItem){\n this.buttonShow = true;\n }\n } \n }\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74486800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18746578/" ]