qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,238,340
<p>Python 3.10.7, Django 4.1.1, Django REST Framework 3.13.1</p> <p>I am unable to get the <strong>django.test.Client</strong> <strong>login</strong> or <strong>force_login</strong> methods to work in a <strong>django.test.TestCase</strong>-derived test class. I'm referring to <a href="https://docs.djangoproject.com/en/4.1/topics/testing/tools/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.1/topics/testing/tools/</a></p> <p>My project seems to work when viewing it in a browser. Unauthenticated DRF views appear as expected, and if I log in through the admin site, protected views also appear as expected. A preliminary version of the front end that will consume this API is able to read data and display it with no problem. The local Django unit test environment uses a local SQLite3 install for data. All tests not requiring authentication are currently passing.</p> <p>This simplified test class reliably displays the problem:</p> <pre class="lang-python prettyprint-override"><code>from django.contrib.auth.models import User from django.test import Client, TestCase from django.urls import reverse from eventsadmin.models import Address class AddressesViewTest(TestCase): username = &quot;jrandomuser&quot; password = &quot;qwerty123&quot; user = User.objects.filter(username=username).first() if user: print(&quot;User exists&quot;) else: user = User.objects.create(username=username) print(&quot;User created&quot;) user.set_password(password) user.save() client = Client() def setUp(self): if self.client.login(username=self.username, password=self.password): print(&quot;Login successful&quot;) else: print(&quot;Login failed&quot;) Address.objects.create(name=&quot;White House&quot;, address1=&quot;1600 Pennsylvania Ave&quot;, city=&quot;Washington&quot;, state=&quot;DC&quot;, postal_code=&quot;37188&quot;) def test_addresses(self): response = self.client.get(reverse(&quot;addresses-list&quot;)) self.assertContains(response, '&quot;name&quot;:&quot;White House&quot;') </code></pre> <p>First, I was surprised that I had to test for the existence of the <strong>User</strong>. Even though the test framework emits messages saying it is creating and destroying the test database for each run, after the test has been run once the creation of the <strong>User</strong> fails with a unique constraint violation on the username. If I don't change the value of <strong>username</strong> the test as written here consistently emits <strong>User exists</strong>. This is the only test currently creating/getting a <strong>User</strong> so I'm sure it's not being created by another test.</p> <p>The real problem is <strong>setUp</strong>. It consistently emits <strong>Login failed</strong>, and <strong>test_addresses</strong> fails on access permissions (which is correct behavior when access is attempted on that view without authentication). If I set a breakpoint in the last line of <strong>setUp</strong>, at that point <strong>self.client</strong> is an instance of <strong>django.test.Client</strong>, and <strong>self.username</strong> and <strong>self.password</strong> have the expected values as set above.</p> <p>I tried replacing the call to <strong>login</strong> with <code>self.client.force_login(self.user)</code> but in that case when that line is reached Django raises <strong>django.db.utils.DatabaseError: Save with update_fields did not affect any rows.</strong> (the stack trace originates at <strong>venv/lib/python3.10/site-packages/django/db/models/base.py&quot;, line 1001, in _save_table</strong>).</p> <p>What am I doing wrong? How can I authenticate in this context so I can test views that require authentication?</p>
[ { "answer_id": 74238829, "author": "Nealium", "author_id": 10229768, "author_profile": "https://Stackoverflow.com/users/10229768", "pm_score": 1, "selected": false, "text": "class AddressesViewTest(TestCase):\n def setUp(self):\n self.username = \"jrandomuser\"\n self.pa...
2022/10/28
[ "https://Stackoverflow.com/questions/74238340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8364806/" ]
74,238,343
<p>I have written the following codes in three separate cells in my jupyter notebook and have been able to generate the output I want. However, having this information in one dataframe will make it much easier to read.</p> <p>How can I combine these separate dataframes into one so that the <code>member_casual</code> column is the index with <code>max_ride_length</code>, <code>avg_ride_length</code> and <code>most_active_day_of_week</code> columns next to it in the same dataframe?</p> <p><a href="https://i.stack.imgur.com/VHVro.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHVro.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74238529, "author": "Malo", "author_id": 14662179, "author_profile": "https://Stackoverflow.com/users/14662179", "pm_score": 0, "selected": false, "text": "df.groupby('A').agg(['min', 'max'])\n" }, { "answer_id": 74239411, "author": "Vincent Rupp", "author_...
2022/10/28
[ "https://Stackoverflow.com/questions/74238343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207606/" ]
74,238,372
<pre><code>protocol Builder { associatedtype Output where Output: MyProtocol func build() -&gt; Output? } // concrete type struct ABuilder: Builder { func builder() -&gt; MyProtocol { if someCondition { return aSubClassOfMyProtocol } else { return anotherSubClassOfMyProtocol } } } </code></pre> <p><code>MyProtocol</code> is a protocol type. It is also the <code>Output</code> constraint. Because the concrete Builder <code>ABuilder</code> is going to return two different sub class types that conform <code>MyProtocol</code>. How can I make the generic constraint work?</p> <p>I am trying to make the generic constraint be the same.</p>
[ { "answer_id": 74238935, "author": "Bulat Yakupov", "author_id": 17834877, "author_profile": "https://Stackoverflow.com/users/17834877", "pm_score": 1, "selected": false, "text": "build()" }, { "answer_id": 74246942, "author": "Hanbo", "author_id": 16359851, "author_p...
2022/10/28
[ "https://Stackoverflow.com/questions/74238372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16359851/" ]
74,238,384
<p>I've created vector x and I need to create a vector z by removing the 3rd and 6th elements of x. I cannot just create a vector by simply typing in the elements that should be in z. I have to index them or use a separate function.</p> <pre><code>x = [5,2,0,6,-10,12] np.array(x) print x z = np.delete(x,) </code></pre> <p>I am not sure if using np.delete is best or if there is a better approach. Help?</p>
[ { "answer_id": 74238935, "author": "Bulat Yakupov", "author_id": 17834877, "author_profile": "https://Stackoverflow.com/users/17834877", "pm_score": 1, "selected": false, "text": "build()" }, { "answer_id": 74246942, "author": "Hanbo", "author_id": 16359851, "author_p...
2022/10/28
[ "https://Stackoverflow.com/questions/74238384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20242378/" ]
74,238,391
<p>So I was looking for a more precise alternative to <code>time.sleep()</code> in Python but couldn't find any good options. Does anyone know if there is a more accurate alternative with at least millisecond precision?</p> <p><strong>Something like this:</strong></p> <pre><code>precise_delay(3.141) # Pauses the program for exactly 3.141 seconds </code></pre> <p>And no, I tried, and <code>time.sleep()</code> is not very precise.</p> <p>I did some testing using <code>time.perf_counter()</code> and the results varied from <code>0.005</code> to <code>0.015</code> even tho I entered <code>0.001</code>.</p> <p>Here are the precise times: <code>0.013264300000628282</code>, <code>0.005171099999643047</code> and <code>0.015634399999726156</code></p>
[ { "answer_id": 74243636, "author": "Leo", "author_id": 19280945, "author_profile": "https://Stackoverflow.com/users/19280945", "pm_score": 0, "selected": false, "text": "import time\nimport re\n\ndef precise_delay(delay_amount):\n prv_t = time.perf_counter()\n\n try:\n if le...
2022/10/28
[ "https://Stackoverflow.com/questions/74238391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19280945/" ]
74,238,407
<p>I have two variable lenght lists extracted from an excel file. One has wagon number and the other the wagon weight, something like this:</p> <pre><code>wagon_list = [1234567, 2345678, 3456789, 4567890] weight_list = [1.1, 2.2, 3.3, 4.4] </code></pre> <p>Sometimes the wagon_list will have a duplicate number, I need to sum the wagon weight and remove the duplicate from both:</p> <pre><code>wagon_list = [1234567, 2345678, 2345678, 4567890] weight_list = [1.1, 2.2, 3.3, 4.4] </code></pre> <p>should become:</p> <pre><code>wagon_list = [1234567, 2345678, 4567890] weight_list = [1.1, 5.5, 4.4] </code></pre> <p>My first option was to pop items and sum them while iterating with a for loop. It didnt work because (after some research) you cant change a list youre iterating over. So I moved to the second option, using an auxiliary list. It doesnt work when it hits the last index. Even after some tweaking of my code, I cant find a solution.</p> <p>I can see it would have further problems if the last three elements were to be added.</p> <pre><code>counter_3 = 0 for i in wagon_list: if i == wagon_list[-1]: #last entry, simply appends to the new list. This comes first because the next option returns error if running the last entry as i new_wagon_list.append(wagon_list[counter_3]) new_weight_list.append(weight_list[counter_3]) counter_3 +=2 elif i != wagon_list[(counter_3 + 1)]: #if they are different, appends. new_wagon_list.append(wagon_list[counter_3]) new_weight_list.append(weight_list[counter_3]) counter_3 += 1 elif i == wagon_list[(counter_3 + 1)]: #if equal to next item, appends the wagon and sums the weights new_wagon_list.append(wagon_list[counter_3]) new_weight_list.append(weight_list[counter_3] + weight_list[counter_3 + 1]) </code></pre> <p>This should return:</p> <pre><code>wagon_list = [1234567, 2345678, 4567890] weight_list = [1.1, 5.5, 4.4] </code></pre> <p>But returns</p> <pre><code>wagon_list = [1234567, 2345678, 3456789, 3456789, 3456789] weight_list = [1.1, 2.2, 7.7, 7.7, 3.3] </code></pre>
[ { "answer_id": 74243636, "author": "Leo", "author_id": 19280945, "author_profile": "https://Stackoverflow.com/users/19280945", "pm_score": 0, "selected": false, "text": "import time\nimport re\n\ndef precise_delay(delay_amount):\n prv_t = time.perf_counter()\n\n try:\n if le...
2022/10/28
[ "https://Stackoverflow.com/questions/74238407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20036782/" ]
74,238,409
<p>I am using map in one of the component in React -</p> <pre><code>{ iconName.map(icon =&gt; ( &lt;button onClick={clickHandler} key={icon.id} className='nav__tab'&gt; &lt;Tabs iconName={icon.name} iconUrl={icon.src}/&gt; &lt;/button&gt; ))} </code></pre> <p>And in the Tabs component, I have</p> <pre><code>&lt;div className='tabs'&gt; &lt;div&gt;{ iconUrl }&lt;/div&gt; &lt;span className='tabs__name'&gt;{iconName}&lt;/span&gt; &lt;/div&gt; </code></pre> <p>And on the UI, it looks like this -</p> <p>[<img src="https://i.stack.imgur.com/Trb97.png" alt="(https://i.stack.imgur.com/Trb97.png)" /></p> <p><strong>The problem</strong> - Whenever I click on any button, I want to differentiate which button is clicked. Like when user clicks on Button1, I want to know that button1 is clicked and so on. I am not getting anything inside event on clickHandler function to differentiate the buttons.</p> <p>I checked event.target inside the event, but when I click on SVG icon, it consoles null. And when I click on the text like button1, button2 it gives me the desired result. Only problem is when I click on SVG icons.</p>
[ { "answer_id": 74243636, "author": "Leo", "author_id": 19280945, "author_profile": "https://Stackoverflow.com/users/19280945", "pm_score": 0, "selected": false, "text": "import time\nimport re\n\ndef precise_delay(delay_amount):\n prv_t = time.perf_counter()\n\n try:\n if le...
2022/10/28
[ "https://Stackoverflow.com/questions/74238409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19290397/" ]
74,238,430
<p>I'm new to Python and I've seen a lot of tutorials which jump into the Django REST Framework when discussing how to create REST APIs without explaining why they need this library. I don't see the purpose of using the Django Rest Framework when I can just define API endpoints in views and return a simple HttpResponse to send data to a client.</p> <p>What does the Django Rest Framework accomplish that I can't do simply using HttpResponse? Why is it worth learning?</p> <p>I was going to use the library as it was included in the video, but it seemed more complex than I needed and I decided to try creating an API without Django REST Framework</p> <pre><code>def getStats(request): print('--------STARTING Stats----------') # Take some GET variable version = request.GET.get('version') # Get some data with open('static/data.json') as f: data = json.load(f) # Filter the data if version is not None: data = list(filter(lambda x: x['version'] == version, data)) print(&quot;FILTERED DATA&quot;, len(data)) # Perform some operations on the data data = calculateStats(data) # Return an HTTP response return HttpResponse(json.dumps(data)) </code></pre> <p>This code seemed to work as needed and I get the feeling that I could make this view more robust if needed based on the demands of my application.</p>
[ { "answer_id": 74243636, "author": "Leo", "author_id": 19280945, "author_profile": "https://Stackoverflow.com/users/19280945", "pm_score": 0, "selected": false, "text": "import time\nimport re\n\ndef precise_delay(delay_amount):\n prv_t = time.perf_counter()\n\n try:\n if le...
2022/10/28
[ "https://Stackoverflow.com/questions/74238430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360070/" ]
74,238,453
<p>I have a column that contains data like:</p> <pre><code>September 12, 2022 September 15, 2022 December 12, 2022 January 31, 2023 </code></pre> <p>and this is what I need from those string:</p> <pre><code>September 2022 September 2022 December 2022 January 2023 </code></pre> <p>I only need the month and year of those already existing string values. How can I extract this using sql server?</p> <p>Kindly help with coming up a solution for this.</p> <p>I tried using trim but didnt work as expected.</p>
[ { "answer_id": 74243636, "author": "Leo", "author_id": 19280945, "author_profile": "https://Stackoverflow.com/users/19280945", "pm_score": 0, "selected": false, "text": "import time\nimport re\n\ndef precise_delay(delay_amount):\n prv_t = time.perf_counter()\n\n try:\n if le...
2022/10/28
[ "https://Stackoverflow.com/questions/74238453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20113103/" ]
74,238,454
<p>I have two pandas dataframes:</p> <pre><code>df1 = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2, 4, 2], 'c': [3, 1, 5], 'd': [-1, 0, 1] }, index=('A', 'B', 'C')) df2 = pd.DataFrame({ 'a': [0, 5, 10], 'b': [9, 5, 1], 'c': [3, 4, 2], 'd': [12, 3, 0] }, index=('A', 'B', 'C')) &gt;&gt;&gt; print(df1) a b c d A 1 2 3 -1 B 2 4 1 0 C 3 2 5 1 &gt;&gt;&gt; print(df2) a b c d A 0 9 3 12 B 5 5 4 3 C 10 1 2 0 </code></pre> <p>I would like to get the value from each column of <code>df1</code> that corresponds to (i.e. is at the same coordinates as) the maximal value of that same column in <code>df2</code>. So in the above example it should return the values <code>[3, 2, 1, -1]</code>. I was able to get the correct indices using <code>idxmax</code>:</p> <pre><code>&gt;&gt;&gt; print(df2.idxmax()) a C b A c B d A dtype: object </code></pre> <p>As you can see, these are indeed the indices corresponding to the column-wise maximums in <code>df2</code>. However trying to index into <code>df1</code> using these indices does not return the desired result:</p> <pre><code>&gt;&gt;&gt; print(df1.loc[df2.idxmax()]) a b c d C 3 2 5 1 A 1 2 3 -1 B 2 4 1 0 A 1 2 3 -1 </code></pre> <p>This indexing seems to only use the values of the <code>Series</code> returned by <code>idxmax</code>. How do I correctly index <code>df1</code> using both parts (labels and values) of the returned <code>Series</code>? Or is there maybe a simpler solution to achieve what I want?</p>
[ { "answer_id": 74238557, "author": "Code Different", "author_id": 2538939, "author_profile": "https://Stackoverflow.com/users/2538939", "pm_score": 3, "selected": true, "text": "s = df2.idxmax()\n[df1.loc[row, col] for col, row in s.items()]\n" }, { "answer_id": 74238856, "au...
2022/10/28
[ "https://Stackoverflow.com/questions/74238454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769814/" ]
74,238,462
<p>I am trying to call a function pointer using an explicit dereference. But the compiler throws an error:</p> <pre><code>no operator &quot;*&quot; matches these operands. </code></pre> <p>Here's a simplified version of my code:</p> <pre><code>#include &lt;functional&gt; #include &lt;iostream&gt; int add(int a, int b) { return a + b; } std::function&lt;int(int, int)&gt; passFunction() { return &amp;add; } int main() { int a{ 1 }; int b{ 2 }; std::cout &lt;&lt; (*passFunction())(a, b); return 0; } </code></pre> <p>The thing is, it works fine when I just write:</p> <pre><code>std::cout &lt;&lt; passFunction()(a, b); // without asterix. </code></pre> <p>which blows my mind.</p> <p>I thought that, I messed up parentheses in function call. I tried different order and precedence, I called it with ampersand, and still compiler doesn't even flinch.</p>
[ { "answer_id": 74238521, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 0, "selected": false, "text": "*" }, { "answer_id": 74238524, "author": "Jason Liam", "author_id": 12002570, "author_profile...
2022/10/28
[ "https://Stackoverflow.com/questions/74238462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19291400/" ]
74,238,491
<p>Been banging my ahead against a wall on this one for a while. Doing the FCC course, essentially completed a project but trying to fetch a JSON with an array rather than just putting one in directly, myself, as I wanted to learn how to do it... Didn't think it would be this difficult!</p> <p><strong>What do I want to do?</strong></p> <p>I want to fetch a <a href="https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json" rel="nofollow noreferrer">json</a> and assign the array within it to state within my react component. I'll then use a random num gen to pick a random quote to display from the array.</p> <p><strong>Where am I having trouble?</strong></p> <p>I'm able to fetch the json and log the quotes to the console, however whenever I try to assign them to a variable, I end up with the promise object. I think it's a problem that I must've misunderstood/not quite wrapped my head around asynchronous functions yet</p> <p><strong>What I need help with</strong></p> <p>I've created a <a href="https://codepen.io/Jobeyobey/pen/OJEVvQa" rel="nofollow noreferrer">new codepen</a>, separate to the task, where I have been testing how to get this to work without React, so I can then work it into my React project when I know what to do.</p> <p>I'm able to log the first quote in the array to the console when I run the async function, however when I try to use that same async function to return that quote to myQuote, it returns a Pending Promise. Am I approaching this correctly at all, or am I completely going in the wrong direction?</p> <p>If you don't want to visit the codepen link, code below:</p> <pre><code>const testFetch = fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json') .then(response =&gt; response.json()) .then((quote) =&gt; { return quote.quotes; }) // The console.log below logs &quot;The quote is [quote as a string]&quot; to the console const testVar = async () =&gt; { const quoteArr = await testFetch; console.log(&quot;The quote is &quot;, quoteArr[0].quote); return quoteArr[0].quote; }; let myQuote = testVar(); // This logs &quot;Is my quote variable working? [Promise pending]&quot; to the console console.log(&quot;Is my quote variable working? + &quot;, myQuote) </code></pre>
[ { "answer_id": 74238631, "author": "Yuloskov Artyom", "author_id": 20359923, "author_profile": "https://Stackoverflow.com/users/20359923", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\n\nconst App = () => {\n const [quotes, setQuotes] =...
2022/10/28
[ "https://Stackoverflow.com/questions/74238491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20359726/" ]
74,238,518
<p>I have the following text:</p> <blockquote> <p>This is a test ::a. MODE 3 within 7 hours,</p> <p>::b. MODE 4 within 13 hours, and</p> <p>::c. MODE 5 within 37 hours</p> <p>:: My Test</p> </blockquote> <p>And the following RegEx pattern:</p> <pre><code>(?&lt;=^::[A-z ])(.*?)(?=$) </code></pre> <p>Testing on here: <a href="https://regex101.com/r/w1f0Dn/1" rel="nofollow noreferrer">https://regex101.com/r/w1f0Dn/1</a></p> <p>It identifies the results that I need correctly (not the first line as it should). However, I'm trying to include the first character as part of the match for the results.</p> <p>Example: the <code>::b. MODE</code> line finds the line, but it's not including the b as part of the match. I need the final match to be <code>b. MODE 4 within 13 hours, and</code> vs <code>.MODE 4 within 13 hours, and</code> Is there a way to do this?</p>
[ { "answer_id": 74238631, "author": "Yuloskov Artyom", "author_id": 20359923, "author_profile": "https://Stackoverflow.com/users/20359923", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\n\nconst App = () => {\n const [quotes, setQuotes] =...
2022/10/28
[ "https://Stackoverflow.com/questions/74238518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337315/" ]
74,238,540
<p>I have an application with the following code:</p> <pre><code>string passedValue = &quot;5&quot;; results = db.procedure1 .Where(c =&gt; c.User.Contains(passedValue)) .OrderBy(o =&gt; o.User).ToList(); </code></pre> <p>The data in the <code>Users</code> column looks like this:</p> <pre><code> 05621 18763 58763 98599 </code></pre> <p>When I run the code, the resulting list contains 05621, 58763, and 98599</p> <p>Instead of a <code>Contains</code>, I would like to implement a <code>Like</code>. In other words, I want to retrieve each data record where <code>User is LIKE &quot;5%&quot;</code>.</p> <p>The resulting list should be:</p> <pre><code> 58763 </code></pre> <p>How would I accomplish this?</p> <p>Thanks!</p>
[ { "answer_id": 74238631, "author": "Yuloskov Artyom", "author_id": 20359923, "author_profile": "https://Stackoverflow.com/users/20359923", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\n\nconst App = () => {\n const [quotes, setQuotes] =...
2022/10/28
[ "https://Stackoverflow.com/questions/74238540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586807/" ]
74,238,545
<p>Can someone help me, my code was working fine until I put a loop that checks and deletes an array if it includes &quot;0.00000000&quot; by the second index, it doesn't work and sometimes writes &quot;list index out of range&quot; what's the problem? Thank you in advance, and here is my code:</p> <pre><code>parse = json.loads(message) sum = len(parse[&quot;b&quot;]) for x in range(sum): if (parse[&quot;b&quot;][x][1] == &quot;0.00000000&quot;): del parse[&quot;b&quot;][x] </code></pre> <p>My json:</p> <pre><code>{ &quot;U&quot;:26450991840, &quot;u&quot;:26450991976, &quot;b&quot;:[ [ &quot;20640.59000000&quot;, &quot;0.00000000&quot; ], [ &quot;20640.15000000&quot;, &quot;0.08415000&quot; ], [ &quot;20640.14000000&quot;, &quot;0.05144000&quot; ], [ &quot;20640.13000000&quot;, &quot;0.00519000&quot; ], [ &quot;20640.12000000&quot;, &quot;0.00000000&quot; ], [ &quot;20640.11000000&quot;, &quot;0.00000000&quot; ], [ &quot;20640.10000000&quot;, &quot;0.00000000&quot; ] ] } </code></pre> <p>I tried to make a script that checks all the json string converting it in dictionary by using python library and deleting all the arrays containing &quot;0.00000000&quot;</p>
[ { "answer_id": 74238631, "author": "Yuloskov Artyom", "author_id": 20359923, "author_profile": "https://Stackoverflow.com/users/20359923", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\n\nconst App = () => {\n const [quotes, setQuotes] =...
2022/10/28
[ "https://Stackoverflow.com/questions/74238545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20228343/" ]
74,238,572
<p>I'm just learning java and working on a homework problem. Our assignment was two read two-word lists into arrays and then combine them into one ArrayList alternating the words in the list. e.g. L1[0], L2[0], L1[1], L2[1], etc.</p> <p>I've got my code almost running EXCEPT if the word lists are not exactly the same length, I either leave off the last words in the long list or get an out-of-bounds index for the shorter list. I know there must be an obvious solution I haven't thought of. Thanks for your help!</p> <p>Here is the code I've written:</p> <pre><code>public class ArrayMixer { public static void main (String[] args){ Scanner scnr= new Scanner(System.in); // set up scanner // Initialize variables to capture user inputs String firstLine; String secondLine; //collect user input for the first list System.out.println(&quot;Please enter the first word list:&quot;); // prompt user for first list firstLine= scnr.nextLine(); String[] firstArray= firstLine.split(&quot; &quot;); // creates array to store first line split by spaces //System.out.println(firstLine);//FIXME COMMENT OUT AFTER TESTING //System.out.println(Arrays.toString(firstArray));//FIXME COMMENT OUT AFTER TESTING //collect user input for the second list System.out.println(&quot;Please enter the second word list:&quot;);// prompt user for second list secondLine= scnr.nextLine();// String[] secArray= secondLine.split(&quot; &quot;);//create array to store second list split by spaces //System.out.println(secondLine);//FIXME COMMENT OUT //System.out.println(Arrays.toString(secArray)); //FIXME COMMENT OUT //Create an array list called mixList to store combination of list 1 and 2 ArrayList &lt;String&gt; mixList = new ArrayList&lt;String&gt;(); // need to find out size of two lists put together int mixSize= (firstArray.length + secArray.length); System.out.println(mixSize); //HERE IS MY PROBLEM I've replace secArray.length w/ mxSize, and firstArray.length NO DICE for (int i=0; i&lt; secArray.length; ++i) {//FIXME NEED TO FIGURE OUT HOW TO GET THE LOOP // NOT GO OUT OF BOUNDS mixList.add(firstArray[i]); mixList.add(secArray[i]); } //print new list to output for (int i=0; i&lt; mixList.size(); ++i) { String tempWord=mixList.get(i); System.out.println(tempWord); } } } </code></pre> <p>I've tried using the length of the two lists combined and the length of the longer list-&gt; index out of bounds, the shorter list- last words of the longer list left off because the loop never gets to their index.</p> <p>Is there some sort of special arrayList for loop I can use?</p>
[ { "answer_id": 74238841, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 1, "selected": false, "text": " List<Integer> evens = List.of(2, 4, 6, 8, 10, 12);\n List<Integer> odds = List.of(1, 3, 5);\n List<Integer> combined = ...
2022/10/28
[ "https://Stackoverflow.com/questions/74238572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20193201/" ]
74,238,574
<p>e.g.</p> <pre class="lang-ml prettyprint-override"><code>let expect_raises f exc = try f () with | exc -&gt; &quot;Expected error raised&quot; | e -&gt; &quot;Unexpected error raised&quot; in expect_raises (fun () -&gt; raise Not_found) Not_found (* &quot;Expected&quot; *) expect_raises (fun () -&gt; raise Invalid_argument &quot;bad&quot;) Not_found (* &quot;Unexpected&quot; *) </code></pre> <p>But this doesn't work because I can't pattern match on the <code>exc</code> arg, it just becomes the pattern variable.</p> <p>Is there some way to do this?</p>
[ { "answer_id": 74238778, "author": "Jeffrey Scofield", "author_id": 821679, "author_profile": "https://Stackoverflow.com/users/821679", "pm_score": 3, "selected": true, "text": "let expect_raises f exc =\n try f ()\n with e ->\n if e = exc then \"Expected error raise\"\n else...
2022/10/28
[ "https://Stackoverflow.com/questions/74238574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202168/" ]
74,238,575
<p>I used npm to install <strong>appium 2.0.0-beta.46.</strong> After that I installed appium 1.22, but the appium -v still shows <strong>2.0.0-beta.46.</strong></p> <p>So I tried various options</p> <ul> <li><p>npm uninstall -g appium@2.0.0-beta.46</p> </li> <li><p>sudo npm uninstall -g appium@2.0.0-beta.46</p> </li> <li><p>sudo npm uninstall -g appium@beta</p> </li> <li><p>sudo npm uninstall -g appium@next Plus</p> </li> <li><p>npm cache clean --force But still, I am getting <strong>$ appium -v 2.0.0-beta.46</strong></p> </li> </ul> <p>When I did <strong>$which appium,</strong> I get <em>/usr/local/bin/appium</em></p> <p>I rebooted the system twice, but no use. What is the best way to do the uninstall the 2.0.0-beta.46 and go back to 1.22 ?</p> <p>Appreciate the help.</p>
[ { "answer_id": 74238778, "author": "Jeffrey Scofield", "author_id": 821679, "author_profile": "https://Stackoverflow.com/users/821679", "pm_score": 3, "selected": true, "text": "let expect_raises f exc =\n try f ()\n with e ->\n if e = exc then \"Expected error raise\"\n else...
2022/10/28
[ "https://Stackoverflow.com/questions/74238575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3780373/" ]
74,238,583
<p>Why must I state the table I'm referring to TWICE when using a join on a query?</p> <pre><code>select table1.name from table1 inner join table2 on etc ... </code></pre>
[ { "answer_id": 74238668, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "name" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74238583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18547376/" ]
74,238,584
<p>I am attempting to use a <code>PutItemRequest</code> to insert records into a DynamoDB table, however I do not want the insert to succeed when certain values on the inserted item already exist on other items.</p> <p>Here is the code for the request:</p> <pre><code>var req = PutItemRequest.builder() .tableName(TABLE_NAME) .item(getAllValues(settings)) .conditionExpression(&quot;attribute_not_exists(#&quot; + MAC_ADDRESS + &quot;) AND attribute_not_exists(#&quot; + REGISTRATION_CODE + &quot;)&quot;) .expressionAttributeNames(Map.of(&quot;#&quot; + MAC_ADDRESS, MAC_ADDRESS, &quot;#&quot; + REGISTRATION_CODE, REGISTRATION_CODE)) .build(); </code></pre> <p>The table already contains an item with a mac address of '000000000000' so I would expect the above to fail when trying to insert another item with the same mac address, but the insert succeeds.</p> <p>What am I doing wrong here? Both MAC_ADDRESS and REGISTRATION_CODE are GSI's.</p>
[ { "answer_id": 74238668, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "name" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74238584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369449/" ]
74,238,590
<p>How can I add random character from <code>[A-Za-z0-9]</code> <code>/</code> or <code>-</code> to a string every second character? e.g. input:</p> <pre><code>Hello_world! </code></pre> <p>output:</p> <pre><code>H3e7l2l-o2_aWmocr9l/db!s </code></pre> <p>Edit: Here is what I've tried, however without the line below the one marked <code>Here</code> that throws an error</p> <p><code>Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in...</code>.</p> <p>l guess it's because a fragment of $char is not an array. After l'd added the line below <code>Here</code> to &quot;convert&quot; the string to array another error appeared:</p> <p><code>Uncaught TypeError: str_repeat(): Argument #1 ($string) must be of type string, array given in...</code></p> <pre class="lang-php prettyprint-override"><code>&lt;?php $string = &quot;Hello_World!&quot;; $length = strlen($string); $string = str_split($string, 2); $chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-&quot;; //Here $chars = (is_array($chars)) ? $chars : [$chars]; for($i = 0; $i &lt; ($length / 2); $i++){ $char = substr(str_shuffle(str_repeat($chars, 1)), 0, 1); $added = implode($string[$i], $char); } echo $string; ?&gt; </code></pre>
[ { "answer_id": 74238668, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "name" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74238590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17349345/" ]
74,238,636
<p>I work with a terminal and often i have to do it fast. Sometimes, rarely, i need to prove a point by looking at a terminal output from yesterday, for example.</p> <p>I need my terminal entries to be saved in a text file and instead of copying and pasting the terminal output with my mouse, i want to practice C a bit (since apparently, i haven't done it much)</p> <p>Long story, short: I want my terminal output to be saved into a text file in the most automated way possible.</p>
[ { "answer_id": 74238668, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "name" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74238636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360149/" ]
74,238,648
<p>I have 3 arrays key_1, key_2, key_3 they each have 2 values that serve as x &amp; y coordinates. When I run the code I expect 9 circles of 3 different colours but instead the colours get mixed up. I dont know why or how to fix it, any clues</p> <pre><code>let key_1 = [], key_2 = [], key_3 = []; function setup() { createCanvas(790, 800); for (let i = 0; i &lt; 5; i++) { let x = random(0, width); let y = random(0, height); key_1.push([i, x, y]); }; for (let i = 0; i &lt; 3; i++) { let x = random(0, width); let y = random(0, height); key_2.push([i, x, y]); }; for (let i = 0; i &lt; 3; i++) { let x = random(0, width); let y = random(0, height); key_3.push([i, x, y]); }; }; function draw() { background(0); for (let i = 0; i &lt; 5; i++) { //expect 3 red circles, I'll get 2 red circles and 1 either green or blue ellipse(key_1[i][1], key_1[i][2], 5, 5); fill('rgba(100,0,0,1)'); noStroke() }; for (let i = 0; i &lt; 3; i++) { //expect 3 green circles, I'll get 2 green circles and 1 either green or blue ellipse(key_2[i][1], key_2[i][2], 10, 10); fill('rgba(0,100,0,1)'); noStroke(); }; for (let i = 0; i &lt; 3; i++) { //expect 3 blue circles, I'll get 2 blue circles and 1 either green or blue ellipse(key_3[i][1], key_3[i][2], 30, 30); fill('rgba(0,0,100,1)'); noStroke(); }; }; </code></pre>
[ { "answer_id": 74238668, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "name" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74238648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19961842/" ]
74,238,669
<p>AWK has the match(s, r [, a]) function which according to the manual is capable of recording all occuring patterns into array &quot;a&quot;:</p> <p>...If array a is provided, a is cleared and then elements 1 through n are filled with the portions of s that match the corresponding parenthesized subexpression in r. The 0'th element of a contains the portion of s matched by the entire regular expression r. Subscripts a[n, &quot;start&quot;], and a[n, &quot;length&quot;] provide the starting index in the string and length respectively, of EACH matching substring.</p> <p>I expect that the following line:</p> <p><code>echo 123412341234 | awk '{match($0,&quot;1&quot;,arr); print arr[0] arr[1] arr[2];)</code>'</p> <p>prints 111</p> <p>But in fact &quot;match&quot; ignores all other matches except the first one.</p> <p>Could please someone tell me please what is the proper syntax here to populate &quot;arr&quot; with all occurrences of &quot;1&quot;?</p>
[ { "answer_id": 74238739, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 3, "selected": false, "text": "match" }, { "answer_id": 74239303, "author": "Daweo", "author_id": 10785975, "author_profile": "h...
2022/10/28
[ "https://Stackoverflow.com/questions/74238669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15077946/" ]
74,238,693
<p>i have grid container with 3 columns. However I only have 5 contents.</p> <p>right now it looks like this:</p> <pre><code>| 1 | 2 | 3 | | 4 | 5 | </code></pre> <p>I want to center the two remaining bottom div contents:</p> <pre><code>| 1 | 2 | 3 | | 4 | 5 | </code></pre> <p>Is this achievable or should I just create separate column for that? <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 5px; } span { border: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;span&gt;1&lt;/span&gt; &lt;span&gt;2&lt;/span&gt; &lt;span&gt;3&lt;/span&gt; &lt;span&gt;4&lt;/span&gt; &lt;span&gt;5&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74238739, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 3, "selected": false, "text": "match" }, { "answer_id": 74239303, "author": "Daweo", "author_id": 10785975, "author_profile": "h...
2022/10/28
[ "https://Stackoverflow.com/questions/74238693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14820590/" ]
74,238,703
<p>This self-answered question addresses the following scenario:</p> <p>How can I write a PowerShell script to check if a computer is a domain controller or not?</p>
[ { "answer_id": 74238710, "author": "Robert Karamagi", "author_id": 9467450, "author_profile": "https://Stackoverflow.com/users/9467450", "pm_score": 0, "selected": false, "text": "$listofcomputers = Import-CSV -Path \"C:\\computers_list.csv\"\n\nforeach ($computerobject in $listofcompute...
2022/10/28
[ "https://Stackoverflow.com/questions/74238703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9467450/" ]
74,238,709
<p>What i want to do is a code which accepts letters and just stops when a vowel is typed in console. My problem is that yes it does that, but it doesn't stop asking for more letters after the vowel is introduced.</p> <p>Here is what i have:</p> <pre><code>using System; namespace ConsoleApp9 { class Program { static void Main(string[] args) { char cha; do { Console.WriteLine(&quot;Insert letter: &quot;); cha = char.Parse(Console.ReadLine()); if (cha == 'a' | cha == 'e' | cha == 'i' | cha == 'o' | cha == 'u') { Console.WriteLine(&quot;We are sorry, ¡the program ends here!&quot;); Console.ReadLine(); } } while (cha != 'a' | cha != 'e' | cha != 'i' | cha != 'o' | cha != 'u') ; } } } </code></pre>
[ { "answer_id": 74239313, "author": "Rikudou En Sof", "author_id": 9337608, "author_profile": "https://Stackoverflow.com/users/9337608", "pm_score": -1, "selected": false, "text": "int n = 5;\nwhile (++n < 6) \n{\nConsole.WriteLine(\"Current value of n is {0}\", n);\n}\n" }, { "an...
2022/10/28
[ "https://Stackoverflow.com/questions/74238709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20114716/" ]
74,238,801
<p>I have the following 3 variables:</p> <pre><code>Year=2022 Month=09 Filename=asd </code></pre> <p>And I need to create the following path:</p> <pre><code>&quot;C:\Documents\2022\09_September\asd.xlsx&quot; </code></pre> <p>How can I create that path including the backslash symbols?</p>
[ { "answer_id": 74238819, "author": "KillerRebooted", "author_id": 18554284, "author_profile": "https://Stackoverflow.com/users/18554284", "pm_score": 2, "selected": false, "text": "Year=2022\nMonth='09'\nFilename='asd'\n\npath = fr\"C:\\Documents\\{Year}\\{Month}_September\\{Filename}.xl...
2022/10/28
[ "https://Stackoverflow.com/questions/74238801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11789082/" ]
74,238,836
<p>My flutter app, which was able to build for many months, apparently can't build anymore, and I didn't make any build related changes.</p> <p><strong>How I build my app:</strong></p> <pre><code>flutter build apk --split-per-abi prod -t lib/main.dart --no-sound-null-safety </code></pre> <p><strong>Where do i build my app:</strong></p> <ol> <li>Inside Android Emulator terminal</li> <li>In macos terminal</li> </ol> <p><strong>Error log</strong></p> <pre><code>[01:14:40]: ▸ FAILURE: Build failed with an exception. [01:14:40]: ▸ * What went wrong: [01:14:40]: ▸ Execution failed for task ':amplify_api_android:mergeReleaseResources'. [01:14:40]: ▸ &gt; Could not resolve all files for configuration ':amplify_api_android:releaseRuntimeClasspath'. [01:14:40]: ▸ &gt; Could not resolve io.flutter:flutter_embedding_release:1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f. [01:14:40]: ▸ Required by: [01:14:40]: ▸ project :amplify_api_android [01:14:40]: ▸ project :amplify_api_android &gt; project :amplify_core [01:14:40]: ▸ &gt; Could not resolve io.flutter:flutter_embedding_release:1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f. [01:14:40]: ▸ &gt; Could not get resource 'https://storage.googleapis.com/download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f/flutter_embedding_release-1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f.pom'. [01:14:40]: ▸ &gt; Could not GET 'https://storage.googleapis.com/download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f/flutter_embedding_release-1.0.0-3ad69d7be3a7231aab5525db322fc699f098315f.pom'. [01:14:40]: ▸ &gt; PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target [01:14:40]: ▸ * Try: [01:14:40]: ▸ Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. [01:14:40]: ▸ * Get more help at https://help.gradle.org [01:14:40]: ▸ BUILD FAILED in 32s </code></pre> <p>It keeps on throwing <code>&gt; PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</code></p> <p>But this file, i'm able to download when I run thru the browser.</p> <p><strong>What I've done so far</strong></p> <ol> <li>Invalidated android studio cache</li> <li>Delete flutter cache</li> <li>flutter clean &amp;&amp; flutter pub get</li> <li>flutter channel stable &amp;&amp; flutter clean &amp;&amp; flutter pub get</li> </ol>
[ { "answer_id": 74238819, "author": "KillerRebooted", "author_id": 18554284, "author_profile": "https://Stackoverflow.com/users/18554284", "pm_score": 2, "selected": false, "text": "Year=2022\nMonth='09'\nFilename='asd'\n\npath = fr\"C:\\Documents\\{Year}\\{Month}_September\\{Filename}.xl...
2022/10/28
[ "https://Stackoverflow.com/questions/74238836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3644938/" ]
74,238,878
<p>Basically what I'm trying to get at is below my program will generate a shuffle between the numbers in the tuple below, for example if it generates <code>[3,2,2,4,5,6]</code>, then the program would add up the values of 1 since there's no ones generated it would print as 0, then it would add up the values of 2 since there's 2 twos it would add up the value to 4 and print out a 4 etc etc.</p> <pre><code>from random import shuffle def make_roll() -&gt; tuple: roll_number = [1,2,3,4,5,6] shuffle(roll_number) print(f'Rolling the dice...{roll_number}') </code></pre>
[ { "answer_id": 74238996, "author": "Rodrigo Guzman", "author_id": 13315525, "author_profile": "https://Stackoverflow.com/users/13315525", "pm_score": -1, "selected": false, "text": "numbers = [3,2,2,4,5,6]\nfor i in range(1,max(numbers)+1):\n n = 0\n for j in numbers:\n if i...
2022/10/28
[ "https://Stackoverflow.com/questions/74238878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178041/" ]
74,238,883
<p>So, I'm trying to show an Amazon country API to my React-Select component and I've tried to do this in many different ways, but I would only get as result a blank page or a white list on my Select component</p> <p>The code below has only the Axios method to call the API.</p> <p>What Should I do so I can show the API data on the Select component?</p> <p>Here's my Form.jsx component:</p> <pre><code>import { useState, useEffect } from 'react'; import '../App.css'; import Form from 'react-bootstrap/Form'; import Col from 'react-bootstrap/Col'; import Row from 'react-bootstrap/Row'; import Button from 'react-bootstrap/Button'; import Select from 'react-select'; import Axios from 'axios'; function Forms() { const [countries, setCountry] = useState([]) Axios.get(`https://amazon-api.sellead.com/country`) .then(res =&gt; { const countries = res.data; console.log(countries) }) return ( &lt;Form&gt; &lt;Row className=&quot;mb-3&quot;&gt; &lt;Form.Group as={Col} controlId=&quot;formGridEmail&quot;&gt; &lt;Form.Control type=&quot;text&quot; name = &quot;name&quot; placeholder=&quot;Nome&quot; /&gt; &lt;/Form.Group&gt; &lt;Form.Group as={Col} controlId=&quot;formGridPassword&quot;&gt; &lt;Form.Control type=&quot;email&quot; name = &quot;email&quot; placeholder=&quot;E-mail&quot; /&gt; &lt;/Form.Group&gt; &lt;Form.Group as={Col} controlId=&quot;formGridPassword&quot;&gt; &lt;Form.Control type=&quot;text&quot; name = &quot;cpf&quot; placeholder=&quot;CPF&quot; /&gt; &lt;/Form.Group&gt; &lt;Form.Group as={Col} controlId=&quot;formGridPassword&quot;&gt; &lt;Form.Control type=&quot;text&quot; name = &quot;tel&quot; placeholder=&quot;Telefone&quot; /&gt; &lt;/Form.Group&gt; &lt;Form.Label&gt;País&lt;/Form.Label&gt; &lt;Form.Group as={Col} controlId=&quot;formGridPassword&quot;&gt; &lt;Select /&gt; &lt;/Form.Group&gt; &lt;Form.Label&gt;Cidade&lt;/Form.Label&gt; &lt;Form.Group as={Col} controlId=&quot;formGridPassword&quot;&gt; &lt;br/&gt; &lt;Select /&gt; &lt;/Form.Group&gt; &lt;Button variant=&quot;primary&quot; type=&quot;submit&quot;&gt; Enviar &lt;/Button&gt; &lt;/Row&gt; &lt;/Form&gt; ); } export default Forms; </code></pre>
[ { "answer_id": 74238996, "author": "Rodrigo Guzman", "author_id": 13315525, "author_profile": "https://Stackoverflow.com/users/13315525", "pm_score": -1, "selected": false, "text": "numbers = [3,2,2,4,5,6]\nfor i in range(1,max(numbers)+1):\n n = 0\n for j in numbers:\n if i...
2022/10/28
[ "https://Stackoverflow.com/questions/74238883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18466712/" ]
74,238,892
<p>I have a 1d numpy array and a list of values to remove (not indexes), how can I modify this code so that the actual values not indexes are removed</p> <pre><code>import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) values_to_remove = [2, 3, 6] new_a = np.delete(a, values_to_remove) </code></pre> <p>So what I want to delete is the values 2,3,6 NOT their corresponding index. Actually the list is quite long so ideally I should be able to pass the second parameter as a list</p> <p>So the final array should actually be = 1, 4, 5, 7, 8, 9</p>
[ { "answer_id": 74238929, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "numpy.isin" }, { "answer_id": 74238939, "author": "I'mahdi", "author_id": 1740577, "author_prof...
2022/10/28
[ "https://Stackoverflow.com/questions/74238892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7824826/" ]
74,238,896
<p>I have a text file with a bunch of serial numbers and they're supposed to be 16 characters long. But some of the records were damaged and are 13 characters long. I want to add 3 zeros at the beginning of every record that has 13 characters long.</p> <p><em>Note: The serial numbers doesn't start at the beginning of the line, they all start at the column 15 of every line.</em></p> <p>My file currently looks like this:</p> <pre><code>1:CCCC:CC: :C:**0000000999993**: :CCC: : 1:CCCC:CC: :C:**0000000999994**: :CCC: : 1:CCCC:CC: :C:**0000000999995**: :CCC: : 1:CCCC:CC: :C:**0000000000170891**: :CCC: : 1:CCCC:CC: :C:**0000000000170892**: :CCC: : 1:CCCC:CC: :C:**0000000000170893**: :CCC: : </code></pre> <p>And the output should be:</p> <pre><code>1:CCCC:CC: :C:**0000000000999993**: :CCC: : 1:CCCC:CC: :C:**0000000000999994**: :CCC: : 1:CCCC:CC: :C:**0000000000999995**: :CCC: : 1:CCCC:CC: :C:**0000000000170891**: :CCC: : 1:CCCC:CC: :C:**0000000000170892**: :CCC: : 1:CCCC:CC: :C:**0000000000170893**: :CCC: : </code></pre> <p>This is the code I made to get the records that are shortened:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash i=1 for OUTPUT in $*(cut -c15-30 file.txt) do if [[ ${#OUTPUT} == 13 ]] then echo $OUTPUT echo $i i=$((i+1)) fi done </code></pre> <p><em>The txt file has more than 50,000 records so I can't change them manually.</em></p>
[ { "answer_id": 74239182, "author": "tink", "author_id": 1394729, "author_profile": "https://Stackoverflow.com/users/1394729", "pm_score": 0, "selected": false, "text": ":" }, { "answer_id": 74239185, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile":...
2022/10/28
[ "https://Stackoverflow.com/questions/74238896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069611/" ]
74,238,904
<p>I have the problem for this situation. I want to print like console.log did in the screen for react native<a href="https://i.stack.imgur.com/bF9bi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bF9bi.png" alt="enter image description here" /></a></p> <p>`</p> <pre><code>const dString = text; const days = 30; let [day, month, year] = dString.split('/'); // month - 1 as month in the Date constructor is zero indexed const now = new Date(year, month - 1, day); let loopDay = now; for (let i = 0; i &lt;= days; i++) { loopDay.setDate(loopDay.getDate() + 6); console.log ('Day: ' + loopDay); } </code></pre> <p>here's my code and I want to print in return of function in react-native so result of looping can show on my screen`</p>
[ { "answer_id": 74239182, "author": "tink", "author_id": 1394729, "author_profile": "https://Stackoverflow.com/users/1394729", "pm_score": 0, "selected": false, "text": ":" }, { "answer_id": 74239185, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile":...
2022/10/28
[ "https://Stackoverflow.com/questions/74238904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360373/" ]
74,238,921
<p>I am encountering a very bizarre problem with my <strong>FutureBuilder</strong> on my home screen that only shows up when I've navigated to other pages and then it keeps reloading (I've verified by putting breakpoints on my home screen).</p> <p>I'm fairly certain this is not how FutureBuilders are supposed to act, or even <em>why</em> it's reloading in a loop <em>only</em> away from my home screen?</p> <p><strong>CONOPS:</strong></p> <ol> <li>I load my app</li> <li>the FutureBuilder on the home screen works as expected. It receives its futures, builds the app, and that's that</li> <li>I navigate to another screen</li> <li>the FutureBuilder on my home screen suddenly starts firing again and won't stop</li> </ol> <p>My home screen code, which is a <code>Stateful</code> widget:</p> <pre class="lang-dart prettyprint-override"><code>@override Widget build(BuildContext context) { generateLayout(); // Assigns padding/spacing based on screen size return MaterialApp( title: 'Home Screen', // This builder is here for routes needing an up-the-tree context home: Builder(builder: (context) { Future.delayed(Duration.zero, () { // Shows disclosure on location usage return showLocationDisclosureDetermination(context); }); return Scaffold( appBar: AppBar( title: startScreenTitle('Location Alerts'), ), body: FutureBuilder( future: initFunctions(), builder: (BuildContext context, AsyncSnapshot&lt;bool&gt; snapshot) { if (snapshot.hasData) { return startScreenBody(context); } else { return const Center( child: CircularProgressIndicator( color: Color(s_darkSalmon), )); } }), ); }), ); } </code></pre> <p>My <code>initFunctions()</code> code:</p> <pre class="lang-dart prettyprint-override"><code>Future&lt;bool&gt; initFunctions() async { await sharedPreferencesLookUp(); // Getting Shared Preferences vars await databaseLookUp(); // Doing a Firestore query await locationServicesLookUp(); // Getting location services info return true; } </code></pre> <p>And lastly, how I navigate away from the home screen:</p> <pre class="lang-dart prettyprint-override"><code>return ElevatedButton( onPressed: () async { Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; const SpecificScreen()), ); }, child: Text('Go Right')); </code></pre>
[ { "answer_id": 74239182, "author": "tink", "author_id": 1394729, "author_profile": "https://Stackoverflow.com/users/1394729", "pm_score": 0, "selected": false, "text": ":" }, { "answer_id": 74239185, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile":...
2022/10/28
[ "https://Stackoverflow.com/questions/74238921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8846093/" ]
74,238,933
<p>I am trying to implement a simple DropdownMenu. Everything works correct but when I click the first item , ripple effect does not cover DropDownMenu on the top completely and the same is happening for the last item.</p> <p>Here is an image of what is happening :</p> <p><a href="https://i.stack.imgur.com/u3Op1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3Op1.jpg" alt="enter image description here" /></a></p> <p>Here is my code :</p> <pre><code> MaterialTheme(shapes=MaterialTheme.shapes.copy(medium = RoundedCornerShape(16.dp))) { DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, ) { DropdownMenuItem(onClick = { Toast.makeText( context, &quot;Refresh Clicked&quot;, Toast.LENGTH_SHORT ).show() } , ) { Text(&quot;Refresh&quot;) } DropdownMenuItem(onClick = { Toast.makeText( context, &quot;Setting Clicked&quot;, Toast.LENGTH_SHORT ).show() }) { Text(&quot;Settings&quot;) } Divider() DropdownMenuItem(onClick = { Toast.makeText( context, &quot;Details Clicked&quot;, Toast.LENGTH_SHORT ).show() }) { Text(&quot;Details&quot;) } } </code></pre>
[ { "answer_id": 74240967, "author": "Mike", "author_id": 2004073, "author_profile": "https://Stackoverflow.com/users/2004073", "pm_score": 1, "selected": false, "text": "Column(\n modifier = modifier\n .padding(vertical = DropdownMenuVerticalPadding)\n .width(...
2022/10/28
[ "https://Stackoverflow.com/questions/74238933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17948179/" ]
74,238,938
<p>I am trying to work with a hover event inline in react as a hook. I am really close, but it's activating ALL items in the <code>.map</code>. I am trying to get it to only fire on the specific <code>&lt;a&gt;</code> element that is being hovered on ..</p> <p>It's a very basic setup:</p> <pre><code>const data = [ {id: 1, text: 'Inbox Item 1 -- Subject -- Short description', date: '1.03.2016'}, {id: 2, text: 'Inbox Item 2 -- Subject -- Short description', date: '23.01.2017'}, {id: 3, text: 'Inbox Item 3 -- Subject -- Short description', date: '12.01.2022'} ]; const inboxItemStyle = ({hover}) =&gt; ({ display: &quot;block&quot;, borderBottom: '1px solid #CCC', backgroundColor: hover ? '#EEF' : '#FFF', padding:&quot;15px&quot;, }) function Inbox() { const [hover, setHover] = useState(false); return ( &lt;div className=&quot;list-group&quot;&gt; { data.map((item) =&gt; &lt;SwipeToDelete key={item.id}&gt; &lt;a style={inboxItemStyle({hover})} onPointerOver={()=&gt; setHover(true)} onPointerOut={() =&gt; setHover(false)} &gt; &lt;h4 className=&quot;list-group-item-heading&quot;&gt;{item.date}&lt;/h4&gt; &lt;p className=&quot;list-group-item-text&quot;&gt;{item.text}&lt;/p&gt; &lt;/a&gt; &lt;/SwipeToDelete&gt; ) } &lt;/div&gt; ); } export default Inbox; </code></pre> <p>This is what's happening:</p> <p><a href="https://i.stack.imgur.com/foEnz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/foEnz.png" alt="enter image description here" /></a></p> <p>This is my expected result:</p> <p><a href="https://i.stack.imgur.com/KjNWx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KjNWx.png" alt="enter image description here" /></a></p> <p>Why is it enabling hover on ALL <code>&lt;a&gt;</code> elements? Isn't the <code>.map</code> separating them into individual objects? Where am I going wrong?</p> <p><strong>I tried using index based hooks as well from <a href="https://stackoverflow.com/questions/67501705/handle-mouse-hover-events-over-a-mapped-array-in-react">THIS QUESTION</a></strong></p> <p>But the hover ceases to work altogether with this functionality. What Am I doing wrong?</p> <pre><code>const [hover, setHover] = useState(-1); const showHandler = (i)=&gt;{ setHover(i); } const hideHandler=()=&gt;{ setHover(-1) } return ( &lt;div className=&quot;list-group&quot;&gt; { data.map((item, i) =&gt; ( &lt;SwipeToDelete key={item.id}&gt; &lt;a style={setInboxItemStyle({hover})} onMouseLeave={hideHandler} onMouseEnter={()=&gt;showHandler(i)} &gt; &lt;h4 className=&quot;list-group-item-heading&quot;&gt;{item.date}&lt;/h4&gt; &lt;p className=&quot;list-group-item-text&quot;&gt;{item.text}&lt;/p&gt; &lt;/a&gt; &lt;/SwipeToDelete&gt; )) } &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74240967, "author": "Mike", "author_id": 2004073, "author_profile": "https://Stackoverflow.com/users/2004073", "pm_score": 1, "selected": false, "text": "Column(\n modifier = modifier\n .padding(vertical = DropdownMenuVerticalPadding)\n .width(...
2022/10/28
[ "https://Stackoverflow.com/questions/74238938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1507691/" ]
74,238,944
<p>I'm trying to close and open an image on HTML with a click on a button but it's not working.</p> <p>There's my code:</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>.cover { position: sticky; display: flex; align-items: flex-start; height: 275.25px; width: 275.25px; } @keyframes closeCover { 0% { height: 275.25px; } 100% { height: 0px; } } .cover:active { animation: closeCover 1s linear forwards; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="cover"&gt; &lt;img src="./images/arrow.svg" alt="close cover" id="close"&gt; &lt;a href=""&gt;&lt;img src="./images/Fiure-de-vie.jpg" alt="cover" id="cover"&gt;&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm trying to close and open an image with HTML/CSS.</p>
[ { "answer_id": 74239421, "author": "tacoshy", "author_id": 14072420, "author_profile": "https://Stackoverflow.com/users/14072420", "pm_score": 0, "selected": false, "text": "label" }, { "answer_id": 74239435, "author": "mdabrowski", "author_id": 14748862, "author_prof...
2022/10/28
[ "https://Stackoverflow.com/questions/74238944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19801430/" ]
74,238,947
<p>I want the same effect on canvas as in this answer by <a href="https://stackoverflow.com/users/3877726/blindman67">Blindman67</a></p> <p><a href="https://stackoverflow.com/a/45755177/5651569">https://stackoverflow.com/a/45755177/5651569</a></p> <p>but with transparent background i.e. have the two lines commented out:</p> <pre><code> //background.ctx.fillStyle = &quot;white&quot;; //background.ctx.fillRect(0,0,w,h); </code></pre> <p>when you do that the smeared pixels get weird colors. How to achieve the original effect as if the white background is there but with transparent background?</p> <p>I would like a clean effect where transparent pixels get smeared into visible pixels</p> <p><a href="https://i.stack.imgur.com/Lh6jx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lh6jx.png" alt="enter image description here" /></a></p> <p>but I am getting strange dark colored pixels appearing on edges that get smeared further</p> <p><a href="https://i.stack.imgur.com/4yIKM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4yIKM.png" alt="enter image description here" /></a></p> <pre><code>&lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt; &lt;style&gt; canvas { position: absolute; top: 0px; left: 0px; } &lt;/style&gt; &lt;script&gt; &quot;use strict&quot;; var drawon_ctx = canvas.getContext(&quot;2d&quot;); //is our drawon var tmp_canvas = createCanvas(canvas.width, canvas.height); //is our tmp var tmp_ctx = tmp_canvas.ctx; // var brushSize = 64; var bs = 64; var bsh = bs / 2; var smudgeAmount = 0.25; // values from 0 none to 1 full // helpers var doFor = function doFor(count, cb) { var i = 0; while (i &lt; count &amp;&amp; cb(i++) !== true) { ; } }; // the ; after while loop is important don't remove var randI = function randI(min) { var max = arguments.length &gt; 1 &amp;&amp; arguments[1] !== undefined ? arguments[1] : min + (min = 0); return Math.random() * (max - min) + min | 0; }; // simple mouse var mouse = { x: 0, y: 0, button: false }; function mouseEvents(e) { mouse.x = e.pageX; mouse.y = e.pageY; mouse.button = e.type === &quot;mousedown&quot; ? true : e.type === &quot;mouseup&quot; ? false : mouse.button; } [&quot;down&quot;, &quot;up&quot;, &quot;move&quot;].forEach(function (name) { return document.addEventListener(&quot;mouse&quot; + name, mouseEvents); }); // brush gradient for feather var grad = drawon_ctx.createRadialGradient(bsh, bsh, 0, bsh, bsh, bsh); //center coords/ bsh is half of bs grad.addColorStop(0, &quot;black&quot;); grad.addColorStop(1, &quot;rgba(0,0,0,0)&quot;); var v_brush = createCanvas(bs); // our v_brush // creates an offscreen canvas function createCanvas(w) { var h = arguments.length &gt; 1 &amp;&amp; arguments[1] !== undefined ? arguments[1] : w; var c = document.createElement(&quot;canvas&quot;); c.width = w; c.height = h; c.ctx = c.getContext(&quot;2d&quot;); return c; } // get the brush from source ctx at x,y function brushFrom(tmp_ctx, x, y) { v_brush.ctx.globalCompositeOperation = &quot;source-over&quot;; v_brush.ctx.globalAlpha = 1; v_brush.ctx.drawImage(tmp_canvas, -(x - bsh), -(y - bsh)); // v_brush.ctx.drawImage(tmp_ctx.canvas, -(x - bsh), -(y - bsh)); v_brush.ctx.globalCompositeOperation = &quot;destination-in&quot;; v_brush.ctx.globalAlpha = 1; v_brush.ctx.fillStyle = grad; v_brush.ctx.fillRect(0, 0, bs, bs); } // short cut vars var w = canvas.width; var h = canvas.height; var cw = w / 2; // center var ch = h / 2; var globalTime; var lastX; var lastY; // update tmp_canvas is size changed function createBackground() { tmp_canvas.width = w; tmp_canvas.height = h; // tmp_ctx.fillStyle = &quot;white&quot;; // tmp_ctx.fillRect(0, 0, w, h); doFor(64, function () { tmp_ctx.fillStyle = &quot;rgb(&quot;.concat(randI(255), &quot;,&quot;).concat(randI(255), &quot;,&quot;).concat(randI( 255)); tmp_ctx.fillRect(randI(w), randI(h), randI(10, 100), randI(10, 100)); }); } // main update function function update(timer) { globalTime = timer; drawon_ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform drawon_ctx.globalAlpha = 1; // reset alpha if (w !== innerWidth || h !== innerHeight) { cw = (w = canvas.width = innerWidth) / 2; ch = (h = canvas.height = innerHeight) / 2; createBackground(); } else { drawon_ctx.clearRect(0, 0, w, h); } drawon_ctx.drawImage(tmp_canvas, 0, 0); // if mouse down then do the smudge for all pixels between last mouse and mouse now if (mouse.button) { v_brush.ctx.globalAlpha = smudgeAmount; var dx = mouse.x - lastX; var dy = mouse.y - lastY; var dist = Math.sqrt(dx * dx + dy * dy); for (var i = 0; i &lt; dist; i += 1) { var ni = i / dist; brushFrom(tmp_ctx, lastX + dx * ni, lastY + dy * ni); ni = (i + 1) / dist; tmp_ctx.drawImage(v_brush, lastX + dx * ni - bsh, lastY + dy * ni - bsh); } } else { v_brush.ctx.clearRect(0, 0, bs, bs); /// clear brush if not used } lastX = mouse.x; lastY = mouse.y; requestAnimationFrame(update); } requestAnimationFrame(update); </code></pre>
[ { "answer_id": 74244152, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "v_brush" }, { "answer_id": 74282503, "author": "Alsat", "author_id": 5651569, "author_profile": "...
2022/10/28
[ "https://Stackoverflow.com/questions/74238947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5651569/" ]
74,238,999
<p>I am using python <code>with open</code> to read a file.</p> <pre><code>with open('/Users/ks/Downloads/file name 1.pdf', 'rb') as data: print(data) &lt;_io.BufferedReader name='/Users/ks/Downloads/file name 1.pdf'&gt; </code></pre> <p>I am trying to rename the file to <code>file_name_1.pdf</code> before uploading. Is there a way to parse the file name from data and rename? I'd like to replace <code> </code> with <code>_</code>.</p>
[ { "answer_id": 74239071, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 1, "selected": false, "text": "import os\nfile_path = '/Users/kevalshah/Downloads/file name 1.pdf'\nos.rename(file_path, file_path.replace(' ',...
2022/10/28
[ "https://Stackoverflow.com/questions/74238999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380902/" ]
74,239,026
<p>Is there a better way to flat an array of arrays of integers? this solution is easy but I really don't know if it's time complexity is the best.</p> <pre class="lang-js prettyprint-override"><code>const list = (arr) =&gt; { //to avoid mutating the the entry data let newArr=[...arr] return newArr.flat().sort((a,b)=&gt;a-b) } // this logs [1,2,2,4,5,6,7,8] console.log( list([2,[1,5],4,2,[6,8,7]]) ) </code></pre> <p>I think maybe with reduce I can both flat the array and order it?</p> <p>I'm trying to get a better performance at my algorithm</p>
[ { "answer_id": 74239071, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 1, "selected": false, "text": "import os\nfile_path = '/Users/kevalshah/Downloads/file name 1.pdf'\nos.rename(file_path, file_path.replace(' ',...
2022/10/28
[ "https://Stackoverflow.com/questions/74239026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360455/" ]
74,239,041
<p><strong>Required output:</strong></p> <p><a href="https://i.stack.imgur.com/5Yc5G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Yc5G.png" alt="enter image description here" /></a></p> <p><strong>Current output:</strong></p> <p><a href="https://i.stack.imgur.com/vwrlp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vwrlp.png" alt="enter image description here" /></a></p> <p><strong>Demo:</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-css lang-css prettyprint-override"><code>.Form { background-color: rgb(198, 187, 197); } h2, h3 { color: rgb(67, 37, 70) }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section class="Form"&gt; &lt;h2&gt;Form&lt;/h2&gt; &lt;h3&gt;Name&lt;/h3&gt; &lt;form action="#"&gt; &lt;input type="text" placeholder="Your Name"&gt; &lt;h3&gt;E-mail&lt;/h3&gt; &lt;input type="email" placeholder="Your-mail"&gt; &lt;div&gt; &lt;textarea name="text" cols="30" rows="10" placeholder="Your massage"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button type="submit" class="btn"&gt;Send&lt;/button&gt; &lt;/form&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74239229, "author": "Franco Agustín Torres", "author_id": 20318366, "author_profile": "https://Stackoverflow.com/users/20318366", "pm_score": 2, "selected": true, "text": "body {\n margin: 0;\n}\n\n.my-form {\n background-color: rgb(230, 214, 210);\n color: rgb(0, 0, 0)...
2022/10/28
[ "https://Stackoverflow.com/questions/74239041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19788422/" ]
74,239,074
<p>I'm currently working on migrating our code from global sign package to go mongo-driver, not sure where should I use <code>context.TODO()</code> and <code>context.Background()</code>, it’s really confusing, I know both it returns non-nil empty, so should I use <code>context.Background()</code> in the main function &amp; <code>init()</code> functions? And use <code>context.TODO()</code> in other places? Can anyone help with this?</p> <p>Trying to check to see which param should I use <code>context.TODO()</code> or <code>context.Background()</code>.</p>
[ { "answer_id": 74239177, "author": "icza", "author_id": 1705598, "author_profile": "https://Stackoverflow.com/users/1705598", "pm_score": 2, "selected": false, "text": "context.Background()" }, { "answer_id": 74239191, "author": "Adrian", "author_id": 7426, "author_pr...
2022/10/28
[ "https://Stackoverflow.com/questions/74239074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8371709/" ]
74,239,084
<p>Yes, this question has been addressed many times here, but I can't find a solution to my specific use case.</p> <p>I have a function that hands back a tuple of latitude/longitude coordinates. I'd like to:</p> <ol> <li>prepend a city name to this tuple</li> <li>create a list out of #1</li> <li>append this list to an empty list</li> <li>repeat for each time the function is run</li> </ol> <p>For example:</p> <pre><code>from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent = 'MyApp') cities_list = ['New York', 'Los Angeles', 'Houston'] for city in cities_list: temp_list = [] city_coordinates = geolocator.geocode(city) latitude = city_coordinates.latitude longitude = city_coordinates.longitude list_element = list(city, latitude, longitude) temp_list.append(list_element) temp_list TypeError: list expected at most 1 argument, got 3 </code></pre> <p>This is what I'd like <code>temp_list</code> to look like:</p> <pre><code>[['New York', 40.7127281, -74.0060152], ['Los Angeles', 34.0536909, -118.242766], ['Houston', 29.7589382, -95.3676974]] </code></pre> <p>How would I do this?</p> <p>Thanks!</p>
[ { "answer_id": 74239108, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 0, "selected": false, "text": "list_element = list(city, latitude, longitude)\n" }, { "answer_id": 74239196, "author": "Serge Balle...
2022/10/28
[ "https://Stackoverflow.com/questions/74239084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18908491/" ]
74,239,093
<p>I was wondering how I could fix this issue I'm having with my code‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎</p> <p>if anyone could help me, I would be very grateful:‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎</p> <pre><code>class button(): def __init__(self, color, x, y, width, height, text=''): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text def draw(self, win, outline=None): # Call this method to draw the button on the screen if outline: pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0) pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0) if self.text != '': font = pygame.font.SysFont('comicsans', 60) text = font.render(self.text, 1, (0, 0, 0)) win.blit(text, ( self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2))) def isOver(self, pos): # Pos is the mouse position or a tuple of (x,y) coordinates if pos[0] &gt; self.x and pos[0] &lt; self.x + self.width: if pos[1] &gt; self.y and pos[1] &lt; self.y + self.height: return True return False def isOver(self, pos): # Pos is the mouse position or a tuple of (x,y) coordinates if pos[0] &gt; self.x and pos[0] &lt; self.x + self.width: if pos[1] &gt; self.y and pos[1] &lt; self.y + self.height: return True return False one = button((255,255,255),250,500, 90,90 ,'hi') def DRAW_WINDOW():WIN.blit(bg,(0,0))one.draw(WIN, (0,0,0))pygame.display.update() def main():run = True while run: for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: if one.isOver(pos): one.color = (255,0,0) else: one.color = (255,255,255) if event.type == pygame.MOUSEBUTTONDOWN: if one.isOver(pos): print('ow') if event.type == pygame.QUIT: run = False DRAW_WINDOW() quit() </code></pre>
[ { "answer_id": 74239108, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 0, "selected": false, "text": "list_element = list(city, latitude, longitude)\n" }, { "answer_id": 74239196, "author": "Serge Balle...
2022/10/28
[ "https://Stackoverflow.com/questions/74239093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19484180/" ]
74,239,104
<p>The C++ standard says nothing about packing and padding of <code>struct</code>s, because it is implementation defined.</p> <p>If it is implementation defined, then for example, why it is safe to pass a <code>struct</code> to a DLL, if this DLL could have been compiled with a different compiler, which could have different methods for <code>struct</code> padding?</p> <p>Is the <code>struct</code> padding method enforced by the OS's ABI (for example, the padding will be the same on all Windows platforms)?</p> <p>Or, is there standard method for padding when compiling for a PC (x64 or x86_64 systems) that is used in every modern compiler?</p> <p>If there is nothing that can guarantee the layout of variables, then is it safe to assume that each basic type in C++ (<code>char</code>, all numeric variables and pointers) must be aligned to an address that is a multiple of its size, and because of that, padding inside a <code>struct</code> can be done by hand without performance problems or UB?</p> <p>From what I have checked, g++ compiles <code>struct</code>s in such a way, that it inserts minimum amount of padding, just to ensure alignment of the next variable.</p> <p>For example:</p> <pre><code>struct foo { char a; // char _padding1[3]; &lt;- inserted by compiler uint32_t b; }; </code></pre> <p>There are 3 bytes of padding after <code>a</code> because that is the minimum amount that will give us a suitably aligned address for <code>b</code>.</p> <p>Can we take for granted that compilers will do this that way? Or, can we force this kind of padding by hand without UB or performance issues?</p> <p>By hand, I mean:</p> <pre><code>#pragma pack(1) struct foo { char a; char _padding1[3]; //&lt;- manually adding padding bytes uint32_t b; }; #pragma pack() </code></pre> <p>Just to be clear: I am asking about behavior of compilers only on PC platforms : Windows, Linux distros, and maybe MacOS.</p> <p>Sorry if my question is in category of &quot;you dig into this too much&quot;. I just couldn't find a satisfying answer on the Internet. Some people say that it is not guaranteed. Others say that compiling with different compilers on systems that use the same ABI guarantee that the same <code>struct</code> will have the same layout. Others show how to reduce struct padding assuming that compilers pack <code>struct</code>s the way that I described above (it is with minimum required padding to align variables).</p>
[ { "answer_id": 74239365, "author": "eerorika", "author_id": 2079303, "author_profile": "https://Stackoverflow.com/users/2079303", "pm_score": 2, "selected": false, "text": "alignof(std::uint32_t) == 1" }, { "answer_id": 74239644, "author": "supercat", "author_id": 363751,...
2022/10/28
[ "https://Stackoverflow.com/questions/74239104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14785259/" ]
74,239,110
<p>I have a ComboBox:</p> <pre><code> &lt;ComboBox Height=&quot;25&quot; Width=&quot;150&quot; Name=&quot;EnvironmentComboBox&quot; ItemsSource=&quot;{Binding Path=SourceList}&quot; SelectedIndex=&quot;{Binding Path=SourceIndex}&quot; SelectionChanged=&quot;EnvironmentComboBox_SelectionChanged&quot;&gt; &lt;/ComboBox&gt; </code></pre> <p>In the code-behind, I populate the SourceList:</p> <pre><code> public MainWindow() { InitializeComponent(); ConfigurationService.SetEnvironmentValues(ConfigurationService.DefaultEnvironment); DataContext = this; //SourceIndex = 0; List&lt;ComboBoxItem&gt; source = new List&lt;ComboBoxItem&gt; { //new ComboBoxItem { Content = &quot; - Select Environment - &quot;}, new ComboBoxItem { Content = &quot;PROD&quot;}, new ComboBoxItem { Content = &quot;CERT&quot;}, new ComboBoxItem { Content = &quot;DEV&quot;}, }; SourceList = source; } </code></pre> <p>This was largely based on what I found here (including the _sourceIndex and _sourceList fields and corresponding properties): <a href="https://stackoverflow.com/questions/21916483/setting-a-combobox-s-selected-value-without-firing-selectionchanged-event">Setting a Combobox &#39;s selected value without firing SelectionChanged event</a></p> <p>I have a SelectionChanged event, which fires after ComboBox selection is changed:</p> <pre><code> private void EnvironmentComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!(SourceIndex == 0)) { String env = ((ComboBoxItem)((ComboBox)sender).SelectedValue).Content.ToString(); string message = $&quot;Are you sure you want to change environment to {env}?\nAll unsaved work will be lost!&quot;; const string caption = &quot;Change Environment?&quot;; MessageBoxResult userResponse = MessageBox.Show(message, caption, MessageBoxButton.YesNo, MessageBoxImage.Warning); if (userResponse == MessageBoxResult.Yes) { bool envChange = ConfigurationService.SetEnvironmentValues(env); EnvironmentChangedMessage(envChange); } else { } } } </code></pre> <p>There are really two issues here.</p> <p>First, the SelectionChanged event appears to run upon the app starting, which I thought doing the data binding would solve (and it doesn't). So then I thought, I'll add a &quot; - Select Environment - &quot; ComboBoxItem (which you can see commented out) and then have that condition !(SourceIndex == 0) to prevent the code that switches the environment in my ConfigurationService class when that &quot;dummy&quot; value is selected. However, I'd really just like PROD to load in ConfigurationService class, and that to also be the selected index when the app starts up. So then I'm stuck with getting a MessageBox before the app has started, or PROD not changing becasue it is then equal to index 0.</p> <p>Second, when the user clicks &quot;No&quot; on the MessageBox, I want to revert the value of the selected combo box item to what it was originally. I reviewed this: <a href="https://stackoverflow.com/questions/2585183/wpf-combobox-selecteditem-change-to-previous-value/2709931#2709931">WPF ComboBox SelectedItem - change to previous value</a>, but I am quite unsure how to implement this in my proof-of-concept. Do I have the setter mentioned there in my SourceIndex setter? If so, where does CancelChange() in my case?</p> <p>I'd appreciate any help on these two questions.</p>
[ { "answer_id": 74242391, "author": "Mustafa Mutasim", "author_id": 3392605, "author_profile": "https://Stackoverflow.com/users/3392605", "pm_score": 1, "selected": false, "text": " bool Is_Loaded=false;\n public MainWindow()\n {\n InitializeComponent();\n ConfigurationSe...
2022/10/28
[ "https://Stackoverflow.com/questions/74239110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12191667/" ]
74,239,135
<p>I'm working with Google Sheets API and Pyinstaller.</p> <p>My code runs just fine on the IDE, but whenever i try to run it on a .exe created by Pyinstaller, it provides the following error:<a href="https://i.stack.imgur.com/FqkL3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FqkL3.png" alt="error service" /></a>.</p> <p>I thought it could be a missing file or dependency but i tested it on other environments and the error persists. Any thoughts?</p> <p>It was supposed to update a Google Sheets file and it does exactly that, except when i run it with pyinstaller.</p>
[ { "answer_id": 74242391, "author": "Mustafa Mutasim", "author_id": 3392605, "author_profile": "https://Stackoverflow.com/users/3392605", "pm_score": 1, "selected": false, "text": " bool Is_Loaded=false;\n public MainWindow()\n {\n InitializeComponent();\n ConfigurationSe...
2022/10/28
[ "https://Stackoverflow.com/questions/74239135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360548/" ]
74,239,139
<p>I have a structure inside which char array and int value is maintained. I want to treat this char array as a flat array to store the list of strings and the offset will track the starting position where the string is added in the array.</p> <p>Structure is shown below:</p> <pre><code>struct A { char element[256]; int offset; } </code></pre> <p>Also, I want to delete the strings after performing some operation if found.</p> <p>Please let me know if this feasible. If yes then how?</p>
[ { "answer_id": 74242391, "author": "Mustafa Mutasim", "author_id": 3392605, "author_profile": "https://Stackoverflow.com/users/3392605", "pm_score": 1, "selected": false, "text": " bool Is_Loaded=false;\n public MainWindow()\n {\n InitializeComponent();\n ConfigurationSe...
2022/10/28
[ "https://Stackoverflow.com/questions/74239139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20089469/" ]
74,239,156
<h1>The Question</h1> <p>Write a program that asks the user to enter their name and grades for all the courses they took this semester. Check that the name is composed of only letters and that each grade entry is composed of numbers only. When the user has entered all their grades, they may enter -1 to indicate they are done. Calculate the average grade and display that to the user.</p> <h1>Sample given to me</h1> <pre><code>Enter your name: Sar@ Please enter a valid name. Enter your name: sara Enter your grade for course 1: 90 Enter your grade for course 2: 90s Please enter a valid grade. Enter your grade for course 2: 80 Enter your grade for course 3: 70 Enter your grade for course 4: 60 Enter your grade for course 5: -1 Sara, your average grade for 4 courses this semester is 75.0. Well done! </code></pre> <h1>My progress</h1> <pre><code>count=0 sum=0 name = input(&quot;Enter your name: &quot;) while name.isalpha()==False: print(&quot;Please enter a valid name.&quot;) name = input(&quot;Enter your name: &quot;) grade = int(input(&quot;Enter your grade for course &quot;+ str(count+1)+&quot;: &quot;)) grade == 1 while grade!=-1: grade = str(grade) while grade.isnumeric()==False: print(&quot;Please enter a valid grade.&quot;) grade = input(&quot;Enter your grade for course &quot;+ str(count+1)+&quot;: &quot;) grade =int(grade) count+=1 sum+=grade grade = int(input(&quot;Enter your grade for course &quot;+ str(count+1)+&quot;: &quot;)) avg = sum/count if avg&gt;60: print(name.capitalize(),&quot;, your average grade for&quot;,count,&quot;courses this semester is&quot;,avg,&quot;. Well done!&quot;) else: print(name.capitalize(),&quot;, your average grade for&quot;,count,&quot;courses this semester is&quot;,avg,&quot;. Please do better.&quot;) </code></pre> <pre><code> I get an int error. though I know why I get the error but have no other way to solve this problem. Please help! </code></pre>
[ { "answer_id": 74239237, "author": "Rodrigo Guzman", "author_id": 13315525, "author_profile": "https://Stackoverflow.com/users/13315525", "pm_score": 1, "selected": false, "text": "try" }, { "answer_id": 74239241, "author": "mZ0ckERc", "author_id": 20360520, "author_p...
2022/10/28
[ "https://Stackoverflow.com/questions/74239156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20347651/" ]
74,239,184
<p>How will I do select with <a href="https://github.com/sagalbot/vue-select" rel="nofollow noreferrer">vue-select</a> in vue 3?</p> <pre><code>&lt;v2-select :options=&quot;options&quot; label=&quot;title&quot;&gt; &lt;template slot=&quot;option&quot; slot-scope=&quot;option&quot;&gt; &lt;img :src=&quot;option.url&quot;&gt; {{ option.url }} &lt;/template&gt; &lt;/v2-select&gt; </code></pre> <p>Data:</p> <pre><code> options: [ { title: 'Read the Docs', icon: 'fa-book', url: 'https://codeclimate.com/github/sagalbot/vue-select' }, { title: 'View on GitHub', icon: 'fa-github', url: 'https://codeclimate.com/github/sagalbot/vue-select' }, { title: 'View on NPM', icon: 'fa-database', url: 'https://codeclimate.com/github/sagalbot/vue-select' }, { title: 'View Codepen Examples', icon: 'fa-pencil', url: 'https://codeclimate.com/github/sagalbot/vue-select' } ], } </code></pre> <p>example: <a href="https://stackblitz.com/edit/vue-5ni27c?file=src%2FApp.vue,package.json,src%2Fcomponents%2FHelloWorld.vue" rel="nofollow noreferrer">https://stackblitz.com/edit/vue-5ni27c?file=src%2FApp.vue,package.json,src%2Fcomponents%2FHelloWorld.vue</a></p> <p>In vue 2 it work, bot in vue 3 dont</p>
[ { "answer_id": 74239237, "author": "Rodrigo Guzman", "author_id": 13315525, "author_profile": "https://Stackoverflow.com/users/13315525", "pm_score": 1, "selected": false, "text": "try" }, { "answer_id": 74239241, "author": "mZ0ckERc", "author_id": 20360520, "author_p...
2022/10/28
[ "https://Stackoverflow.com/questions/74239184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19154125/" ]
74,239,194
<p>I have the following class definition :</p> <pre><code> [Serializable] [DataContract] public class Models { [DataMember] public Dictionary&lt;string, string&gt; models { get; set; } public Models() { models = new Dictionary&lt;string, string&gt;(); } } </code></pre> <p>Then I have a method to get the dictionary to write to a ini file.</p> <pre><code>public bool write_all_model_names(Models models) { bool write_status = false; try { foreach (KeyValuePair&lt;string, string&gt; model in models) { Write(model.Key, model.Value); } write_status = true; } catch { } return write_status; } </code></pre> <p>I get the following error when I try to compile.</p> <pre><code>**Error** CS1579 foreach statement cannot operate on variables of type 'Models' because 'Models' does not contain a public instance or extension definition for 'GetEnumerator' CPTD_SJQ_UI </code></pre> <p>'models' is a dictionary list so why not loop through ?</p>
[ { "answer_id": 74239220, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 1, "selected": false, "text": "models" }, { "answer_id": 74239227, "author": "Blindy", "author_id": 108796, "author_profile...
2022/10/28
[ "https://Stackoverflow.com/questions/74239194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7788402/" ]
74,239,199
<p>I want to pass event prop from Child to Parent, so when we click the button in Child component, state from Parent should be triggered.</p> <p>Let's assume that we have two components, <code>Parent</code> and <code>Child</code>, but <code>Child</code> will not be imported directly in <code>Parent</code>, like this</p> <pre><code>export default function Parent() { const [count, setCount] = useState(0); const handleClick = num =&gt; { setCount(current =&gt; current + num); }; return ( &lt;div&gt; &lt;Child handleClick={handleClick} /&gt; &lt;h2&gt;Count: {count}&lt;/h2&gt; &lt;/div&gt; ); } </code></pre> <p>and it's very straitforward to pass prop in this case, but how to do when we have situation when Parent does not know which component will be passed as <code>{children}</code> prop, like this:</p> <pre><code>export default function Parent({children}) { const [count, setCount] = useState(0); const handleClick = num =&gt; { setCount(current =&gt; current + num); }; return ( &lt;div&gt; {children} &lt;/div&gt; ); } </code></pre> <p>and later we import some child component</p> <pre><code>&lt;Parent&gt; &lt;Child /&gt; &lt;/Parent&gt; </code></pre>
[ { "answer_id": 74239220, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 1, "selected": false, "text": "models" }, { "answer_id": 74239227, "author": "Blindy", "author_id": 108796, "author_profile...
2022/10/28
[ "https://Stackoverflow.com/questions/74239199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618326/" ]
74,239,214
<p><a href="https://i.stack.imgur.com/Gi5g2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gi5g2.jpg" alt="enter image description here" /></a></p> <p>how can i solve this error with Platform exception, i tried to add firebase_core_performance and to run flutter clean and flutter run, but it didn't help</p>
[ { "answer_id": 74239220, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 1, "selected": false, "text": "models" }, { "answer_id": 74239227, "author": "Blindy", "author_id": 108796, "author_profile...
2022/10/28
[ "https://Stackoverflow.com/questions/74239214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360585/" ]
74,239,216
<pre><code>import {useEffect,useState} from 'react'; export default function App() { const [count,setCount]=useState(0); const [flag,setFlag]=useState(false); function increment(){ setCount(prevState=&gt;{ if(flag) return prevState return prevState+1; }); } useEffect(function(){ increment(); setFlag(true); increment(); },[]); return ( &lt;div className=&quot;App&quot;&gt; {count} &lt;/div&gt; ); } </code></pre> <p>Was playing around with effects and states in reatct functional component, I expected the code to output &quot;1&quot; but it's giving the output as &quot;2&quot;, Why is it happening and How can I make it print 1 ?</p>
[ { "answer_id": 74239416, "author": "Yuji 'Tomita' Tomita", "author_id": 267887, "author_profile": "https://Stackoverflow.com/users/267887", "pm_score": 2, "selected": false, "text": "setFlag" }, { "answer_id": 74239515, "author": "KcH", "author_id": 11737596, "author_...
2022/10/28
[ "https://Stackoverflow.com/questions/74239216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9280058/" ]
74,239,224
<p>I have a directory with the following structure:</p> <pre><code>value_students_shop = {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} </code></pre> <p>And, for example, the following data set:</p> <pre><code>df col1 col2 1 1 2 2 3 3 4 4 </code></pre> <p>I need to create a new column in the dataframe so that its values ​​are a dict, that is, I need the following result:</p> <pre><code>df col1 col2 col3 1 1 {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} 2 2 {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} 3 3 {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} 4 4 {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74239416, "author": "Yuji 'Tomita' Tomita", "author_id": 267887, "author_profile": "https://Stackoverflow.com/users/267887", "pm_score": 2, "selected": false, "text": "setFlag" }, { "answer_id": 74239515, "author": "KcH", "author_id": 11737596, "author_...
2022/10/28
[ "https://Stackoverflow.com/questions/74239224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744714/" ]
74,239,230
<pre><code>public IActionResult DeluxRoomCount() { string deluxRoom = &quot;select COUNT(type) from Rooms where Type='Delxu' And Avilability='True'&quot;; int count = 0; using (SqlConnection thisConnection = new SqlConnection(&quot;Data Source=HootelReservationDb1&quot;)) { using (SqlCommand cmdCount = new SqlCommand(deluxRoom, thisConnection)) { thisConnection.Open(); count = (int)cmdCount.ExecuteScalar(); } return count; } } </code></pre> <p>i am hoping that there will be some ideas to count sql data and i am tring to understand what is wrong with this code</p>
[ { "answer_id": 74240470, "author": "Pradeep Kumar", "author_id": 18704952, "author_profile": "https://Stackoverflow.com/users/18704952", "pm_score": 2, "selected": true, "text": "public IActionResult DeluxRoomCount()\n{\n string deluxRoom = \"select COUNT(type) from Rooms where Type='D...
2022/10/28
[ "https://Stackoverflow.com/questions/74239230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10820084/" ]
74,239,250
<p>XCode: 14 iOS: 16 (supports upto ios12)</p> <p>i am writing ios sdk, which presents some UI when we call its method. but since its an SDK, i don't have access of client app delegate.</p> <p>Goal: there are 2 screens (A) and (B). if screen(A) is on let say portrait mode, and user go to screen(B) from screen(A) then even if user rotate device to any other orientation, it should not rotate screen(B).</p> <p>SDK supports min version ios 12 to 16+.</p> <p>tried a few methods but none of them worked. that's why posted a question here.</p> <p>Shouldautoroate(), Preferred Orientation () doesn't work.</p> <pre><code> override func viewDidLoad() { super.viewDidLoad() UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: &quot;orientation&quot;) } override open var shouldAutorotate: Bool { return false } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } </code></pre> <p>tried above approach but doesn't work.</p> <p>shows erorr</p> <pre><code>BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please use UIWindowScene.requestGeometryUpdate(_:) </code></pre> <p><strong>Update 1</strong></p> <p>i am able to implement orientation lock on screen, but its like, it will rotate it for a second, and figure out if it matches or supported orientation or not, if it doesn't match then it will rotate to require orientation. but all of this takes 1-2 seconds, but i want to lock is completely, in sense that it should not even rotate for a second.</p> <p><strong>Update 2</strong></p> <p>i am able to implement lock orientation feature in iOS SDK. but that requires an additinal call. i am not sure if its a best way.</p> <pre><code> func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -&gt; UIInterfaceOrientationMask { // here .all - indicates current client app supports all orientations. return &lt;SDKClassName&gt;.supportedInterfaceOrientations(.all) } </code></pre> <blockquote> <p>supportedInterfaceOrientations() method check if current top viewcontroller is of kind SDKViewController and also checks for current interface orientation and update it to either landscape or portrait depending upon value, if top view controller is not SDKViewController then it returns the original supported interface mask value.</p> </blockquote> <p>looking for a better solution now. Thanks.</p>
[ { "answer_id": 74240470, "author": "Pradeep Kumar", "author_id": 18704952, "author_profile": "https://Stackoverflow.com/users/18704952", "pm_score": 2, "selected": true, "text": "public IActionResult DeluxRoomCount()\n{\n string deluxRoom = \"select COUNT(type) from Rooms where Type='D...
2022/10/28
[ "https://Stackoverflow.com/questions/74239250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128647/" ]
74,239,269
<p>I am trying to write some python code which can click on 'Alles accepteren'. The website is called: <a href="http://www.Bol.com" rel="nofollow noreferrer">www.Bol.com</a></p> <p>Because of my lack of knowledge, i don't know how to find the frame python should focus on.</p> <p>I know that i should use:</p> <p><code>driver.switch_to.frame()</code></p> <p>Anyone who can help me??</p>
[ { "answer_id": 74240470, "author": "Pradeep Kumar", "author_id": 18704952, "author_profile": "https://Stackoverflow.com/users/18704952", "pm_score": 2, "selected": true, "text": "public IActionResult DeluxRoomCount()\n{\n string deluxRoom = \"select COUNT(type) from Rooms where Type='D...
2022/10/28
[ "https://Stackoverflow.com/questions/74239269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19964657/" ]
74,239,317
<p>I have a pyspark object column in a dataframe (df) like this:</p> <pre><code>| 'A' | ------------------------- | field 1 - order - one | | field 2 - sell | | order | | sell | </code></pre> <p>I'd like to remove the first occurence of '- ' and all characters before using regex_replace or whatever other sql function that would work in this case but having a little trouble. Below is the desired output:</p> <pre><code>| 'A' | ------------------- | order - one | | sell | | order | | sell | </code></pre>
[ { "answer_id": 74239635, "author": "iambdot", "author_id": 1415826, "author_profile": "https://Stackoverflow.com/users/1415826", "pm_score": 2, "selected": true, "text": "from pyspark.sql import functions as F\n\ndf = spark.createDataFrame(\n [\n (\"field 1 - order\", \"None\")...
2022/10/28
[ "https://Stackoverflow.com/questions/74239317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12458212/" ]
74,239,361
<p>I want to make a function where given a number like 7 I want to factorise the number by as many 3s and 2s. If left with a remainder then return -1.</p> <p>Note: Through further examples it seems any number can be made up of the addition of multiples of 3s and 2s so -1 for remainder not needed. Goal is to get as many multiples of 3 before having to add multiples of 2 to factorise completely</p> <p>For example given the number 11 I want the function to return 3:3 and 2:1 as 3 fits into 11 3 times and 2 once ie. 3+2+2=7, 3+3+3+2=11, 3+3+3+2+2=13. The preference should be being able to fit as many 3s first.</p> <p>This is part of a wider problem:</p> <pre><code>from collections import Counter #Choose two packages of the same weight #Choose three packages of the same weight #Minimum number of trips to complete all the deliveries else return -1 def getMinimumTrips(weights): weights_counted = Counter(weights) minimum_trips = 0 print(weights_counted) for i in weights_counted: if weights_counted[i]==1: return -1 elif weights_counted[i]%3==0: minimum_trips += (weights_counted[i]//3) elif weights_counted[i]%2==0: minimum_trips += (weights_counted[i]//2) return minimum_trips print(getMinimumTrips([2, 4, 6, 6, 4, 2, 4])) </code></pre> <p>Possible solution:</p> <pre><code>#Looking at inputs that are not a multiple of 3 or 2 eg, 5, 7, 11, 13 def get_components(n): f3 = 0 f2 = 0 if n%3==1: f3 = (n//3)-1 f2 = 2 elif n%3==2: f3 = (n//3) f2=1 return f&quot;3:{f3}, 2:{f2}&quot; </code></pre>
[ { "answer_id": 74239635, "author": "iambdot", "author_id": 1415826, "author_profile": "https://Stackoverflow.com/users/1415826", "pm_score": 2, "selected": true, "text": "from pyspark.sql import functions as F\n\ndf = spark.createDataFrame(\n [\n (\"field 1 - order\", \"None\")...
2022/10/28
[ "https://Stackoverflow.com/questions/74239361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19820043/" ]
74,239,371
<p>I seem to have relatively easy question, but I have a little problem. I would like to iterr through the column prices in table products and then sum the prices. I know an easy solution would be to change sql query -&gt; sum(price), but in my exercise I need to avoid this solution.</p> <pre><code>import psycopg2 connection = psycopg2.connect( host='host', user='user', password='password', dbname='dbname', ) cursor = connection.cursor() sql = &quot;select price from products&quot; cursor.execute(sql) for price in cursor: print(sum(price)) </code></pre>
[ { "answer_id": 74239635, "author": "iambdot", "author_id": 1415826, "author_profile": "https://Stackoverflow.com/users/1415826", "pm_score": 2, "selected": true, "text": "from pyspark.sql import functions as F\n\ndf = spark.createDataFrame(\n [\n (\"field 1 - order\", \"None\")...
2022/10/28
[ "https://Stackoverflow.com/questions/74239371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17277677/" ]
74,239,398
<p>I am looking to build a filter component where my search comes like <code>b_cycle_type = '1st Day Of The Month'</code></p> <p>and in the database <code>b_cycle_type</code> is stored as -1,0,1,2,3,4,5</p> <p>How can I prepare postgres statement</p> <p>I am trying:</p> <pre><code>SELECT &quot;customers&quot;.* FROM &quot;customers&quot; WHERE (CASE customers.b_cycle_type WHEN -1 THEN 'Last day of the month' WHEN 0 THEN 'Align with first' ELSE to_char(customers.b_cycle_type, '99th') || ' Day Of The Month' END = '27th Day Of The Month') </code></pre> <p>It's not returning any results.</p>
[ { "answer_id": 74239635, "author": "iambdot", "author_id": 1415826, "author_profile": "https://Stackoverflow.com/users/1415826", "pm_score": 2, "selected": true, "text": "from pyspark.sql import functions as F\n\ndf = spark.createDataFrame(\n [\n (\"field 1 - order\", \"None\")...
2022/10/28
[ "https://Stackoverflow.com/questions/74239398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1216272/" ]
74,239,403
<p>I have two lists of objects which have a common property called OrderNumber.</p> <p>The first list has about 20000 items and the second list has about 1.5 million items.</p> <p>I need an efficient way of finding items from list 1 which dont have a match in list 2. I am currently using Linq and it takes more than 20 mins to compute the solution. I am not able to find an efficient solution to this online.</p> <p>My code so far</p> <pre><code>notmatched.AddRange(List1.Where(l1=&gt; !list2.Select(l2=&gt; l2.OrderNumber).Contains(l1.OrderNumber)).Select(l1 =&gt; new SomeObj { OrderNumber = l1.OrderNumber })); </code></pre>
[ { "answer_id": 74239625, "author": "youssefsbai", "author_id": 14901824, "author_profile": "https://Stackoverflow.com/users/14901824", "pm_score": 0, "selected": false, "text": "notmatched.AddRange(List1.Where(l1=> !list2.Any(l2=> l2.OrderNumber == l1.OrderNumber).Select(l1 => new SomeOb...
2022/10/28
[ "https://Stackoverflow.com/questions/74239403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370017/" ]
74,239,439
<p>I am trying to make a quiz app using React.</p> <p>I am currently working on the main quiz page where I have 4 buttons, and each of the buttons denotes an answer I'm importing from a question bank.</p> <p>I want the current selected button to be highlighted, and for this I am currently using a state for each button. Is there any way to just use one state and deal with all four of the buttons, as this way is too tedious and cannot be used for a large number of such buttons? Also, I want only one button, the one the user selects finally, to be highlighted. So for this reason I need to set the state of all the other buttons to <code>null</code>, which makes the task even more tedious.</p> <p>Here is the div containing the buttons</p> <pre><code>&lt;div&gt; &lt;button className={selected1} onClick={() =&gt; dealingWithOptions(&quot;A&quot;)}&gt;{questions[currentQuestion].optionA}&lt;/button&gt; &lt;button className={selected2} onClick={() =&gt; dealingWithOptions(&quot;B&quot;)}&gt;{questions[currentQuestion].optionB}&lt;/button&gt; &lt;button className={selected3} onClick={() =&gt; dealingWithOptions(&quot;C&quot;)}&gt;{questions[currentQuestion].optionC}&lt;/button&gt; &lt;button className={selected4} onClick={() =&gt; dealingWithOptions(&quot;D&quot;)}&gt;{questions[currentQuestion].optionD}&lt;/button&gt; &lt;/div&gt; </code></pre> <p>Here is the function dealing with the options clicking</p> <pre><code>const [selected1,setSelectedButton1] = useState(&quot;&quot;) const [selected2,setSelectedButton2] = useState(&quot;&quot;) const dealingWithOptions = (op) =&gt; { setOptionChosen(op); if (op==&quot;A&quot;) { setSelectedButton1(&quot;selected1&quot;); setSelectedButton2(&quot;&quot;) setSelectedButton3(&quot;&quot;) setSelectedButton4(&quot;&quot;) } else if (op=='B') { setSelectedButton1(&quot;&quot;); setSelectedButton2(&quot;selected2&quot;) setSelectedButton3(&quot;&quot;) setSelectedButton4(&quot;&quot;) } else if (op=='C') { setSelectedButton1(&quot;&quot;); setSelectedButton2(&quot;&quot;) setSelectedButton3(&quot;selected3&quot;) setSelectedButton4(&quot;&quot;); } else if (op=='D') { setSelectedButton1(&quot;&quot;); setSelectedButton2(&quot;&quot;) setSelectedButton3(&quot;&quot;) setSelectedButton4(&quot;selected3&quot;); } } </code></pre>
[ { "answer_id": 74239590, "author": "andy mccullough", "author_id": 1849358, "author_profile": "https://Stackoverflow.com/users/1849358", "pm_score": 0, "selected": false, "text": "setSelectedButton('A')\n" }, { "answer_id": 74239649, "author": "moshfiqrony", "author_id": ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19551765/" ]
74,239,506
<p>I have a column that are characters. There are observations where ph was added to the end of the string. Any string in the column that has ph in the string I want replaced with &quot;NA&quot;. Here is what I have tried and gives the below error.</p> <p><strong>Column</strong></p> <pre><code>wind_speed_m_s &lt;- c(&quot;1.7&quot;, &quot;0.7&quot;, &quot;0&quot;, &quot;0.6&quot;, &quot;0.4&quot;, &quot;1.2&quot;, &quot;1.9&quot;, &quot;1.3&quot;, &quot;2.0, gust to 3.7&quot;, &quot;0.5&quot;, &quot;1.8&quot;, &quot;1.4&quot;, &quot;3.4&quot;, &quot;2.8&quot;, &quot;1.6&quot;, &quot;2&quot;, NA, &quot;0.9&quot;, &quot;0.8&quot;, &quot;1&quot;, &quot;1.1&quot;, &quot;2.6&quot;, &quot;2.4&quot;, &quot;1.1ph&quot;, &quot;1.7 kt&quot;, &quot;2.1&quot;, &quot;1.5&quot;, &quot;0ph&quot;, &quot;3&quot;, &quot;.4 /s&quot;, &quot;0.3&quot;, &quot;2.3&quot;, &quot;0.2&quot;, &quot;3.3&quot;, &quot;3.9ph&quot;, &quot;1.5ph&quot;, &quot;1ph&quot;, &quot;2ph&quot;, &quot;1.7ph&quot;, &quot;0.8 ph&quot;, &quot;1.5 ph&quot;, &quot;2.2&quot;, &quot;1.9 k/hr&quot;, &quot;2.5&quot;, &quot;NA&quot;, &quot;0.4/s&quot;, &quot;1/s&quot;) </code></pre> <pre><code>date &lt;- data_raw %&gt;% mutate(wind_speed_m_s = str_replace(wind_speed_m_s, pattern = str_detect(&quot;ph&quot;), &quot;NA&quot;)) Error in `mutate()`: ! Problem while computing `wind_speed_m_s = str_replace(wind_speed_m_s, pattern = str_detect(&quot;ph&quot;), &quot;NA&quot;)`. Caused by error in `type()`: ! argument &quot;pattern&quot; is missing, with no default Backtrace: 1. ... %&gt;% ... 9. stringr::str_detect(&quot;ph&quot;) 10. stringr:::type(pattern) </code></pre>
[ { "answer_id": 74239590, "author": "andy mccullough", "author_id": 1849358, "author_profile": "https://Stackoverflow.com/users/1849358", "pm_score": 0, "selected": false, "text": "setSelectedButton('A')\n" }, { "answer_id": 74239649, "author": "moshfiqrony", "author_id": ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17296506/" ]
74,239,550
<p>My code is meant to find the longest path in a matrix, where each value is greater than the one previous. However, I've been instructed to not use for loops at all, which is difficult because I have 3, with 2 of them being involved in a nested loop. Is there any way I could only user recursion to solve this?</p> <pre class="lang-py prettyprint-override"><code> def path(self, matrix): res = 1 # for loop to run the function for every element in list for row in range (len(matrix)): for col in range (len(matrix[0])): # pass in the current max and the new spot, and take the max value res = max(res, self.dfs(matrix, row, col)) # return the max value return res # function to compare paths (Depth-First Seach) def dfs(self, matrix, row, col): # if spot was visited before, return value from cache if (row, col) in self.cache: return self.cache[(row, col)] # Set a default value of 1 self.cache[(row, col)] = 1 # moving the tile of focus for rowVal, colVal in self.directions: newRow = row + rowVal newCol = col + colVal # if the pointer can move in a direction (not out of bounds), and is greater: store cache value if (0 &lt;= newRow &lt; len(matrix)) and (0 &lt;= newCol &lt; len(matrix[0])) and matrix[row][col] &lt; matrix[newRow][newCol]: self.cache[(row, col)] = max(self.cache[(row, col)], 1 + self.dfs(matrix, newRow, newCol)) </code></pre>
[ { "answer_id": 74239972, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": -1, "selected": false, "text": "\"\"\" Emulation Of:\nfor row in range (len(matrix)):\n for col in range (len(matrix[0])):\n print(...
2022/10/28
[ "https://Stackoverflow.com/questions/74239550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12903816/" ]
74,239,558
<p>There are plenty of algorithms and tools out there that can take in an image and determine what the most dominant colors are (<a href="https://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image">see here</a>). However, is there a way to determine what colors stand out the most (not necessarily the most dominant/used colors in an image)? For example, if you had a white page with a line of blue, then the blue would stand out the most. Or if there was an image with a lot of pastel colors but then a couple of squares of neon colors, then probably the neon colors would stand out the most.</p> <p>As a potential alternative to a more algorithmic approach, I ran a survey that asks people to select the colors from an image that stand out the most. Unfortunately, the results were inconsistent and I'll probably re-run a similar test, but I'd still be open to hearing any ideas about deep learning architectures that could be done here. I'm a bit stumped here though, because I can't quite figure out what sort of architecture could be useful here.</p> <p>Any ideas on the matter would be appreciated. Thanks!</p>
[ { "answer_id": 74239972, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": -1, "selected": false, "text": "\"\"\" Emulation Of:\nfor row in range (len(matrix)):\n for col in range (len(matrix[0])):\n print(...
2022/10/28
[ "https://Stackoverflow.com/questions/74239558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11602367/" ]
74,239,559
<p>I have a data frame:</p> <pre><code>a &lt;- c(0, 0, 1, 3, NA, 0, 0, NA) b &lt;- c(NA, 0, 1, 3, 3, NA, 6, 4) c &lt;- c(0, NA, 1, 1, 5, 0, NA, 0) d &lt;- c(4, 0, 0, 2, 3, NA, 1, 4) e &lt;- c(NA, NA, 0, 0, 6, 1, 1, 0) f &lt;- c(0, NA, 0, 0, 3, 5, 1, 4) df &lt;- data.frame(a,b,c,d,e,f) df a b c d e f 1 0 NA 0 4 NA 0 2 0 0 NA 0 NA NA 3 1 1 1 0 0 0 4 3 3 1 2 0 0 5 NA 3 5 3 6 3 6 0 NA 0 NA 1 5 7 0 6 NA 1 1 1 8 NA 4 0 4 0 4 </code></pre> <p>I want to create new variables as follows:</p> <pre><code>df %&gt;% mutate(new_var1 = a + (b/7), new_var2 = c + (d/7), new_var3 = e + (f/7)) </code></pre> <p>Within pairs, if the value in column a, c, or e is not NA, but the value in column b, d, or f is NA, then I would like R to return the value in a, c, or e.</p> <p>If the value in column a, c, or e is NA, but the value in column b, d, or f is not, then I would like R to return b/7, d/7, or f/7.</p> <p>Since I want to do this across multiple pairs of columns in the data frame, it would also be helpful to know a more efficient way to iterate through.</p> <p>Any advice would be greatly appreciated!</p>
[ { "answer_id": 74239642, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "reshape(df, matrix(seq(ncol(df)),2), dir='long')|>\n transform(new_var = ifelse(is.na(a), b/7,\n ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7647881/" ]
74,239,647
<p>I have a nested list holding dictionaries as mapping table using a tuple as key. I am struggling to <code>zip</code> the dictionary together so it can be exported by Pandas to csv file:</p> <pre><code>l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}] def dynDictCombiner(item): # would lambda be faster? def _combine(item): key = item.keys()[0] return key, item[key] col_keys = ('start', 'stop') row_keys = ('value') # syntax error l = [dict(zip(col_keys + row_keys, k + v)) for ((k, v) :=_combine(item) in l)] print(l) l = dynDictCombiner(l) #import pandas as pd #df = pd.DataFrame.from_dict(l) #print(df.shape) #print(df) #df.to_csv(path_or_buf='C:/temp/foo.csv', index=False, header=True) </code></pre> <p>Expected Output:</p> <pre><code>[ {'start': 'A', 'stop': 'B', 'value': 1}, {'start': 'A', 'stop': 'C', 'value': 2}, {'start': 'A', 'stop': 'D', 'value': 3} ] </code></pre> <p><strong>Edit</strong>, function without walrus:</p> <pre><code>def dynDictCombinerSimple(items): # would lambda be faster? def _combine(item): key = list(item.keys())[0] return key, (item[key], ) col_keys = ('start', 'stop') row_keys = ('value', ) result = [] for item in items: k, v = _combine(item) result.append(dict(zip(col_keys + row_keys, k + v))) print(result) </code></pre> <p>Out as expected:</p> <pre><code>[{'start': 'A', 'stop': 'B', 'value': 1}, {'start': 'A', 'stop': 'C', 'value': 2}, {'start': 'A', 'stop': 'D', 'value': 3}] </code></pre>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18582978/" ]
74,239,664
<p>I'm trying to extract some values from 1 column. Some rows have 3 values I want to with different setups.</p> <p><strong>My dataset:</strong></p> <pre><code> col1 0 1001100100 / hello street 2 a town1 1 1001100102 ;hello 3 towns2 2 STRZ19-0072 DT001001-0100 location1 town4 3 1001100103_hello street 3, town5 4 DT001002-0100 street 78 5 1001100107 DT001002-0102 street 6a town7 </code></pre> <p><strong>I need:</strong></p> <p>I need 3 new columns with different values focused on the 10 digit number starting with &quot;100&quot;, the 'DT'number with 6 digits-4 digits and the street + town combined. Other values like 'STRZ19-0072' are not relevant.</p> <p><strong>I tried this:</strong></p> <pre><code>df2 = df['col1'].str.extract(r&quot;(?&lt;col2&gt;\d{10})|(?&lt;col3&gt;PR\d{6}-\d{4})|(?&lt;col4&gt;\w.*)&quot;) </code></pre> <p>This does not get me the DT-number from row 3.</p> <p><strong>Expected result:</strong></p> <pre><code> col2 col3 address 0 1001100100 NaN hello street 2 a town1 1 1001100102 NaN hello 3 towns2 2 NaN DT001001-0100 location1 town4 3 1001100103 NaN hello street 3, town5 4 NaN DT001002-0100 street 78 5 1001100107 DT001002-0102 street 6a town7 </code></pre> <p>Appreciate the help and effort. Thank you!</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20301326/" ]
74,239,683
<p>I am receiving an error while creating <code>aws_launch_template</code> using Terraform, below the error message I am using an existing Role which is pre-created in the account</p> <p><strong>Error message</strong> - <strong>An argument named &quot;iam_instance_profile&quot; is not expected here. Did you mean to define a block of type &quot;iam_instance_profile&quot;?</strong></p> <p>Code</p> <pre><code>data &quot;aws_iam_roles&quot; &quot;seamless_domain_join_role&quot; { name = &quot;seamless-domain-join-role&quot; } data &quot;aws_iam_instance_profile&quot; &quot;autoscale-instance-profile&quot; { name = &quot;seamless-domain-join-role&quot; } </code></pre> <pre><code>resource &quot;aws_launch_template&quot; &quot;Windows-instance&quot; { name_prefix = &quot;Windows_Instance&quot; image_id = &quot;ami-0526b9747c2c87a0b&quot; iam_instance_profile = { arn = data.aws_iam_instance_profile.autoscale-instance-profile.arn } instance_type = &quot;t2.medium&quot; tag_specifications { resource_type = &quot;instance&quot; tags = { Name : &quot;sk-autoscaling-dj&quot; } } } </code></pre> <p>I am receiving same error with **name ** as well.</p> <pre><code> iam_instance_profile = { name= data.aws_iam_instance_profile.autoscale-instance-profile.name } </code></pre> <p>Any suggestions will be appreciated.</p> <p>Any suggestions on how to fix this issue?</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16378044/" ]
74,239,696
<p>I'm trying to create over flowing pythonic list meaning that if i'm trying to get the index of list even if the index is larger then then the list size.</p> <p>if the index is bigger then the list size I want to get the index from the start of the list.</p> <p>for example if the list size is 5</p> <pre class="lang-py prettyprint-override"><code>l = [1,2,3,4,5] </code></pre> <p>so <code>l[7]</code> should return <code>3</code> [index 2]</p> <p>Thanks!</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8622976/" ]
74,239,727
<p>My team inherited a 3rd party Azure software product from another company. It was migrated or moved over by someone external, and the website had been working, until The cert for our dev site in Azure has expired..</p> <p>but I'm not seeing the SSL cert anywhere in places recommended online to store certs. We're looking to find the cert and then renew it as well. The website is set up to only allow https access.</p> <p>It was issued by Let's Encrypt, and there are helpful articles out there to auto renew; I just don't know where the cert is located yet. Hoping someone can help give options, maybe a different keyword other than (SSL or Cert) to find it on a global level in Azure.</p> <p>The usual places for certs that I know of but are EMPTY are: Azure Key Vault &gt; Cert. App Services Cert Application Gateway App Services (This resource type is not even used)</p> <p>I've also looked under Settings/Properties for our AKS resource, Azure Load Balancer, and in various YAML files for these. Not seeing anything cert related there.</p> <p>I expected there to be a cert in a Key Vault and to then update/configure that to auto renew so that it's a hands-off approach.</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360833/" ]
74,239,733
<p>i have the following table : <a href="https://i.stack.imgur.com/y70P2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y70P2.png" alt="enter image description here" /></a></p> <p>And what i want to do is to calculate the difference in terms of days between the dates. The first step that i'm trying to implement is to pull the previous rows and then calculate the difference.</p> <p>Here's what i tried :</p> <pre><code>SELECT YEAR,MONTH,DAY, lag(DATE) OVER w AS Lag FROM DATASET WINDOW w AS (PARTITION BY YEAR , MONTH , DAY ORDER BY YEAR , MONTH) </code></pre> <p>when i try to implement the lag i get this error:</p> <p><em><strong>check the manual that corresponds to your MySQL server version for the right syntax to use near 'Lag</strong></em></p> <p>Any help would be greatly appreciated , thank you</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11819525/" ]
74,239,750
<p>I have a html template i want to code in django. For now i need to take the header and footer parts and make images, css and js into static files. I tried to do it but it does not quite work, can anyone help me with it? I would greatly appreciate if someone can fix my mistakes and send me the file</p> <p>{% extends 'base.html' %} {% block content %} {% load static %} none of them work</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360978/" ]
74,239,776
<p>I am on webpage 1.</p> <p>On webpage 2, I have a form that needs some GET request values to be submitted and some events are also triggered e.g</p> <pre><code>form.php?a=1&amp;b=2&amp;c=3 </code></pre> <p>Now, if I visit webpage 2 via the browser Url, it works.</p> <p>I want to know, is there a way I can do this stuff via Ajax? Like, if I send a request to webpage 2 via ajax, it is treated like a normal browser request and the form is submitted from there.</p> <p>Thanks</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13019136/" ]
74,239,778
<p>heres the code</p> <pre><code>#l is a list that stores all the GPAs of 10 students l = [] #iterates the loop to collect GPAs of 10 members in the class for i in range(1, 11): j = int(float(input())) #this is where the error is l.append(j) #find the average GPA of the class and store the average in the &quot;result&quot; variable result = sum(l)/10 #printing the result print(&quot;Average is: &quot;,result) </code></pre> <p>at first it was j=int(input) and that was also giving an error. im new to python</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360968/" ]
74,239,785
<p>This may be very naive but I am struggling to make the div children of a parent div element horizontal</p> <p>I am trying to make a header, here is my code</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>.logoImg { width: 50px; height: 50px; } .header { display: flex; justify-content: center; float: left; } .logo { margin: 0 auto; display: flex; } .addressDropDown { margin: 0 auto; display: flex; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;div className="logo"&gt; &lt;img className="logoImg" src='https://via.placeholder.com/100x100' alt="" /&gt; &lt;/div&gt; &lt;div className="addressDropDown"&gt; &lt;p&gt;Dropdown&lt;/p&gt; &lt;/div&gt; &lt;div className="searchBar"&gt; &lt;input type="text" placeholder="What are you looking for?" /&gt; &lt;/div&gt; &lt;div className="languageSetting"&gt; &lt;p&gt;language&lt;/p&gt; &lt;/div&gt; &lt;div className="singInBtn"&gt; &lt;p&gt;signIn&lt;/p&gt; &lt;/div&gt; &lt;div className="cartBtn"&gt; &lt;p&gt;Cart&lt;/p&gt; &lt;/div&gt; &lt;/header&gt; &lt;body&gt; Body of the page &lt;/body&gt;</code></pre> </div> </div> </p> <p>I would really appreciate it if someone can point out my mistake or give me some hints</p> <p>Thank you</p>
[ { "answer_id": 74239765, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": false, "text": "l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\...
2022/10/28
[ "https://Stackoverflow.com/questions/74239785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9976333/" ]
74,239,787
<p>I'm in a unique situation where my production code is being used does not allow for the browser debugger to open. So bringing up the browser console is not an option. This causes issues when it comes to debugging and finding out what errors come up.</p> <p>Is there a way to get the console output (errors and warnings) through JavaScript, a library, or API?</p> <p>I've looked into console API but so far it looks like just different ways to display data within the console.</p>
[ { "answer_id": 74239861, "author": "ControlAltDel", "author_id": 1291492, "author_profile": "https://Stackoverflow.com/users/1291492", "pm_score": 0, "selected": false, "text": "console.log = function (data) {\n alert(data);\n}\n" }, { "answer_id": 74239883, "author": "Bijoy...
2022/10/28
[ "https://Stackoverflow.com/questions/74239787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11938531/" ]
74,239,789
<p>basically, I have a streaming website with multiple servers and I want to hide that server link. here the code</p> <p><code>&lt;a id=&quot;server1&quot; href=&quot;SERVER-URL&quot; target=&quot;iframe-to-load&quot; class=&quot;btn btn-server active&quot;&gt;server 1&lt;/a&gt;</code></p> <p>Does anyone know how to do that?</p> <p>I have tried multiple methods like using <strong>onclick</strong> event like:</p> <p><code>&lt;a id=&quot;server1&quot; onclick=&quot;window.location.href=&quot;SERVER-URL&quot; target=&quot;iframe-to-load&quot; class=&quot;btn btn-server active&quot;&gt;server 1&lt;/a&gt;</code></p> <p>sometimes they open in a new tab instead of load in iframe</p> <p>I want to hide exactly like <a href="http://asp-arka.blogspot.com/2014/08/hide-url-on-mouse-hover-of-hyper-link.html" rel="nofollow noreferrer">http://asp-arka.blogspot.com/2014/08/hide-url-on-mouse-hover-of-hyper-link.html</a></p>
[ { "answer_id": 74239805, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 1, "selected": false, "text": "href" }, { "answer_id": 74240064, "author": "Kai Steinke", "author_id": 12554273, "author_profile": ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360896/" ]
74,239,800
<p>For example if you have <code>a1 | a2 = 0011</code> so the possible states for a1 and a2 are =&gt; <code>result = [ (0000,0011) , (0001,0010) , (0001,0011) ]</code> and a1 &lt; a2. Our numbers are not necessarily 4-bit, they can be more.</p> <p>I mean, you have the answer of Bitwise OR and you are looking for all possible states for a2, a1 (in binary).</p> <p>Could you help me how to find all possible states in python? Thank you.</p>
[ { "answer_id": 74240614, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 2, "selected": true, "text": "from itertools import product\n\ndef or_factors(bits):\n bit_pairs = [[('0','0')] if i == '0' else [('0','1')...
2022/10/28
[ "https://Stackoverflow.com/questions/74239800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360938/" ]
74,239,811
<p>How can I transform an array like this:</p> <pre><code>const arrayTocheck = [ { result: 2 }, { result: 2 }, { result: 0 }, { result: 2 }, { result: 0 }, { result: 2 }, { result: 2 }, { result: 2 }, { result: 0 }, { result: 2 }, { result: 2 }, { result: 2 }, { result: 2 }, { result: 0 }, { result: 2 } ]; </code></pre> <p>to this:</p> <pre><code>const expectedResult = [2, 1, 3, 4, 1]; </code></pre> <p>I want to count each group of consecutive 2's and return those as an array.</p>
[ { "answer_id": 74240614, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 2, "selected": true, "text": "from itertools import product\n\ndef or_factors(bits):\n bit_pairs = [[('0','0')] if i == '0' else [('0','1')...
2022/10/28
[ "https://Stackoverflow.com/questions/74239811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3887366/" ]
74,239,825
<p>In some specific numbers my algorithm gets stuck. It never reaches the minimum approximation so we never get out of the while. I think I can either low my approximation requisites or use double for my numbers, but I'm trying to figure out other solutions.</p> <p>I'm programming a babylonian algorithm to calculate roots. First I'm doing this in C and later I will do this in Assembly(University homework). When I try to find the root of numbers like 99999 the program iterates to infinity. I have already tried two different stop conditions, one of them I did exactly like this tutorial from geeks4geeks(the first one inside the site).</p> <p><a href="https://www.geeksforgeeks.org/square-root-of-a-perfect-square/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/square-root-of-a-perfect-square/</a></p> <p>The second stop condition I tested was this:</p> <p><code>while ((x*x - n) &gt; e) {}</code></p> <p>I tried something like this because it is more &quot;relatable&quot; to the method enunciation. The full code is showed below:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; /*Returns the square root of n. Note that the function */ float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while ((x*x - n) &gt; e) { x = (x + y) / 2; y = n / x; // if(prev_err == x-y){ // printf(&quot;A aproximação por ponto flutuante alcançou o máximo possível para o caso\n&quot;); // return x; // } // prev_err = x-y; } return x; } /* Driver program to test above function*/ int main() { int n; printf(&quot;Insira o número cuja raiz deseja calcular\n&quot;); scanf(&quot;%d&quot;, &amp;n); printf(&quot;Square root of %d is %.8f\n&quot;, n, squareRoot(n)); return 0; } </code></pre>
[ { "answer_id": 74243821, "author": "Ahmad Makki", "author_id": 19506269, "author_profile": "https://Stackoverflow.com/users/19506269", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\n/*Returns the square root of n. Note that the function */\n\ndouble ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20360967/" ]
74,239,847
<p>For four days I am trying to figure out how to solve this, as well as googling it, and was no luck</p> <p>The problem is that I needed to loop through a nested array (for unknown deep) and keep the top-level keys (as a prefix to the last value) as long as I am still going deep, and then start over (the prefix need to reset) once it started a new path.</p> <p>I want to generate complete addresses from this array.</p> <pre><code>$arr = [ &quot;buildings&quot; =&gt; [ &quot;group1&quot; =&gt; [ &quot;b1&quot; =&gt; [1,2,3,4], &quot;b2&quot; =&gt; [1,2,3] ], &quot;group2&quot; =&gt; [ &quot;b1&quot; =&gt; [1,2] ] ], &quot;villas&quot; =&gt;[ &quot;group1&quot; =&gt; [ &quot;v1&quot; =&gt; [1,2], &quot;v2&quot; =&gt; [1] ], &quot;group2&quot; =&gt; [ &quot;v1&quot; =&gt; [1], &quot;v2&quot; =&gt; [1] ], &quot;group3&quot; =&gt; [ &quot;v1&quot; =&gt; [1] ], ] ]; </code></pre> <p><strong>This is the needed output</strong></p> <pre><code>buildings/group1/b1/1 buildings/group1/b1/2 buildings/group1/b1/3 buildings/group1/b1/4 buildings/group1/b2/1 buildings/group1/b2/2 buildings/group1/b2/3 buildings/group2/b1/1 buildings/group2/b1/2 villas/group1/v1/1 villas/group1/v1/2 villas/group1/v2/1 villas/group2/v1/1 villas/group2/v2/1 villas/group3/v1/1 </code></pre> <p>I tried this function but also it didn't bring the wanted results</p> <pre><code>function test($array, $path = &quot;&quot;){ foreach ($array as $key =&gt; $value) { if (is_array($value)){ $path .= $key.&quot;/&quot;; test($value, $path); } else { echo $path.$value.&quot;&lt;br&gt;&quot;; } } } test($arr); </code></pre> <p><strong>UPDATE</strong></p> <p>I understood where was my mistake and I wanted to share with you my modification to my method after I fixed it.</p> <pre><code>function test($array, $path = &quot;&quot;){ foreach ($array as $key =&gt; $value) { if (is_array($value)){ test($value, $path . $key . '/'); } else { echo $path.$value.&quot;&lt;br&gt;&quot;; } } } </code></pre> <p>And thanks to <a href="https://stackoverflow.com/users/12554273/kai-steinke">@Kai Steinke</a> he's method is way better than mine, and here is some improvements just to make it look better.</p> <pre><code>function flatten(array $array, array $flattened = [], string $prefix = ''): array { foreach ($array as $key =&gt; $value) { if (is_array($value)) { $flattened = array_merge( flatten($value, $flattened, $prefix . $key . '/')); continue; } $flattened[] = $prefix . $value; } return $flattened; } </code></pre>
[ { "answer_id": 74239930, "author": "Kai Steinke", "author_id": 12554273, "author_profile": "https://Stackoverflow.com/users/12554273", "pm_score": 3, "selected": true, "text": "function flatten($arr, $prefix = '') {\n $result = [];\n foreach ($arr as $key => $value) {\n if (...
2022/10/28
[ "https://Stackoverflow.com/questions/74239847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666947/" ]
74,239,914
<p>I'm trying to implement the layout below in <strong>SwiftUI</strong> - a cell that can be used in <code>VStack</code> or <code>List</code> but I'm stuck. Is it possible to achieve this layout without <code>Grid</code> (I have to support iOS 15+)? <a href="https://i.stack.imgur.com/eoyNM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eoyNM.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74239930, "author": "Kai Steinke", "author_id": 12554273, "author_profile": "https://Stackoverflow.com/users/12554273", "pm_score": 3, "selected": true, "text": "function flatten($arr, $prefix = '') {\n $result = [];\n foreach ($arr as $key => $value) {\n if (...
2022/10/28
[ "https://Stackoverflow.com/questions/74239914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2453581/" ]
74,239,924
<p>I'm receiving the following variable with a type of text/plain with newline characters (\r\n) in my js lambda, But I need to convert it to a json with JS</p> <p>input</p> <pre><code>{&quot;body&quot;: &quot;TokenId=dsbfjj&amp;s=b+j%f-b*sfwe1we\r\nTaskid=\r\valueP=12345\r\nvalueN=89542fgdfgdf\r\n&quot;} </code></pre> <p>output:</p> <pre><code>{ &quot;body&quot;:{ &quot;TokenId&quot;:&quot;sbfjj&amp;s=b+j%f-b*sfwe1we&quot;, &quot;Taskid&quot;:&quot;&quot;, &quot;valueP&quot;:&quot;12345&quot;, &quot;valueN&quot;:&quot;89542fgdfgdf&quot; } } </code></pre>
[ { "answer_id": 74239930, "author": "Kai Steinke", "author_id": 12554273, "author_profile": "https://Stackoverflow.com/users/12554273", "pm_score": 3, "selected": true, "text": "function flatten($arr, $prefix = '') {\n $result = [];\n foreach ($arr as $key => $value) {\n if (...
2022/10/28
[ "https://Stackoverflow.com/questions/74239924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9263321/" ]
74,239,928
<pre><code>class A: def m(self, v): for i in range(v): print(&quot;A&quot;) self.m(v-1) class B(A): def m(self, value): print(&quot;B&quot;) super(B, self).m(value) B().m(3) </code></pre> <p>Output: <code>B A B A B A</code></p> <p>Expected output: <code>BAAAA</code></p> <p>On class A, the self object is of B and it's calling method m of class B, but I don't want this to happen.</p> <p>I know I can change the method name, but that is a constraint, I can not change the name of method.</p>
[ { "answer_id": 74240873, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "class A:\n def m(self, v, count=0):\n for i in range(v):\n print(\"A\")\n self.m...
2022/10/28
[ "https://Stackoverflow.com/questions/74239928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6459622/" ]
74,239,938
<p>I made a responsive web page and started from phones and small devices first then moved up to desktops view. But the problem is when I began designing how it should look on desktops and big screens I thought that I had only to make my nav bar displays again by changing this CSS line inside media queries to <code>#myLinks {display: block;}</code> or <code>#myLinks {display: flex;}</code> so it becomes visible again, yet nothing is happening. Note that the display value was set to none because in phones and tablets the nav bar could only show up by clicking the burger icon. And in desktops, I don't want the menu icon to be displayed and I want the nav bar to be displayed as a row on top of the page.</p> <p><strong>Link to the full code inside my GitHub repository :</strong> <a href="https://github.com/IssamAth/Waitlist-page/tree/master/src/components/navbarlogo" rel="nofollow noreferrer">https://github.com/IssamAth/Waitlist-page/tree/master/src/components/navbarlogo</a></p> <p><strong>Here is the CSS code for the Nav bar</strong>,</p> <pre><code>#myLinks { display: none; } #navbarlogo { margin: 1rem 0 4rem 0; } .logo-menu { display: flex; justify-content: space-between; } nav { text-decoration: none; background: black; border-radius: 0.5rem; margin: 1rem 0; } .icon { color: black; } .logo { display: inline-block; } li a:link {color:#FFFAFA;} li a:visited {color:#FFFAFA;} li { padding: 1rem; } /* MEDIA QUERIES ================ ( For Mobiles ) ================ */ @media screen and (min-width: 1024px) { #myLinks { } nav { margin: 0; background: var(--color-bg); } li a:link {color:var(--color-primary);} li a:visited {color:var(--color-primary);} .icon { display: none; } #navbarlogo { display: flex; justify-content: space-between; } .topnav #myLinks { display: flex; } .topnav { } #navbarlogo { } } </code></pre> <p><strong>Here is the layout</strong></p> <pre><code>function myFunction() { var x = document.getElementById(&quot;myLinks&quot;); if (x.style.display === &quot;block&quot;) { x.style.display = &quot;none&quot;; } else { x.style.display = &quot;block&quot;; } } const navbarlogo = () =&gt; { return ( &lt;div id='navbarlogo'&gt; &lt;div className=&quot;logo-menu&quot;&gt; &lt;div className='logo'&gt; &lt;img src={logo} alt=&quot;&quot; /&gt; &lt;/div&gt; &lt;a href=&quot;#&quot; class=&quot;icon&quot; onClick={myFunction}&gt; &lt;GiHamburgerMenu size = '28'/&gt; &lt;/a&gt; &lt;/div&gt; &lt;nav class=&quot;topnav&quot;&gt; &lt;ul id=&quot;myLinks&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Features&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Affiliates&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Pricing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Communities&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Join Waitlist&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; ) } </code></pre> <p><strong>This is how it shows when I stretch the screen and the nav bar doesn't show up</strong></p> <p><a href="https://i.stack.imgur.com/L00Ey.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L00Ey.png" alt="enter image description here" /></a></p> <p><strong>And this how it displays in smaller screens</strong></p> <p><a href="https://i.stack.imgur.com/z1crB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z1crB.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74240120, "author": "tadej", "author_id": 11317165, "author_profile": "https://Stackoverflow.com/users/11317165", "pm_score": 2, "selected": true, "text": ".mylinks{\n display: block;\n}\n\n.topnav{\n display: flex;\n}\n\n.topnavhide{\n display: none;\n}\n\n#navbarlogo ...
2022/10/28
[ "https://Stackoverflow.com/questions/74239938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17345724/" ]
74,239,949
<p>How do I tell the compiler that one lifetime must outlive another?</p> <pre><code>use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct Tokens&lt;'a&gt; { buffer: String, list: Vec&lt;Token&lt;'a&gt;&gt;, } #[derive(Serialize, Deserialize, Debug)] pub struct Token&lt;'a&gt; { term: &amp;'a str, } </code></pre> <p>yields</p> <pre><code>error: lifetime may not live long enough --&gt; src/pipeline/tokenizers/test.rs:6:5 | 3 | #[derive(Serialize, Deserialize, Debug)] | ----------- lifetime `'de` defined here 4 | pub struct Tokens&lt;'a&gt; { | -- lifetime `'a` defined here 5 | buffer: String, 6 | list: Vec&lt;Token&lt;'a&gt;&gt;, | ^^^^ requires that `'de` must outlive `'a` | = help: consider adding the following bound: `'de: 'a` </code></pre> <p>In the code above, the token.term: &amp;str will always refer to a slice of tokens.buffer. I'm not sure how to specify that relationship. I'm also not sure how to add the requested bound.</p> <p>Will this even work? If so, what's the magic syntax?</p>
[ { "answer_id": 74239960, "author": "Peter Hall", "author_id": 493729, "author_profile": "https://Stackoverflow.com/users/493729", "pm_score": 3, "selected": true, "text": "#[serde(borrow)]" }, { "answer_id": 74239983, "author": "Silvio Mayolo", "author_id": 2288659, "...
2022/10/28
[ "https://Stackoverflow.com/questions/74239949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237815/" ]
74,239,959
<p>I am trying to create a program that does a binary search of array of randomly generated doubles and when I try to run the code, I get this error.</p> <pre><code>Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: Index 9999 out of bounds for length 9999 at Search.binarySearch(Search.java:34) at Search.main(Search.java:17) </code></pre> <p>I tried changing the array size and making it smaller and bigger, but I always get a error. I don't know what less I can do. Here is the code.</p> <pre><code>import java.lang.Math; import java.util.Arrays; import java.util.Random; class Search{ public static void main(String [] args){ double [] array2 = new double [9999]; for(int i = 0; i &lt;array2.length;i++){ array[i] = (double) (Math.random() * 9999); } Arrays.sort(array); System.out.println(binarySearch(array, new Random().nextDouble(9999))); } public static int binarySearch(double [] array, double find){ int first = 0; int last = array.length; int mid = (first + last ) / 2; while(first &lt;= last){ if(array[mid] &lt; last){ first = mid +1; }else if(array[mid] == find){ return mid; }else{ last = mid -1; } mid = (first + last) / 2; } if(first &gt; last){ return -1; } return -1; } } </code></pre> <p>How it is supposed to work that it takes the array of doubles and a random number to find if the number is in the array, if it is returns the index, if its not in the array, it returns -1. I have a linear search method that works but for some reason this won't work. Thank you</p>
[ { "answer_id": 74240107, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n double[] arr = new double[9999];\n Random random = new Rando...
2022/10/28
[ "https://Stackoverflow.com/questions/74239959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20200634/" ]
74,239,961
<p>I have a Pandas dataframe that looks like this:</p> <pre><code>import pandas as pd data = { 'a' : [['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69]], 'b' : [['YLK', 44.48, -79.55], ['HG76', 44.60, -65.76], ['DEF', 49.52, -113.99], ['YXZ', 47.96, -84.78]], 'c' : [1628.931942, 1949.748061, 2556.622213, 301.193418] } df = pd.DataFrame(data) df a b c 0 [Foo, 49.51, -120.69] [YLK, 44.48, -79.55] 1628.931942 1 [Foo, 49.51, -120.69] [HG76, 44.6, -65.76] 1949.748061 2 [Foo, 49.51, -120.69] [DEF, 49.52, -113.99] 2556.622213 3 [Foo, 49.51, -120.69] [YXZ, 47.96, -84.78] 301.193418 </code></pre> <p>I would like to split out columns <code>a</code> and <code>b</code> such that their elements become their own columns, like this:</p> <pre><code> a b c d e f g 0 Foo 49.51 -120.69 YLK 44.48 -79.55 1628.931942 1 Foo 49.51 -120.69 HG76 44.6 -65.76 1949.748061 2 Foo 49.51 -120.69 DEF 49.52 -113.99 2556.622213 3 Foo 49.51 -120.69 YXZ 47.96 -84.78 301.193418 </code></pre> <p>How would I do this?</p> <p>Thanks!</p>
[ { "answer_id": 74240107, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n double[] arr = new double[9999];\n Random random = new Rando...
2022/10/28
[ "https://Stackoverflow.com/questions/74239961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18908491/" ]
74,240,008
<p>I'm having a problem that the mutable state ignores first value if set two values in a row. I assume it's expected behaviour, just wondering if there is a clean workaround for that? I have this code:</p> <pre><code> var userState by mutableStateOf&lt;UserData?&gt;(null) fun clearState() { userState = null // clear user state cleanInnerState() // Set next user state if exist stateQueue.poll()?.let { userState = it } } @Composable fun ProfileScreen() { val userData = store.userState if(userData == null){ clearViewModelState() } else { UserUI(userData) } } </code></pre> <p>The problem that when we set the state value to null and then we set new state in a row it ignores the null value and observers the last set value only.</p>
[ { "answer_id": 74240076, "author": "Mike", "author_id": 2004073, "author_profile": "https://Stackoverflow.com/users/2004073", "pm_score": 1, "selected": false, "text": "if(userData == null){\n clearViewModelState()\n }\n" } ]
2022/10/28
[ "https://Stackoverflow.com/questions/74240008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5236016/" ]
74,240,015
<p>By generic; I mean to say that I do not know the name of a column that needs to be dropped ahead of pulling in the file. Examples I have found; assume that you know the name of a column you wish to drop. Those familiar with the PlayTennis data set are probably used to seeing:</p> <pre><code>my_df = pd.DataFrame({&quot;Outlook&quot;: [Sunny,Cloudy,Rainy], &quot;Temp&quot;:[Hot,Cold], &quot;Humidity&quot;:[high,low]...}) </code></pre> <p>However in my class we get a first column 'Days' so something like:</p> <pre><code>my_df = pd.DataFrame({&quot;Days&quot;:[D1,D2,...,D14],&quot;Outlook&quot;: [Sunny,Cloudy,Rainy], &quot;Temp&quot;:[Hot,Cold],&quot;Humidity&quot;:[high,low]...}) </code></pre> <p>Obviously, looking at this I would want to drop the 'Days' column:</p> <pre><code>df.drop(columns=['Days'], inplace=True) </code></pre> <p>The problem is that playtennis is just a sample dataset and in the actual dataset the column I may need to drop for the same reason as 'Days' will not be called Days. I need a way to drop the useless column by some method that can see that the number of unique values in a column and understands its too many to be useful (Edit: Meaning it overfits, if I have 30 instances and 30 days the model will try to predict a result based on what day it is and therefore, useless for predictability); Before I read it into my machine learning algorithm.</p> <pre><code>import pandas as pd import numpy as np df_train = pd.read_csv(&quot;assets\playtennis.csv&quot;) # read in data df_train.head() # see first 5 # get a list of attribute excluding the class label (e.g.,PlayTennis) def attributes (df,label): return df.columns.drop(label).values.tolist() def trash(df,attr,label): # Do something to trash useless columns df.drop(columns=[x],inplace=True) class_label = df_train.columns[-1] # class label in the last column attr = attributes(df_train,class_label) trash(df_train,attr,class_label) </code></pre> <p>I only have about 6 weeks working with python so please forgive(and point out) syntax errors.</p>
[ { "answer_id": 74240257, "author": "bitflip", "author_id": 20027803, "author_profile": "https://Stackoverflow.com/users/20027803", "pm_score": 0, "selected": false, "text": "understands its too many to be useful" }, { "answer_id": 74240283, "author": "Max Bileschi", "auth...
2022/10/28
[ "https://Stackoverflow.com/questions/74240015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13436929/" ]
74,240,046
<p>I'm working on snowflake to solve a problem. I wanted to find the number of events for the first 24 hours for each user id.</p> <p>This is a snippet of the database table I'm working on. I modified the table and used a date format without the time for simplification purposes.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>client_event_time</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-07-28</td> </tr> <tr> <td>1</td> <td>2022-07-29</td> </tr> <tr> <td>1</td> <td>2022-08-21</td> </tr> <tr> <td>2</td> <td>2022-07-29</td> </tr> <tr> <td>2</td> <td>2022-07-30</td> </tr> <tr> <td>2</td> <td>2022-08-03</td> </tr> </tbody> </table> </div> <p>I used the following approach to find the minimum event time per user_id.</p> <pre><code>SELECT user_id, client_event_time, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY client_event_time) row_number, MIN(client_event_time) OVER (PARTITION BY user_id) MinEventTime FROM Data ORDER BY user_id, client_event_time; </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>client_event_time</th> <th>row_number</th> <th>MinEventTime</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2022-07-28</td> <td>1</td> <td>2022-07-28</td> </tr> <tr> <td>1</td> <td>2022-07-29</td> <td>2</td> <td>2022-07-28</td> </tr> <tr> <td>1</td> <td>2022-08-21</td> <td>3</td> <td>2022-07-28</td> </tr> <tr> <td>2</td> <td>2022-07-29</td> <td>1</td> <td>2022-07-29</td> </tr> <tr> <td>2</td> <td>2022-07-30</td> <td>2</td> <td>2022-07-29</td> </tr> <tr> <td>2</td> <td>2022-08-03</td> <td>3</td> <td>2022-07-29</td> </tr> </tbody> </table> </div> <p>Then I tried to find the difference between the minimum event time and client_event_time, and if the difference is less than or equal to 24, I counted the client_event_time.</p> <pre><code>with NewTable as ( (SELECT user_id,client_event_time, event_type, row_number() over (partition by user_id order by CLIENT_EVENT_TIME) row_number, MIN(client_event_time) OVER (PARTITION BY user_id) MinEventTime FROM Data ORDER BY user_id, client_event_time)) SELECT user_id, COUNT(case when timestampdiff(hh, client_event_time, MinEventTime) &lt;= 24 then 1 else 0 end) AS duration FROM NEWTABLE GROUP BY user_id </code></pre> <p>I got the following result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>duration</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>3</td> </tr> </tbody> </table> </div> <p>I wanted to find the following result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>duration</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>2</td> </tr> </tbody> </table> </div> <p>Could you please help me solve this problem? Thanks!</p>
[ { "answer_id": 74240241, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "WITH min_data as\n(SELECT user_id,MIN(client_event_time) mindate FROM data GROUP BY user_id)\n SELECT d.user_id, COUNT(...
2022/10/28
[ "https://Stackoverflow.com/questions/74240046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17109107/" ]
74,240,050
<p>I'm trying to get some images from an API but facing this error</p> <pre><code>[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'Map&lt;dynamic, dynamic&gt;' </code></pre> <p>The Json from the API looks like this and it's from <a href="https://www.themoviedb.org/" rel="nofollow noreferrer">www.themoviedb.org</a>:</p> <pre><code>{ &quot;page&quot;: 1, &quot;results&quot;: [ { &quot;adult&quot;: false, &quot;backdrop_path&quot;: &quot;/qxeqKcVBWnQxUp1w6fwWcxZEA6m.jpg&quot;, &quot;genre_ids&quot;: [ 28, 12, 14 ], &quot;id&quot;: 436270, &quot;original_language&quot;: &quot;en&quot;, &quot;original_title&quot;: &quot;Black Adam&quot;, &quot;overview&quot;: &quot;Nearly 5,000 years after he was bestowed with the almighty powers of the Egyptian gods—and imprisoned just as quickly—Black Adam is freed from his earthly tomb, ready to unleash his unique form of justice on the modern world.&quot;, &quot;popularity&quot;: 6041.545, &quot;poster_path&quot;: &quot;/3zXceNTtyj5FLjwQXuPvLYK5YYL.jpg&quot;, &quot;release_date&quot;: &quot;2022-10-19&quot;, &quot;title&quot;: &quot;Black Adam&quot;, &quot;video&quot;: false, &quot;vote_average&quot;: 7.2, &quot;vote_count&quot;: 425 }, ], &quot;total_pages&quot;: 35601, &quot;total_results&quot;: 712013 } </code></pre> <p>Here is the code:</p> <p><strong>Movie</strong></p> <pre><code>class Movie { final int id; final String name; final String description; final String? posterPath; //&lt;editor-fold desc=&quot;Data Methods&quot;&gt; Movie({ required this.id, required this.name, required this.description, this.posterPath, }); Movie copyWith({ int? id, String? name, String? description, String? posterPath, }) { return Movie( id: id ?? this.id, name: name ?? this.name, description: description ?? this.description, posterPath: posterPath ?? this.posterPath, ); } factory Movie.fromJson(Map&lt;String, dynamic&gt; map) { return Movie( id: map['id'] as int, name: map['title'] as String, description: map['overview'] as String, posterPath: map['poster_path'] as String, ); } // Poster url **************************************************************** String posterUrl() { Api api = Api(); return api.baseUrl + posterPath!; } //&lt;/editor-fold&gt; } </code></pre> <p><strong>API</strong></p> <pre><code>class Api { final String apiKey = ApiKey.apiKey; final String baseUrl = &quot;https://developers.themoviedb.org/3&quot;; final String baseImageUrl = &quot;https://image.tmdb.org/t/p/w500/&quot;; final String baseVideoUrl = &quot;https://www.youtube.com/watch?=v&quot;; } </code></pre> <p><strong>ApiKey</strong></p> <pre><code>class ApiKey { static String apiKey = &quot;my_api_key&quot;; } </code></pre> <p><strong>ApiService</strong></p> <pre><code>class ApiService { final Api api = Api(); final Dio dio = Dio(); Future&lt;Response&gt; getData(String path, {Map&lt;String, dynamic&gt;? params}) async { String url = api.baseUrl + path; Map&lt;String, dynamic&gt; query = { &quot;api_key&quot;: api.apiKey, &quot;language&quot;: &quot;en-US&quot;, }; if(params != null) { query.addAll(params); } final response = await dio.get(url, queryParameters: query); if(response.statusCode == 200) { return response; } else { throw response; } } //**************************************************************************** // Get popular movies //**************************************************************************** Future getPopularMovies({required int pageNumber}) async{ Response response = await getData( &quot;/movie/popular&quot;, params: { &quot;page&quot;: pageNumber, } ); if(response.statusCode == 200){ Map data = response.data; // &lt;--------------------------- Problem is here List&lt;dynamic&gt; results = data[&quot;results&quot;]; // &lt;--------------------------- And here List&lt;Movie&gt; movies = []; for(Map&lt;String, dynamic&gt; json in results){ Movie movie = Movie.fromJson(json); movies.add(movie); } return movies; } else{ throw response; } } } </code></pre> <p><strong>HomeScreen</strong></p> <pre><code>class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key); @override State&lt;HomeScreen&gt; createState() =&gt; _HomeScreenState(); } class _HomeScreenState extends State&lt;HomeScreen&gt; { List&lt;Movie&gt;? movies; @override void initState() { super.initState(); getMovies(); } //**************************************************************************** // Get movies //**************************************************************************** void getMovies(){ ApiService().getPopularMovies(pageNumber: 1) .then((movieList){ setState(() { movies = movieList; }); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: kBackgroundColor, appBar: AppBar( backgroundColor: kBackgroundColor, leading: Image.asset( &quot;assets/images/netflix_logo_2.png&quot; ), ), body: ListView( children: [ Container( height: 500, color: Colors.red, child: movies == null ? const Center() : Image.network( movies![0].posterUrl(), fit: BoxFit.cover, ), ), const SizedBox(height: 15,), Text(&quot;Current trends&quot;, style: GoogleFonts.poppins( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold ), ), const SizedBox(height: 5,), SizedBox( height: 160, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { return Container( width: 110, margin: const EdgeInsets.only(right: 8), color: Colors.yellow, child: Center( child: Text(index.toString()), ), ); }, ), ), const SizedBox(height: 15,), Text(&quot;Currently in cinema&quot;, style: GoogleFonts.poppins( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold ), ), const SizedBox(height: 5,), SizedBox( height: 320, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { return Container( width: 220, margin: const EdgeInsets.only(right: 8), color: Colors.blue, child: Center( child: Text(index.toString()), ), ); }, ), ), const SizedBox(height: 15,), Text(&quot;Available soon&quot;, style: GoogleFonts.poppins( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold ), ), const SizedBox(height: 5,), SizedBox( height: 160, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { return Container( width: 110, margin: const EdgeInsets.only(right: 8), color: Colors.green, child: Center( child: Text(index.toString()), ), ); }, ), ), ], ), ); } } </code></pre> <p><strong>What I've tried:</strong></p> <p>I've tried to replace <code>Map</code> with <code>var</code> in ApiService but the problem isn't solved because another error is shown in the logcat doing this:</p> <p>[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'</p> <p>Thanks in advance for the help</p>
[ { "answer_id": 74240241, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "WITH min_data as\n(SELECT user_id,MIN(client_event_time) mindate FROM data GROUP BY user_id)\n SELECT d.user_id, COUNT(...
2022/10/28
[ "https://Stackoverflow.com/questions/74240050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15995870/" ]
74,240,057
<p>I am trying to write the tests for the NavBar component (using react-native-testing-library) that has several buttons that are basically just icons (using ui-kitten for react native). So I can't get these buttons by text (as there is none) but other methods didn't work for me either (like adding accesibilityLabel or testID and then getting by the label text / getting by test ID). Any ideas what I am doing wrong?</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>// NavBar.tsx import React from 'react'; import {View, StyleSheet} from 'react-native'; import {HomeBtn, SaveBtn} from '../components/buttons'; import UserSignOut from './UserSignOut'; const NavBar = ({ navigation, pressHandlers, }) =&gt; { return ( &lt;View style={styles.navBar}&gt; &lt;View&gt; &lt;HomeBtn navigation={navigation} /&gt; &lt;SaveBtn pressHandler={pressHandlers?.saveBtn ?? undefined} /&gt; &lt;/View&gt; &lt;UserSignOut /&gt; &lt;/View&gt; ); }; export default NavBar; // HomeBtn.tsx import React from 'react'; import {Button} from '@ui-kitten/components'; import {HomeIcon} from '../shared/icons'; import styles from './Btn.style'; export const HomeBtn = ({navigation}: any) =&gt; { return ( &lt;Button accesibilityLabel="home button" style={styles.button} accessoryLeft={props =&gt; HomeIcon(props, styles.icon)} onPress={() =&gt; navigation.navigate('Home')} /&gt; ); }; // NavBar.test.tsx import React from 'react'; import {render, screen} from '@testing-library/react-native'; import * as eva from '@eva-design/eva'; import {RootSiblingParent} from 'react-native-root-siblings'; import {EvaIconsPack} from '@ui-kitten/eva-icons'; import {ApplicationProvider, IconRegistry} from '@ui-kitten/components'; import NavBar from '../../containers/NavBar'; describe('NavBar', () =&gt; { const navBarContainer = ( &lt;RootSiblingParent&gt; &lt;IconRegistry icons={EvaIconsPack} /&gt; &lt;ApplicationProvider {...eva} theme={eva.light}&gt; &lt;NavBar /&gt; &lt;/ApplicationProvider&gt; &lt;/RootSiblingParent&gt; ); it('should render the buttons', async () =&gt; { render(navBarContainer); // this test fails (nothing is found with this accesibility label) await screen.findByLabelText('home button'); }); });</code></pre> </div> </div> </p>
[ { "answer_id": 74240241, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "WITH min_data as\n(SELECT user_id,MIN(client_event_time) mindate FROM data GROUP BY user_id)\n SELECT d.user_id, COUNT(...
2022/10/28
[ "https://Stackoverflow.com/questions/74240057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16537918/" ]
74,240,161
<pre class="lang-cs prettyprint-override"><code>public static Product[] LoadItems() { //method to return array contents of vending machine return new Product[] { new Product() { name = &quot;Cheese&quot;, price = 2.0M }, new Product() { name = &quot;Salami&quot;, price = 1.5M }, new Product() { name = &quot;Kitkat&quot;, price = 1.0M }, new Product() { name = &quot;Fanta&quot;, price = 1.8M }, new Product() { name = &quot;Sharp hamburger&quot;, price = 4.3M }, new Product() { name = &quot;Coconut water&quot;, price = 0.8M }, new Product() { name = &quot;Crackers&quot;, price = 2.0M }, new Product() { name = &quot;Orange juice&quot;, price = 0.75M }, new Product() { name = &quot;Water&quot;, price = 0.6M } }; } static void Main(string[] args) { //creates array named machine using LoadItems Product[] machine = LoadItems(); Console.WriteLine(&quot;Welcome to the vending machine. The products available are:&quot;); for (int i = 0; i &lt; machine.Length; i++) { Console.WriteLine(machine[i]); } } </code></pre> <p>I would like to display the items and prices, however I am unsure on how to do this.</p> <p>I believe it may be an error with my formatting of <code>Console.WriteLine(machine[i]);</code></p>
[ { "answer_id": 74240241, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "WITH min_data as\n(SELECT user_id,MIN(client_event_time) mindate FROM data GROUP BY user_id)\n SELECT d.user_id, COUNT(...
2022/10/28
[ "https://Stackoverflow.com/questions/74240161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352891/" ]
74,240,167
<p>basically I'm making a page where the information from mySQL database will be displayed. I have a column named <strong>topics</strong> in the database where the string (VARCHAR) goes like this:</p> <blockquote> <p>Marketing, Business, Law, Medicine, ...</p> </blockquote> <p>I'm trying to break up this string after a comma and display them in a single line one by one like this:</p> <pre><code>&lt;h6&gt;Marketing&lt;/h6&gt; &lt;h6&gt;Business&lt;/h6&gt; &lt;h6&gt;Law&lt;/h6&gt; &lt;h6&gt;Medicine&lt;/h6&gt; &lt;h6&gt;...&lt;/h6&gt; </code></pre> <p>I already have a loop for other rows and I'm not sure if it's possible to make a loop in the loop, I'm not even sure if what i'm trying to achieve is possible but I belive it is. Here goes my full PHP code:</p> <pre><code>&lt;?php include_once '../handlers/db_conn.php'; $sql = $conn-&gt;prepare(&quot;SELECT * FROM esc WHERE hosting_country = ?&quot;); $sql-&gt;bind_param(&quot;s&quot;, $hosting_country); $hosting_country = 'Poland'; $sql-&gt;execute(); $result = $sql-&gt;get_result(); $resultCheck = mysqli_num_rows($result); if ($resultCheck &gt; 0) { } else { echo '&lt;p class=&quot;not_found&quot;&gt;Nothing Found&lt;/p&gt;'; } while($escrow = $result-&gt;fetch_assoc()) { ?&gt; &lt;div class=&quot;col-lg-6 col-md-12 col-sm-12 col-12&quot;&gt; &lt;div class=&quot;sec1_col1&quot;&gt; &lt;h2&gt;&lt;?php echo $escrow['project_name'] ?&gt;&lt;/h2&gt; &lt;i class=&quot;fi fi-br-world&quot;&gt;&lt;/i&gt; &lt;h3&gt;&lt;?php echo $escrow['hosting_country'] ?&gt;&lt;/h3&gt; &lt;i class=&quot;fi fi-sr-calendar-lines&quot;&gt;&lt;/i&gt; &lt;h3&gt;&lt;?php echo $escrow['start_date'] ?&gt; - &lt;?php echo $escrow['end_date'] ?&gt;&lt;/h3&gt; &lt;h4 class=&quot;objectives&quot;&gt;&lt;?php echo $escrow['objectives'] ?&gt;&lt;/h4&gt; &lt;h5&gt;Topics&lt;/h5&gt; &lt;h6&gt;&lt;?php echo $escrow['topics'] ?&gt;&lt;/h6&gt; &lt;hr&gt; &lt;a href=&quot;#&quot;&gt;Read more&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I'm wondering if it's possible to create another loop in this loop for element, separate this string after a comma and display one by one in tag? Any help would be greatly appreciated. Thanks.</p> <p><strong>EDIT</strong></p> <p>This is what I'm trying to achieve:</p> <p><a href="https://i.stack.imgur.com/CRAPY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CRAPY.png" alt="This is how I want it to look" /></a></p>
[ { "answer_id": 74240231, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$topics = 'Marketing, Business, Law, Medicine';\necho join(PHP_EOL, array_map(fn($topic) => '<h6>'. trim($topi...
2022/10/28
[ "https://Stackoverflow.com/questions/74240167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16722286/" ]
74,240,175
<p>I just started coding in android studio and was creating calculator but now I'm stuck on one problem.</p> <p>after struggling a lot I figured out how to make so u can use one dot but now I came across another problem which is after addition I cant seem to round up the decimals. when I do additions in decimals sometimes it gives me something like 1.9999999998 and I cant seem to round it up. for the reference I used Table Row in xml. if necessary I can show you what I have written so far. Thanks in advance.</p>
[ { "answer_id": 74240231, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$topics = 'Marketing, Business, Law, Medicine';\necho join(PHP_EOL, array_map(fn($topic) => '<h6>'. trim($topi...
2022/10/28
[ "https://Stackoverflow.com/questions/74240175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20263059/" ]