qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,567,456
<p>I need to break from a for loop on a given UI event. I worked out the approach shown below; however, it is unpredictable and I have a sense that this is not the right way to do this.</p> <p>In this minimal example I break from the for loop when the user clicks the document by awaiting a setTimeout at each iteration of the for loop. This await allows for <code>stop</code> to be set to <code>true</code>, which causes the break to happen.</p> <p>This for loop just logs a zero to the console. A more practical use case may be to stop adding list elements to an unordered list given a UI event e.g., the keypress event.</p> <pre><code>let zeros = new Array(10000).fill(0); (async () =&gt; { let stop = false; document.addEventListener('click', async ()=&gt;{ console.log('click'); stop = true; await new Promise((r)=&gt;setTimeout(r, 100)); //2 stop = false; }); for (let zero of zeros) { await new Promise((r)=&gt;setTimeout(r, 100)); //1 if (stop) { break; } console.log(zero); } })(); </code></pre>
[ { "answer_id": 74567501, "author": "Đạt Huỳnh", "author_id": 20595083, "author_profile": "https://Stackoverflow.com/users/20595083", "pm_score": 2, "selected": false, "text": "function Rotate(str){\n return str.substring(1)+str[0]\n}\n" }, { "answer_id": 74567509, "author": "Alberto Chiesa", "author_id": 1395758, "author_profile": "https://Stackoverflow.com/users/1395758", "pm_score": 1, "selected": false, "text": "function Rotate(str) {\n var initial, rest;\n initial = str.charAt(0);\n // if you don't pass the second argument, you get everything up to the end of the string\n rest = str.substring(1);\n return rest + initial;\n}\n\n// please note you don't need separate var statements:\nfunction Rotate(str) {\n var initial = str.charAt(0);\n var rest = str.substring(1);\n return rest + initial;\n}\n\n// or:\nfunction Rotate(str) {\n // substring from the second char + substring of the first char\n return str.substring(1) + str.substring(0, 1);\n}\n\n// you could even extend Rotate to support multiple chars:\nfunction Rotate(str, count) {\n if (count === undefined) count = 1;\n return str.substring(count) + str.substring(0, count);\n}\n\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12465038/" ]
74,567,521
<p>I am wondering why this brute force approach to a Maximum Sum Subarray of Size K problem is of time complexity n<em>k instead of (n-k)k. Given that we are subtracting K elements from the outer most loop wouldn't the latter be more appropriate? The text solution mentions n</em>k and confuses me slightly.</p> <p>I have included the short code snippet below!</p> <p>Thank you</p> <pre><code>def max_sub_array_of_size_k(k, arr): max_sum = 0 window_sum = 0 for i in range(len(arr) - k + 1): window_sum = 0 for j in range(i, i+k): window_sum += arr[j] max_sum = max(max_sum, window_sum) return max_sum </code></pre> <p>I haven't actually tried to fix this, I just want to understand.</p>
[ { "answer_id": 74567748, "author": "sean", "author_id": 20261837, "author_profile": "https://Stackoverflow.com/users/20261837", "pm_score": 1, "selected": false, "text": "def max_sub_array_of_size_k(k, arr):\n s = [0]\n for i in range(len(arr)):\n # sum[i] = sum of arr[0] + ... + arr[i]\n s.append(s[-1] + arr[i]) \n \n max_sum = float(\"-inf\")\n for i in range(1, len(s) + 1 - k):\n max_sum = max(max_sum, s[i + k - 1] - s[i - 1])\n return max_sum\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7214510/" ]
74,567,576
<p>I have following regex.</p> <pre><code>^(.*[^0-9])([0-9A-Fa-f]{8}[-]?[0-9A-Fa-f]{4}[-]?[0-9A-Fa-f]{4}[-]?[0-9A-Fa-f]{4}[-]?[0-9A-Fa-f]{12})(.*)$ </code></pre> <p>It splits a given text into 3 groups. <code>1:Pre-GUID</code>, <code>2:GUID</code> and <code>3:post-GUID</code> text.</p> <pre><code>Input: /user/questions/9c8a8823-d88c-4402-a2c1-4530a966f993/help Results: Group 1: /user/questions/ Group 2: 9c8a8823-d88c-4402-a2c1-4530a966f993 Group 3: /help </code></pre> <p>However, I have some instances where GUID is followed by a special character such as <code>@</code> and in that case I want to ignore everything after GUID ignored i.e. 3rd group that is post GUID be empty.</p> <pre><code>Input: /user/questions/9c8a8823-d88c-4402-a2c1-4530a966f993@help Results: Group 1: /user/questions/ Group 2: 9c8a8823-d88c-4402-a2c1-4530a966f993 Group 3: </code></pre> <p>In other terms i don't want regex to consider anything if it encounters a <code>@</code>.</p>
[ { "answer_id": 74567748, "author": "sean", "author_id": 20261837, "author_profile": "https://Stackoverflow.com/users/20261837", "pm_score": 1, "selected": false, "text": "def max_sub_array_of_size_k(k, arr):\n s = [0]\n for i in range(len(arr)):\n # sum[i] = sum of arr[0] + ... + arr[i]\n s.append(s[-1] + arr[i]) \n \n max_sum = float(\"-inf\")\n for i in range(1, len(s) + 1 - k):\n max_sum = max(max_sum, s[i + k - 1] - s[i - 1])\n return max_sum\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971741/" ]
74,567,578
<pre><code>Dictionary = {File1: &quot;location1&quot;, File2: &quot;location2&quot;, File3: &quot;location3&quot;} def fancy_function1(location, file): df = pd.read_csv(location) df[&quot;new_column&quot;] = df[file] return df </code></pre> <p><strong>need help needed writing this for loop or any other suggestions</strong></p> <pre><code>for key in Dictionary: ##pass key value pairs into function df = fancy_function(key, value) return df </code></pre> <p>I want to then merge all 3 dataframes (created from fancy_function()) or assign each dataframe to variables e.g. df1, df2, df3 etc.</p>
[ { "answer_id": 74567748, "author": "sean", "author_id": 20261837, "author_profile": "https://Stackoverflow.com/users/20261837", "pm_score": 1, "selected": false, "text": "def max_sub_array_of_size_k(k, arr):\n s = [0]\n for i in range(len(arr)):\n # sum[i] = sum of arr[0] + ... + arr[i]\n s.append(s[-1] + arr[i]) \n \n max_sum = float(\"-inf\")\n for i in range(1, len(s) + 1 - k):\n max_sum = max(max_sum, s[i + k - 1] - s[i - 1])\n return max_sum\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14877482/" ]
74,567,593
<p>Trying to create a responsive sidebar, i want some things to be hidden when it's closed, and show when it's opened. I trying to do it with the get, set and remove Attribute, but it doesn't work. The tags already have the hidden attribute in them.</p> <pre><code>const menu = document.querySelector(&quot;.menu&quot;); const sidebar = document.querySelector(&quot;.sidebar&quot;); const hidden = document.querySelectorAll(&quot;.hiddens&quot;); menu.addEventListener(&quot;click&quot;, sidebarWidth) function sidebarWidth(){ if(sidebar.style[&quot;width&quot;] == &quot;5.5vw&quot;){ sidebar.style[&quot;width&quot;] = &quot;18vw&quot;; show(); } else { sidebar.style[&quot;width&quot;] = &quot;5.5vw&quot;; hide(); } } function show(){ hidden.getAttribute(&quot;hidden&quot;); hidden.removeAttribute(&quot;hidden&quot;); } function hide(){ hidden.setAttribute(&quot;hidden&quot;); } </code></pre> <p>Tried using the set, get and remove attribute in the sidebarWidth function, tried creating another event just for them, tried it how it is now, none worked. What's wrong?</p>
[ { "answer_id": 74567614, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "hidden document.querySelectorAll setAttribute function show(){\n for(let i=0;i<hidden.length;i++){\n hidden[i].setAttribute(\"hidden\",true);\n }\n}\n\nfunction hide(){\n for(let i=0;i<hidden.length;i++){\n hidden[i].setAttribute(\"hidden\",false);\n }\n}\n" }, { "answer_id": 74567619, "author": "Josiah", "author_id": 20463298, "author_profile": "https://Stackoverflow.com/users/20463298", "pm_score": 1, "selected": false, "text": "hidden queryselectorAll(\".hiddens\") .hiddens const hidden = document.querySelectorAll(\".hiddens\");\n\nfunction show(){\n for(let i of hidden){\n i.hidden= false\n }\n}\n\nfunction hide(){\n for(let i of hidden){\n i.hidden= true\n }\n}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20594073/" ]
74,567,597
<p>Hello guys I'm learning Angular and we created a HeroesApp but my routerLink doesn't work, I imported and exported my routerModule and I don't know how can I fix it. <a href="https://i.stack.imgur.com/KU1A6.png" rel="nofollow noreferrer"><code>auth-routing.module.ts</code></a> <a href="https://i.stack.imgur.com/GhxZN.png" rel="nofollow noreferrer"><code>auth-routing.module.ts part2</code> </a> <a href="https://i.stack.imgur.com/z26r4.png" rel="nofollow noreferrer"><code>folders</code></a></p> <p>for the moment I tried this other route thinking I had a problem with the route I posted (<a href="https://i.stack.imgur.com/aYQDb.png" rel="nofollow noreferrer">https://i.stack.imgur.com/aYQDb.png</a>)</p>
[ { "answer_id": 74567614, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "hidden document.querySelectorAll setAttribute function show(){\n for(let i=0;i<hidden.length;i++){\n hidden[i].setAttribute(\"hidden\",true);\n }\n}\n\nfunction hide(){\n for(let i=0;i<hidden.length;i++){\n hidden[i].setAttribute(\"hidden\",false);\n }\n}\n" }, { "answer_id": 74567619, "author": "Josiah", "author_id": 20463298, "author_profile": "https://Stackoverflow.com/users/20463298", "pm_score": 1, "selected": false, "text": "hidden queryselectorAll(\".hiddens\") .hiddens const hidden = document.querySelectorAll(\".hiddens\");\n\nfunction show(){\n for(let i of hidden){\n i.hidden= false\n }\n}\n\nfunction hide(){\n for(let i of hidden){\n i.hidden= true\n }\n}" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16023118/" ]
74,567,629
<p><strong>Problem</strong></p> <p>I mad a <code>AccesCheck</code> Mixin, and view named <code>ListFormView</code> that inherits <code>AccessCheck</code>, <code>FormView</code> and <code>ListView</code> to show list and create/update <code>Worker</code> objects. But when I try to add new data by POST method, django keeps returning <code>Attribute Error : Worker object has no attribute 'object_list'</code> error.</p> <p>What is more confusing to me is that whole <code>ListFormView</code> is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem.</p> <p><strong>[AccessCheck]</strong></p> <pre><code>class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View): def test_func(self, *args, **kwargs): access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])] return self.request.user.is_superuser or selr.request.user.id in access def handle_no_permission(self): return redirect('index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id']) return context </code></pre> <p><strong>[ListFormView]</strong></p> <pre><code>class ListFormView(AccessCheck, FormView, ListView): template_name = 'my_template_name.html' context_object_name = 'workers' form_class = WorkerForm success_url = './my_url' def form_valid(self, form): data = form.save() return super().form_valid(form) def get_queryset(self, *args, **kwargs): return Worker.objects.filter(shop_id = self.kwargs['shop_id']) </code></pre> <p><strong>How it was solved</strong></p> <p><strong>[ListFormView]</strong></p> <pre><code>class ListFormView(AccessCheck, FormView, ListView): template_name = 'my_template_name.html' context_object_name = 'workers' form_class = WorkerForm success_url = './my_url' def get_context_data(self, **kwargs): self.object_list = Worker.objects.filter(shop_id = self.kwargs['shop_id']) context = super().get_context_data(**kwargs) return context def form_valid(self, form): data = form.save() return super().form_valid(form) def get_queryset(self, *args, **kwargs): return Worker.objects.filter(shop_id = self.kwargs['shop_id']) </code></pre>
[ { "answer_id": 74571026, "author": "nigel222", "author_id": 5246906, "author_profile": "https://Stackoverflow.com/users/5246906", "pm_score": 0, "selected": false, "text": "object class AccessCheckMixin(LoginRequiredMixin, UserPassesTestMixin):\n # merging two mixins and adding methods is fine\n def test_func(self, *args, **kwargs):\n access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]\n return self.request.user.is_superuser or selr.request.user.id in access\n\n def handle_no_permission(self):\n return redirect('index')\n\n # get_context_data belongs in a View subclass\n\nclass ListFormView(AccessCheckMixin, FormView, ListView):\n # I have misgivings about merging FormView and ListView, but maybe \n ...\n def get_context_data(self, **kwargs):\n # it belongs here, but super() is going to invoke only one of the\n # get_context_data implemenations in one of its parents. \n" }, { "answer_id": 74571589, "author": "rm_kuzmin", "author_id": 20531075, "author_profile": "https://Stackoverflow.com/users/20531075", "pm_score": 1, "selected": false, "text": "get_context_data() ListFormView.get_context_data() AccessCheck.get_context_data() ListFormView AccessCheck.get_context_data() self.object_list = ... class First:\n def f(self):\n print('Code from First')\n\nclass Second:\n def f(self):\n print('Code from Second')\n\nclass A(First, Second):\n pass\n\n\nA().f() >>> \"Code from First\"\n # ╔═══════╗ swithch them\nclass A(Second, First):\n pass\n\nA().f() >>> \"Code from Second\"\n A.__mro__ class A(First, Second): \n def f(self):\n super(First, self).f()\n\nA.__mro__ >>> (<class '__main__.A'>, <class '__main__.First'>, <class '__main__.Second'>, <class 'object'>)\nA().f() >>> \"Code from Second\"\n # make from this line\nclass ListFormView(AccessCheck, FormView, ListView)\n# this one\nclass ListFormView(ListView, AccessCheck, FormView)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7098264/" ]
74,567,638
<p>i have this piece of code in testing currently</p> <pre><code>from_api_response_data = [ { &quot;active&quot;: True, &quot;available&quot;: True, &quot;test1&quot;: True, &quot;test2&quot;: &quot;Testing Only&quot;, &quot;test3&quot;: False, &quot;test_name&quot;: &quot;Tester 1&quot;, &quot;id&quot;: &quot;12345abcxyz&quot;, &quot;test_url&quot;: { &quot;url&quot;: &quot;/something/others/api/v1/abc123&quot; } }, { &quot;active&quot;: True, &quot;available&quot;: True, &quot;test1&quot;: False, &quot;test2&quot;: &quot;This also a test&quot;, &quot;test3&quot;: False, &quot;test_name&quot;: &quot;Tester 2&quot;, &quot;id&quot;: &quot;12345abcxyz678&quot;, &quot;test_url&quot;: { &quot;url&quot;: &quot;/something/others/api/v1/abc1234&quot; } } ] filename = 'testingfile.json' today = datetime.datetime.now().isoformat() from_api_response_data.append( { 'last_updated_date': today } ) Path(filename).write_text( json.dumps(from_api_response_data, default=vars, indent=2) ) test_file_json_read = json.loads( Path(filename).read_text() ) for test in test_file_json_read: if test['available']: print(&quot;true available&quot;) </code></pre> <p>what i am trying to simulate is getting data from api and append updated date and write the data into json file. If i remove that part in appending date, my code works fine when finding test['available']</p> <p>from console output</p> <pre><code> true available true available </code></pre> <p>but with the date append, i will have this error</p> <pre><code> if test['available']: KeyError: 'available' </code></pre> <p>i am not sure why i am not able to read the test['available'] if the date is appended</p> <p>this is what my testingfile.json showing</p> <pre><code>[ { &quot;active&quot;: true, &quot;available&quot;: true, &quot;test1&quot;: true, &quot;test2&quot;: &quot;Testing Only&quot;, &quot;test3&quot;: false, &quot;test_name&quot;: &quot;Tester 1&quot;, &quot;id&quot;: &quot;12345abcxyz&quot;, &quot;test_url&quot;: { &quot;url&quot;: &quot;/something/others/api/v1/abc123&quot; } }, { &quot;active&quot;: true, &quot;available&quot;: true, &quot;test1&quot;: false, &quot;test2&quot;: &quot;This also a test&quot;, &quot;test3&quot;: false, &quot;test_name&quot;: &quot;Tester 2&quot;, &quot;id&quot;: &quot;12345abcxyz678&quot;, &quot;test_url&quot;: { &quot;url&quot;: &quot;/something/others/api/v1/abc1234&quot; } }, { &quot;last_updated_date&quot;: &quot;2022-11-25T09:48:12.765296&quot; } ] </code></pre>
[ { "answer_id": 74567667, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": 2, "selected": true, "text": "{ \"last_updated_date\": \"2022-11-25T09:48:12.765296\" } get for test in test_file_json_read:\n if test.get('available'):\n print(\"true available\")\n" }, { "answer_id": 74567702, "author": "Artem Kotelevych", "author_id": 20595254, "author_profile": "https://Stackoverflow.com/users/20595254", "pm_score": 0, "selected": false, "text": "from_api_response_data.append(\n {\n 'last_updated_date': today\n }\n)\n for obj in from_api_response_data:\n obj[\"last_updated_date\"] = today\n {\n \"data\": [\n ...your objects\n ],\n \"last_updated_date\": today\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897151/" ]
74,567,654
<p>I have been trying to delete lines from a file without loading in memory all the file, because it's too large (~1Gb). How i do it without leaving a blank line in the file?</p> <p>For example:</p> <p>I want this</p> <pre><code>foo bar this is the line to be removed foo bar foo bar </code></pre> <p>To this:</p> <pre><code>foo bar foo bar foo bar </code></pre> <p>But I get this:</p> <pre><code>foo bar foo bar foo bar </code></pre> <p>So I have managed to delete the line but I also want to remove the blank line. The way I did it so far is I move the file pointer (cursor) to the place i want and then with writing ' ' overwrite the line.</p> <pre><code>a = f.tell() f.readline() b = f.tell() f.seek(a) l2 = b-a-1 blank = &quot; &quot;*l2 f.write(blank) f.seek(a) </code></pre>
[ { "answer_id": 74568034, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r+') as f:\n r_pos = w_pos = f.tell()\n while True:\n f.seek(r_pos)\n line = f.readline()\n if not line:\n break\n r_pos = f.tell()\n if 'remove' not in line: # or your criteria\n f.seek(w_pos)\n f.write(line)\n w_pos = f.tell()\n f.seek(w_pos)\n f.truncate()\n" }, { "answer_id": 74568172, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 1, "selected": false, "text": "tell seek with open('file.txt') as file, open('file.txt', 'r+') as output:\n for line in file:\n if line != 'this is the line to be removed\\n':\n output.write(line)\n output.truncate()\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15810134/" ]
74,567,680
<p>My data looks like this:</p> <pre><code>company_name &lt;- c(&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;) year &lt;- c(1985, 1986, 1987, 1988, 1985, 1986, 1987) value &lt;- c(0, 1, 0, 0, 1, 0, 0) df &lt;- data.frame(company_name, year, value) </code></pre> <p>If the value is 1, I want to switch this row of value (value=1) with the next row (value=0). (group_by should be used for company_name) My output must be like this:</p> <pre><code>value &lt;- c(0, 0, 1, 0, 0, 1, 0) new_df &lt;- data.frame(company_name, year, value) </code></pre>
[ { "answer_id": 74568034, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r+') as f:\n r_pos = w_pos = f.tell()\n while True:\n f.seek(r_pos)\n line = f.readline()\n if not line:\n break\n r_pos = f.tell()\n if 'remove' not in line: # or your criteria\n f.seek(w_pos)\n f.write(line)\n w_pos = f.tell()\n f.seek(w_pos)\n f.truncate()\n" }, { "answer_id": 74568172, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 1, "selected": false, "text": "tell seek with open('file.txt') as file, open('file.txt', 'r+') as output:\n for line in file:\n if line != 'this is the line to be removed\\n':\n output.write(line)\n output.truncate()\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18509162/" ]
74,567,688
<p>I am attempting to perform an inner merge of two large dataframes having columns 'ID' and 'Date'. A sample of each is shown below:</p> <p>df1</p> <pre><code> ID Date 0 RHD78 2022-08-05 1 RHD78 2022-08-06 2 RHD78 2022-08-09 3 RHD78 2022-08-11 4 RHD78 2022-08-12 5 RHD78 2022-08-14 6 RHD78 2022-08-15 7 RHD78 2022-08-19 8 BDW56 2022-03-15 9 BDW56 2022-03-16 10 BDW56 2022-03-17 11 BDW56 2022-03-22 12 BDW56 2022-03-23 13 BDW56 2022-03-27 14 BDW56 2022-03-29 15 BDW56 2022-03-30 </code></pre> <p>df2</p> <pre><code> ID Date 0 RHD78 2022-08-12 1 BDW56 2022-03-23 </code></pre> <p>If I use the code <code> df_result = pd.merge(df1, df2, how = 'inner', on='Date')</code> then I get the two intersecting datapoints. However I am struggling to introduce a timedelta such that the resulting dataframe also includes data 4 days before and after the intersecting dates like so:</p> <p>df_desired</p> <pre><code> ID Date 0 RHD78 8/9/2022 1 RHD78 8/11/2022 2 RHD78 8/12/2022 3 RHD78 8/14/2022 4 RHD78 8/15/2022 5 BDW56 3/22/2022 6 BDW56 3/23/2022 7 BDW56 3/27/2022 </code></pre> <p>I tried to look into using merge_asof() function but my understanding is that it gets only the values that are closest to the date and not within a particular date range. I am learning pandas and python so I would appreciate if someone can help me solve this issue and provide simplified explanation of merge_asof().</p>
[ { "answer_id": 74567734, "author": "jhso", "author_id": 10475762, "author_profile": "https://Stackoverflow.com/users/10475762", "pm_score": 2, "selected": false, "text": "df df2 merge = df2.merge(df,how='cross')\nmerge['timedelta'] = pd.to_datetime(merge['Date_x']) - \\\n pd.to_datetime(merge['Date_y'])\nmerge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]\n\n\nprint(merge_filt)\nOut[43]: \n ID_x Date_x ID_y Date_y timedelta\n2 RHD78 2022-08-12 RHD78 2022-08-09 3 days\n3 RHD78 2022-08-12 RHD78 2022-08-11 1 days\n4 RHD78 2022-08-12 RHD78 2022-08-12 0 days\n5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days\n6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days\n27 BDW56 2022-03-23 BDW56 2022-03-22 1 days\n28 BDW56 2022-03-23 BDW56 2022-03-23 0 days\n29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days\n" }, { "answer_id": 74571901, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 2, "selected": false, "text": "d = pd.to_timedelta(4,'days')\ndf2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))\ndf1.merge(df2.set_index('ID').explode('Date').reset_index())\n\n>>>\n'''\n ID Date\n0 RHD78 2022-08-09\n1 RHD78 2022-08-11\n2 RHD78 2022-08-12\n3 RHD78 2022-08-14\n4 RHD78 2022-08-15\n5 BDW56 2022-03-22\n6 BDW56 2022-03-23\n7 BDW56 2022-03-27\n" }, { "answer_id": 74572350, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "df2 = df2.assign(start = df2.Date -pd.Timedelta(days=4), \n end = df2.Date + pd.Timedelta(days=4))\n(df\n.merge(df2.drop(columns='Date'), on='ID')\n.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])\n\n ID Date\n2 RHD78 2022-08-09\n3 RHD78 2022-08-11\n4 RHD78 2022-08-12\n5 RHD78 2022-08-14\n6 RHD78 2022-08-15\n11 BDW56 2022-03-22\n12 BDW56 2022-03-23\n13 BDW56 2022-03-27\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19872294/" ]
74,567,753
<p>I know the current window can be used with &quot;this&quot; but is there anything I can use to call the previous window?</p> <p>For example I have this code going off when I press a button</p> <pre><code>Buyer_Login BuyerWindow = new Buyer_Login(); Visibility= Visibility.Hidden; BuyerWindow.Show(); </code></pre> <p>I need to be able to go back to the first window and I need to close the BuyerWindow and I was going to do it with this.Close();</p> <p>What can I do to make the first window's visibility visible again?</p>
[ { "answer_id": 74567734, "author": "jhso", "author_id": 10475762, "author_profile": "https://Stackoverflow.com/users/10475762", "pm_score": 2, "selected": false, "text": "df df2 merge = df2.merge(df,how='cross')\nmerge['timedelta'] = pd.to_datetime(merge['Date_x']) - \\\n pd.to_datetime(merge['Date_y'])\nmerge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]\n\n\nprint(merge_filt)\nOut[43]: \n ID_x Date_x ID_y Date_y timedelta\n2 RHD78 2022-08-12 RHD78 2022-08-09 3 days\n3 RHD78 2022-08-12 RHD78 2022-08-11 1 days\n4 RHD78 2022-08-12 RHD78 2022-08-12 0 days\n5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days\n6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days\n27 BDW56 2022-03-23 BDW56 2022-03-22 1 days\n28 BDW56 2022-03-23 BDW56 2022-03-23 0 days\n29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days\n" }, { "answer_id": 74571901, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 2, "selected": false, "text": "d = pd.to_timedelta(4,'days')\ndf2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))\ndf1.merge(df2.set_index('ID').explode('Date').reset_index())\n\n>>>\n'''\n ID Date\n0 RHD78 2022-08-09\n1 RHD78 2022-08-11\n2 RHD78 2022-08-12\n3 RHD78 2022-08-14\n4 RHD78 2022-08-15\n5 BDW56 2022-03-22\n6 BDW56 2022-03-23\n7 BDW56 2022-03-27\n" }, { "answer_id": 74572350, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "df2 = df2.assign(start = df2.Date -pd.Timedelta(days=4), \n end = df2.Date + pd.Timedelta(days=4))\n(df\n.merge(df2.drop(columns='Date'), on='ID')\n.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])\n\n ID Date\n2 RHD78 2022-08-09\n3 RHD78 2022-08-11\n4 RHD78 2022-08-12\n5 RHD78 2022-08-14\n6 RHD78 2022-08-15\n11 BDW56 2022-03-22\n12 BDW56 2022-03-23\n13 BDW56 2022-03-27\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17978542/" ]
74,567,795
<p>I’m trying to run a Dijkstra algorithm on bigquery using 2 tables. The first table has the node information (ID, Latitude, Longitude) The second table has the vertex information (Start_node_ID, End_node_ID, Distance between nodes) . I’m not really sure how to start this project, I don’t have that much experience with bigquery, I’ve seen some people make something similar on SQL so I know it’s possible, but I’m having a hard time replicating it on BigQuery.</p> <p>All help is welcome, thanks for your time.</p> <p>P.S here its who the data looks like, some vertexes only goes in one direction.</p> <pre><code>NODE 1. |ID|LAT|LONG| 2. |1 |1.2| 1.3| 3. |2 |1.2| 1.4| 4. |3 |3.4|-2.5| </code></pre> <pre><code>VERTEX 1. |STR|END|DST| 2. | 1 | 2 | 3 | 3. | 2 | 1 | 3 | 4. | 1 | 3 | 4 | </code></pre> <p>I tried the following code, but im not sure how to convert it to bigquery SQL</p> <p><a href="https://kainwen.com/2019/10/31/dijkstra-via-sql-a-glance-at-recursive-cte/" rel="nofollow noreferrer">https://kainwen.com/2019/10/31/dijkstra-via-sql-a-glance-at-recursive-cte/</a></p>
[ { "answer_id": 74567734, "author": "jhso", "author_id": 10475762, "author_profile": "https://Stackoverflow.com/users/10475762", "pm_score": 2, "selected": false, "text": "df df2 merge = df2.merge(df,how='cross')\nmerge['timedelta'] = pd.to_datetime(merge['Date_x']) - \\\n pd.to_datetime(merge['Date_y'])\nmerge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]\n\n\nprint(merge_filt)\nOut[43]: \n ID_x Date_x ID_y Date_y timedelta\n2 RHD78 2022-08-12 RHD78 2022-08-09 3 days\n3 RHD78 2022-08-12 RHD78 2022-08-11 1 days\n4 RHD78 2022-08-12 RHD78 2022-08-12 0 days\n5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days\n6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days\n27 BDW56 2022-03-23 BDW56 2022-03-22 1 days\n28 BDW56 2022-03-23 BDW56 2022-03-23 0 days\n29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days\n" }, { "answer_id": 74571901, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 2, "selected": false, "text": "d = pd.to_timedelta(4,'days')\ndf2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))\ndf1.merge(df2.set_index('ID').explode('Date').reset_index())\n\n>>>\n'''\n ID Date\n0 RHD78 2022-08-09\n1 RHD78 2022-08-11\n2 RHD78 2022-08-12\n3 RHD78 2022-08-14\n4 RHD78 2022-08-15\n5 BDW56 2022-03-22\n6 BDW56 2022-03-23\n7 BDW56 2022-03-27\n" }, { "answer_id": 74572350, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "df2 = df2.assign(start = df2.Date -pd.Timedelta(days=4), \n end = df2.Date + pd.Timedelta(days=4))\n(df\n.merge(df2.drop(columns='Date'), on='ID')\n.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])\n\n ID Date\n2 RHD78 2022-08-09\n3 RHD78 2022-08-11\n4 RHD78 2022-08-12\n5 RHD78 2022-08-14\n6 RHD78 2022-08-15\n11 BDW56 2022-03-22\n12 BDW56 2022-03-23\n13 BDW56 2022-03-27\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20359554/" ]
74,567,804
<p>I have data from a questionnaire that has a column for year of birth. So the range of data was too large and my mapping became confusing. I'm now trying to take the years, group them up by decade decade, and then chart them. But I don't know how to group them.</p> <p>my data is like:</p> <pre><code>birth_year &lt;- data.frame(&quot;years&quot;=c( &quot;1920&quot;,&quot;1923&quot;,&quot;1930&quot;,&quot;1940&quot;,&quot;1932&quot;,&quot;1935&quot;,&quot;1942&quot;,&quot;1944&quot;,&quot;1952&quot;,&quot;1956&quot;,&quot;1996&quot;,&quot;1961&quot;, &quot;1962&quot;,&quot;1966&quot;,&quot;1978&quot;,&quot;1987&quot;,&quot;1998&quot;,&quot;1999&quot;,&quot;1967&quot;,&quot;1934&quot;,&quot;1945&quot;,&quot;1988&quot;,&quot;1976&quot;,&quot;1978&quot;, &quot;1951&quot;,&quot;1986&quot;,&quot;1942&quot;,&quot;1999&quot;,&quot;1935&quot;,&quot;1920&quot;,&quot;1933&quot;,&quot;1987&quot;,&quot;1998&quot;,&quot;1999&quot;,&quot;1931&quot;,&quot;1977&quot;, &quot;1920&quot;,&quot;1931&quot;,&quot;1977&quot;,&quot;1999&quot;,&quot;1967&quot;,&quot;1992&quot;,&quot;1998&quot;,&quot;1984&quot; )) </code></pre> <p>and my plot is like: <a href="https://i.stack.imgur.com/LGyuR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGyuR.png" alt="enter image description here" /></a></p> <p>However, I want my data by group as:</p> <pre><code>birth_year count (1920-1930]: 5 (1931-1940]: 8 (1941-1950]: 4 (1951-1960]: 3 (1961-1970]: 5 (1971-1980]: 5 (1981-1990]: 5 (1991-2000]: 9 </code></pre> <p>and then plot as a range group.</p>
[ { "answer_id": 74567734, "author": "jhso", "author_id": 10475762, "author_profile": "https://Stackoverflow.com/users/10475762", "pm_score": 2, "selected": false, "text": "df df2 merge = df2.merge(df,how='cross')\nmerge['timedelta'] = pd.to_datetime(merge['Date_x']) - \\\n pd.to_datetime(merge['Date_y'])\nmerge_filt = merge.loc[merge['timedelta'].apply(lambda x: x.days).abs()<=4]\n\n\nprint(merge_filt)\nOut[43]: \n ID_x Date_x ID_y Date_y timedelta\n2 RHD78 2022-08-12 RHD78 2022-08-09 3 days\n3 RHD78 2022-08-12 RHD78 2022-08-11 1 days\n4 RHD78 2022-08-12 RHD78 2022-08-12 0 days\n5 RHD78 2022-08-12 RHD78 2022-08-14 -2 days\n6 RHD78 2022-08-12 RHD78 2022-08-15 -3 days\n27 BDW56 2022-03-23 BDW56 2022-03-22 1 days\n28 BDW56 2022-03-23 BDW56 2022-03-23 0 days\n29 BDW56 2022-03-23 BDW56 2022-03-27 -4 days\n" }, { "answer_id": 74571901, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 2, "selected": false, "text": "d = pd.to_timedelta(4,'days')\ndf2['Date'] = df2['Date'].map(lambda x: pd.date_range(x-d,x+d))\ndf1.merge(df2.set_index('ID').explode('Date').reset_index())\n\n>>>\n'''\n ID Date\n0 RHD78 2022-08-09\n1 RHD78 2022-08-11\n2 RHD78 2022-08-12\n3 RHD78 2022-08-14\n4 RHD78 2022-08-15\n5 BDW56 2022-03-22\n6 BDW56 2022-03-23\n7 BDW56 2022-03-27\n" }, { "answer_id": 74572350, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "df2 = df2.assign(start = df2.Date -pd.Timedelta(days=4), \n end = df2.Date + pd.Timedelta(days=4))\n(df\n.merge(df2.drop(columns='Date'), on='ID')\n.loc[lambda d: d.Date.between(d.start, d.end, inclusive='both'), df.columns])\n\n ID Date\n2 RHD78 2022-08-09\n3 RHD78 2022-08-11\n4 RHD78 2022-08-12\n5 RHD78 2022-08-14\n6 RHD78 2022-08-15\n11 BDW56 2022-03-22\n12 BDW56 2022-03-23\n13 BDW56 2022-03-27\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422380/" ]
74,567,828
<p>I'm beginner in Swift. I have made a document picker at my task. But I see the documentation it was deprecated to used <code>open var documentPickerMode: UIDocumentPickerMode { get }</code>. While the project in my task runs with minimum deployment of IOS13. <a href="https://i.stack.imgur.com/ZcHLZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZcHLZ.png" alt="here;s the ScreenShot image description here" /></a></p> <p>Is there a solution for this feature that can be used on IOS14 and below? Or is this normal, where users need to update IOS?. Forgive me for my ignorance, as I'm new to swift world.</p>
[ { "answer_id": 74569743, "author": "Muhammad Manzar", "author_id": 16153772, "author_profile": "https://Stackoverflow.com/users/16153772", "pm_score": -1, "selected": false, "text": " func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {\n guard url.startAccessingSecurityScopedResource() else {\n return\n }\n defer { url.stopAccessingSecurityScopedResource() }\n var error: NSError? = nil\n NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in\n let _ : [URLResourceKey] = [.nameKey, .isDirectoryKey]\n let documentFileData = NSData(contentsOf: (url)) as Data?\n pickImageCallback?(nil, url.lastPathComponent, documentFileData)\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20325604/" ]
74,567,833
<p>I have a Python dataframe with multiple rows and columns, a sample of which I have shared below -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>DocName</th> <th>Content</th> </tr> </thead> <tbody> <tr> <td>Doc1</td> <td>Hi how you are doing ? Hope you are well. I hear the food is great!</td> </tr> <tr> <td>Doc2</td> <td>The food is great. James loves his food. You not so much right ?</td> </tr> <tr> <td>Doc3.</td> <td>Yeah he is alright.</td> </tr> </tbody> </table> </div> <p>I also have a list of 100 words as follows -</p> <pre><code>list = [food, you, ....] </code></pre> <p>Now, I need to extract the top N rows with most frequent occurences of each word from the list in the &quot;Content&quot; column. For the given sample of data,</p> <blockquote> <p>&quot;food&quot; occurs twice in Doc2 and once in Doc1.</p> <p>&quot;you&quot; occurs twice in Doc 1 and once in Doc 2.</p> </blockquote> <p>Hence, desired output is :</p> <pre><code>[food:[doc2, doc1], you:[doc1, doc2], .....] </code></pre> <blockquote> <p>where N = 2 ( top 2 rows having the most frequent occurence of each word )</p> </blockquote> <p>I have tried something as follows but unsure how to move further -</p> <pre><code>list = [food, you, ....] result = [] for word in list: result.append(df.Content.apply(lambda row: sum([row.count(word)]))) </code></pre> <p>How can I implement an efficient solution to the above requirement in Python ?</p>
[ { "answer_id": 74568147, "author": "ZeThey", "author_id": 17451973, "author_profile": "https://Stackoverflow.com/users/17451973", "pm_score": 0, "selected": false, "text": "doc1.dict[\"food\"]\ndoc2.dict[\"food\"]\n...\n" }, { "answer_id": 74570234, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 2, "selected": true, "text": "df words = [\"food\", \"you\"]\nn = 2 # Number of top docs\nres = (\n df\n .assign(Content=df[\"Content\"].str.casefold().str.findall(r\"\\w+\"))\n .explode(\"Content\")\n .loc[lambda df: df[\"Content\"].isin(set(words))]\n .groupby(\"DocName\").value_counts().rename(\"Counts\")\n .sort_values(ascending=False).reset_index(level=0)\n .assign(DocName=lambda df: df[\"DocName\"] + \"_\" + df[\"Counts\"].astype(\"str\"))\n .groupby(level=0).agg({\"DocName\": list})\n .assign(DocName=lambda df: df[\"DocName\"].str[:n])\n .to_dict()[\"DocName\"]\n)\n DocName Content\n0 Doc1 you\n0 Doc1 you\n0 Doc1 food\n1 Doc2 food\n1 Doc2 food\n1 Doc2 you\n .groupby .value_counts .sort_values DocName Counts\nContent \nyou Doc1_2 2\nfood Doc2_2 2\nfood Doc1_1 1\nyou Doc2_1 1\n .groupby .agg n .str[:n] DocName\nContent \nfood [Doc2_2, Doc1_1]\nyou [Doc1_2, Doc2_1]\n DocName Content\n0 Doc1 Hi how you are doing ? Hope you are well. I hear the food is great!\n1 Doc2 The food is great. James loves his food. You not so much right ?\n2 Doc3 Yeah he is alright.\n {'food': ['Doc2_2', 'Doc1_1'], 'you': ['Doc1_2', 'Doc2_1']}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6510332/" ]
74,567,850
<p>It is possible to add when or if condition on Ansible variable? For example we have 2 jenkins server (server A and server B), we want to apply different plugins version for both of them.</p> <p>Example:</p> <pre><code>jenkins_plugins: - name: plugin-x version: &quot;1.1&quot; {&quot;if server == A&quot;} - name: plugin-x version: &quot;1.5&quot; {&quot;if server == B&quot;} </code></pre> <p>Thanks.</p> <p>I want to apply different plugins version to different servers.</p>
[ { "answer_id": 74568147, "author": "ZeThey", "author_id": 17451973, "author_profile": "https://Stackoverflow.com/users/17451973", "pm_score": 0, "selected": false, "text": "doc1.dict[\"food\"]\ndoc2.dict[\"food\"]\n...\n" }, { "answer_id": 74570234, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 2, "selected": true, "text": "df words = [\"food\", \"you\"]\nn = 2 # Number of top docs\nres = (\n df\n .assign(Content=df[\"Content\"].str.casefold().str.findall(r\"\\w+\"))\n .explode(\"Content\")\n .loc[lambda df: df[\"Content\"].isin(set(words))]\n .groupby(\"DocName\").value_counts().rename(\"Counts\")\n .sort_values(ascending=False).reset_index(level=0)\n .assign(DocName=lambda df: df[\"DocName\"] + \"_\" + df[\"Counts\"].astype(\"str\"))\n .groupby(level=0).agg({\"DocName\": list})\n .assign(DocName=lambda df: df[\"DocName\"].str[:n])\n .to_dict()[\"DocName\"]\n)\n DocName Content\n0 Doc1 you\n0 Doc1 you\n0 Doc1 food\n1 Doc2 food\n1 Doc2 food\n1 Doc2 you\n .groupby .value_counts .sort_values DocName Counts\nContent \nyou Doc1_2 2\nfood Doc2_2 2\nfood Doc1_1 1\nyou Doc2_1 1\n .groupby .agg n .str[:n] DocName\nContent \nfood [Doc2_2, Doc1_1]\nyou [Doc1_2, Doc2_1]\n DocName Content\n0 Doc1 Hi how you are doing ? Hope you are well. I hear the food is great!\n1 Doc2 The food is great. James loves his food. You not so much right ?\n2 Doc3 Yeah he is alright.\n {'food': ['Doc2_2', 'Doc1_1'], 'you': ['Doc1_2', 'Doc2_1']}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15865474/" ]
74,567,875
<p>Trying to create a mask for my dataframe but can not compare the upper bound / lower bound datetimes to the index of the dataframe due to it being datetime64[ns]. I have seen the solution be to convert via pd.Timestamp - however I still get a value error.</p> <p>Additionally I have tried to convert the index and am thrown the error: &quot;Cannot convert input ... series... to timestamp&quot;</p> <p>INPUT:</p> <pre><code>x = yf.Ticker('^GSPC').history(period='max',interval='1d').loc[:,['Open']] stdate = pd.Timestamp(2015,12,31) edate = dt.datetime.today() y = x.index &gt; stdate </code></pre> <p>ACTUAL OUTPUT:</p> <pre><code>*&quot;Invalid comparison between dtype=datetime64[ns, TIMEZONE] and Timestamp&quot;* </code></pre> <p>EXPECTED OUTPUT:</p> <pre><code>[FALSE, FALSE, FALSE, TRUE, TRUE... TRUE] </code></pre>
[ { "answer_id": 74568147, "author": "ZeThey", "author_id": 17451973, "author_profile": "https://Stackoverflow.com/users/17451973", "pm_score": 0, "selected": false, "text": "doc1.dict[\"food\"]\ndoc2.dict[\"food\"]\n...\n" }, { "answer_id": 74570234, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 2, "selected": true, "text": "df words = [\"food\", \"you\"]\nn = 2 # Number of top docs\nres = (\n df\n .assign(Content=df[\"Content\"].str.casefold().str.findall(r\"\\w+\"))\n .explode(\"Content\")\n .loc[lambda df: df[\"Content\"].isin(set(words))]\n .groupby(\"DocName\").value_counts().rename(\"Counts\")\n .sort_values(ascending=False).reset_index(level=0)\n .assign(DocName=lambda df: df[\"DocName\"] + \"_\" + df[\"Counts\"].astype(\"str\"))\n .groupby(level=0).agg({\"DocName\": list})\n .assign(DocName=lambda df: df[\"DocName\"].str[:n])\n .to_dict()[\"DocName\"]\n)\n DocName Content\n0 Doc1 you\n0 Doc1 you\n0 Doc1 food\n1 Doc2 food\n1 Doc2 food\n1 Doc2 you\n .groupby .value_counts .sort_values DocName Counts\nContent \nyou Doc1_2 2\nfood Doc2_2 2\nfood Doc1_1 1\nyou Doc2_1 1\n .groupby .agg n .str[:n] DocName\nContent \nfood [Doc2_2, Doc1_1]\nyou [Doc1_2, Doc2_1]\n DocName Content\n0 Doc1 Hi how you are doing ? Hope you are well. I hear the food is great!\n1 Doc2 The food is great. James loves his food. You not so much right ?\n2 Doc3 Yeah he is alright.\n {'food': ['Doc2_2', 'Doc1_1'], 'you': ['Doc1_2', 'Doc2_1']}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16701789/" ]
74,567,879
<p>Ask the user to enter their name and current age. Write code to print a personalised greeting and tell them how old they will be on their next birthday.</p> <p>e.g. If the user enters &quot;Kelly&quot; and &quot;43&quot;, your program should output:</p> <p>&quot;Hello Kelly, on your next birthday you will be 44.&quot;</p> <p>This is my code, it keeps putting 1 at the end of the number instead of doing addition e.g. &quot;Hello earl, on your next birthday you will be 181&quot; instead of &quot;Hello earl, on your next birthday you will be 19.&quot;</p> <pre><code>string name, input; int age; Console.WriteLine(&quot;What is your name?&quot;); name= Console.ReadLine(); Console.WriteLine(&quot;What is your age?&quot;); input = Console.ReadLine(); age = Convert.ToInt32(input); Console.WriteLine(&quot;Hello &quot; + name + &quot;, on your next birthday you will be &quot; + age + 1); Console.ReadLine(); </code></pre>
[ { "answer_id": 74567914, "author": "jmcilhinney", "author_id": 584183, "author_profile": "https://Stackoverflow.com/users/584183", "pm_score": 2, "selected": false, "text": "\"Hello \" + name + \", on your next birthday you will be \"+age +1\n + age age = age + 1;\n \"Hello \" + name + \", on your next birthday you will be \" + (age + 1)\n String.Format $\"Hello {name}, on your next birthday you will be {age + 1}\"\n" }, { "answer_id": 74567926, "author": "RedCrusaderJr", "author_id": 13040040, "author_profile": "https://Stackoverflow.com/users/13040040", "pm_score": 0, "selected": false, "text": "Console.WriteLine($\"Hello {name}, on your next birthday you will be {age++}\");\n ++ age Console.WriteLine($\"Hello {name}, on your next birthday you will be {++age}\");\n" }, { "answer_id": 74567939, "author": "Tejas Parnerkar", "author_id": 4852433, "author_profile": "https://Stackoverflow.com/users/4852433", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n {\n string name, input;\n int age;\n Console.WriteLine(\"What is your name?\");\n name= Console.ReadLine();\n Console.WriteLine(\"What is your age?\");\n input = Console.ReadLine();\n age = Convert.ToInt32(input);\n\n // Change in below line\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \" + (age +1));\n Console.ReadLine();\n }\n }\n}\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \"+(age +1));\n Console.WriteLine() age 1 18 1 181" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20511862/" ]
74,567,946
<p>I am pretty new to PHP so please go easy on me.</p> <p>I am receiving this error &quot;SQLSTATE[HY093]: Invalid parameter...&quot; when I am preparing my SQL statement and binding the values.</p> <p>I have a function that takes three parameters: $table, $data, $id</p> <p>Where $table is simply the table to update in the database.</p> <p>$id is the id of the item within the table I am trying to update.</p> <p>$data is an associative array where the $data[$key] matches the column name in the database.</p> <pre><code>public function update_database($table, $data, $id) { $sql_statement = &quot;'UPDATE `&quot; . $table . &quot;` SET &quot;; foreach ($data as $key =&gt; $value) { if ($key === array_key_last($data)) { $sql_statement .= $key . &quot; = :&quot; . $key . &quot; WHERE id = :id '&quot;; } else { $sql_statement .= $key . &quot; = :&quot; . $key . &quot;, &quot;; } } $this-&gt;db-&gt;query($sql_statement); foreach ($data as $key =&gt; $value) { $this-&gt;db-&gt;bind(':' . $key, $data[$key]); } $this-&gt;db-&gt;bind(':id', $id); if($this-&gt;db-&gt;execute()){ //it worked! return true; }else{ //something did not work return false; } </code></pre> <p>I under stand that the error is simply telling me I am not binding the correct amount of values.</p> <p>Within my SQL statement I am binding 17 values. 16 for each item in the associative array. and I tag on the 17th at the end of the statement. Here is the SQL statement generated with the first foreach loop:</p> <pre><code>string(594) &quot;'UPDATE `clan-info-static` SET tag = :tag, name = :name, location_id = :location_id, location_name = :location_name, location_iscountry = :location_iscountry, location_countrycode = :location_countrycode, badgeUrls_small = :badgeUrls_small, badgeUrls_medium = :badgeUrls_medium, badgeUrls_large = :badgeUrls_large, requiredTrophies = :requiredTrophies, warFrequency = :warFrequency, isWarLogPublic = :isWarLogPublic, warLeague_id = :warLeague_id, warLeague_name = :warLeague_name, requiredVersusTrophies = :requiredVersusTrophies, requiredTownhallLevel = :requiredTownhallLevel WHERE id = :id '&quot; </code></pre> <p>The second foreach loop is binding the values required in the SQL statement. It is using the same data set as the first foreach loop.</p> <p>Ive modified the code to add a ticker to count each time it binds a value. The ticker counts to 16, which is to be expected. That makes 16 times Ive binded the value with the foreach loop, and the 17th time is done manually.</p> <p>Since both foreach loops are using the same dataset, I am at a loss for why it is giving me this error.</p> <p>EDIT: to include my database class.</p> <pre><code>class Database{ private $host = DB_HOST; private $user = DB_USER; private $pass = DB_PASS; private $dbname = DB_NAME; private $dbh; private $stmt; private $error; public function __construct(){ $dsn = 'mysql:host=' . $this-&gt;host . ';dbname=' . $this-&gt;dbname; $options = array( PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, ); try{ $this-&gt;dbh = new PDO($dsn, $this-&gt;user, $this-&gt;pass, $options); }catch(PDOException $e){ $this-&gt;error = $e-&gt;getMessage(); echo $this-&gt;error; } } public function query($sql){ $this-&gt;stmt = $this-&gt;dbh-&gt;prepare($sql); } public function bind($param, $value, $type = null){ if(is_null($type)){ switch(true){ case is_int($value): $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; case is_null($value): $type = PDO::PARAM_NULL; break; default: $type = PDO::PARAM_STR; } } $this-&gt;stmt-&gt;bindValue($param, $value, $type); } public function execute(){ return $this-&gt;stmt-&gt;execute(); } </code></pre> <p>}</p>
[ { "answer_id": 74567914, "author": "jmcilhinney", "author_id": 584183, "author_profile": "https://Stackoverflow.com/users/584183", "pm_score": 2, "selected": false, "text": "\"Hello \" + name + \", on your next birthday you will be \"+age +1\n + age age = age + 1;\n \"Hello \" + name + \", on your next birthday you will be \" + (age + 1)\n String.Format $\"Hello {name}, on your next birthday you will be {age + 1}\"\n" }, { "answer_id": 74567926, "author": "RedCrusaderJr", "author_id": 13040040, "author_profile": "https://Stackoverflow.com/users/13040040", "pm_score": 0, "selected": false, "text": "Console.WriteLine($\"Hello {name}, on your next birthday you will be {age++}\");\n ++ age Console.WriteLine($\"Hello {name}, on your next birthday you will be {++age}\");\n" }, { "answer_id": 74567939, "author": "Tejas Parnerkar", "author_id": 4852433, "author_profile": "https://Stackoverflow.com/users/4852433", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n {\n string name, input;\n int age;\n Console.WriteLine(\"What is your name?\");\n name= Console.ReadLine();\n Console.WriteLine(\"What is your age?\");\n input = Console.ReadLine();\n age = Convert.ToInt32(input);\n\n // Change in below line\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \" + (age +1));\n Console.ReadLine();\n }\n }\n}\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \"+(age +1));\n Console.WriteLine() age 1 18 1 181" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595433/" ]
74,567,962
<p>I really like the debug console feature in VScode, it makes it a lot easier for me to do Python writing. How do I get it to stay on? Is it possible to write launch.json so that the code runs without closing the run afterwards?</p> <p>I can use 'time.sleep()' to continue this console on. Can I edit the'launch.json'? What are other ways?</p>
[ { "answer_id": 74567914, "author": "jmcilhinney", "author_id": 584183, "author_profile": "https://Stackoverflow.com/users/584183", "pm_score": 2, "selected": false, "text": "\"Hello \" + name + \", on your next birthday you will be \"+age +1\n + age age = age + 1;\n \"Hello \" + name + \", on your next birthday you will be \" + (age + 1)\n String.Format $\"Hello {name}, on your next birthday you will be {age + 1}\"\n" }, { "answer_id": 74567926, "author": "RedCrusaderJr", "author_id": 13040040, "author_profile": "https://Stackoverflow.com/users/13040040", "pm_score": 0, "selected": false, "text": "Console.WriteLine($\"Hello {name}, on your next birthday you will be {age++}\");\n ++ age Console.WriteLine($\"Hello {name}, on your next birthday you will be {++age}\");\n" }, { "answer_id": 74567939, "author": "Tejas Parnerkar", "author_id": 4852433, "author_profile": "https://Stackoverflow.com/users/4852433", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n {\n string name, input;\n int age;\n Console.WriteLine(\"What is your name?\");\n name= Console.ReadLine();\n Console.WriteLine(\"What is your age?\");\n input = Console.ReadLine();\n age = Convert.ToInt32(input);\n\n // Change in below line\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \" + (age +1));\n Console.ReadLine();\n }\n }\n}\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \"+(age +1));\n Console.WriteLine() age 1 18 1 181" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595530/" ]
74,567,964
<p>I'm would like to use Array Formula to use the data from another sheet and obtain only the Date from the Date and Time Data.</p> <p>Example, In Sheet 1, there will be a list of date and time date.</p> <ul> <li>Nov 15, 2022, 2:34 PM</li> </ul> <p>In Sheet 2, I would like to use a formula to return the date without the time:</p> <ul> <li>15 Nov 2022</li> </ul>
[ { "answer_id": 74567914, "author": "jmcilhinney", "author_id": 584183, "author_profile": "https://Stackoverflow.com/users/584183", "pm_score": 2, "selected": false, "text": "\"Hello \" + name + \", on your next birthday you will be \"+age +1\n + age age = age + 1;\n \"Hello \" + name + \", on your next birthday you will be \" + (age + 1)\n String.Format $\"Hello {name}, on your next birthday you will be {age + 1}\"\n" }, { "answer_id": 74567926, "author": "RedCrusaderJr", "author_id": 13040040, "author_profile": "https://Stackoverflow.com/users/13040040", "pm_score": 0, "selected": false, "text": "Console.WriteLine($\"Hello {name}, on your next birthday you will be {age++}\");\n ++ age Console.WriteLine($\"Hello {name}, on your next birthday you will be {++age}\");\n" }, { "answer_id": 74567939, "author": "Tejas Parnerkar", "author_id": 4852433, "author_profile": "https://Stackoverflow.com/users/4852433", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n {\n string name, input;\n int age;\n Console.WriteLine(\"What is your name?\");\n name= Console.ReadLine();\n Console.WriteLine(\"What is your age?\");\n input = Console.ReadLine();\n age = Convert.ToInt32(input);\n\n // Change in below line\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \" + (age +1));\n Console.ReadLine();\n }\n }\n}\n Console.WriteLine(\"Hello \" + name + \", on your next birthday you will be \"+(age +1));\n Console.WriteLine() age 1 18 1 181" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595599/" ]
74,567,984
<p>I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new column, I did a search online try to use loop but I can't figure out how to use loop with dataframe</p> <blockquote> <p><code>df['P'] = np.where((df['val2'] &gt; df['val1']) &amp; (df['val2']&gt; df['val1'].shift(1)),1,0 )</code></p> </blockquote> <pre><code> Date val1 val2 P [new column] ( 0 2015-02-24 294 68 0 0 1 2015-02-25 155 31 0 0 2 2015-02-26 168 290 1 1 pattern occur 1 time 3 2015-02-27 273 108 0 0 4 2015-02-28 55 9 0 0 5 2015-03-01 273 123 0 0 6 2015-03-02 200 46 0 0 7 2015-03-03 80 83 0 0 8 2015-03-04 181 208 1 1 pattern occur 1 time 9 2015-03-05 195 41 0 0 10 2015-03-06 50 261 1 1 pattern occur 1 time 11 2015-03-07 50 177 0 0 12 2015-03-08 215 60 1 0 13 2015-03-09 13 290 1 2 pattern occur 2 times 14 2015-03-10 208 41 0 0 15 2015-03-11 49 263 1 0 16 2015-03-12 171 244 1 0 17 2015-03-13 218 266 1 0 18 2015-03-14 188 219 1 3 pattern occur 3 times 19 2015-03-15 232 171 0 0 20 2015-03-16 116 196 0 0 21 2015-03-17 262 102 0 0 22 2015-03-18 263 159 0 0 23 2015-03-19 227 160 0 0 24 2015-03-20 103 236 1 0 25 2015-03-21 55 104 1 0 26 2015-03-22 97 109 1 0 27 2015-03-23 38 118 1 4 pattern occur 4 times 28 2015-03-24 163 116 0 0 29 2015-03-25 256 16 0 0 </code></pre>
[ { "answer_id": 74571172, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 1, "selected": true, "text": "df.iterrows() import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'Date': {0: '2015-02-24', 1: '2015-02-25', 2: '2015-02-26', 3: '2015-02-27', 4: '2015-02-28', 5: '2015-03-01', 6: '2015-03-02', 7: '2015-03-03', 8: '2015-03-04', 9: '2015-03-05', 10: '2015-03-06', 11: '2015-03-07', 12: '2015-03-08', 13: '2015-03-09', 14: '2015-03-10', 15: '2015-03-11', 16: '2015-03-12', 17: '2015-03-13', 18: '2015-03-14', 19: '2015-03-15', 20: '2015-03-16', 21: '2015-03-17', 22: '2015-03-18', 23: '2015-03-19', 24: '2015-03-20', 25: '2015-03-21', 26: '2015-03-22', 27: '2015-03-23', 28: '2015-03-24', 29: '2015-03-25'}, 'val1': {0: 294, 1: 155, 2: 168, 3: 273, 4: 55, 5: 273, 6: 200, 7: 80, 8: 181, 9: 195, 10: 50, 11: 50, 12: 215, 13: 13, 14: 208, 15: 49, 16: 171, 17: 218, 18: 188, 19: 232, 20: 116, 21: 262, 22: 263, 23: 227, 24: 103, 25: 55, 26: 97, 27: 38, 28: 163, 29: 256}, 'val2': {0: 68, 1: 31, 2: 290, 3: 108, 4: 9, 5: 123, 6: 46, 7: 83, 8: 208, 9: 41, 10: 261, 11: 177, 12: 60, 13: 290, 14: 41, 15: 263, 16: 244, 17: 266, 18: 219, 19: 171, 20: 196, 21: 102, 22: 159, 23: 160, 24: 236, 25: 104, 26: 109, 27: 118, 28: 116, 29: 16}})\n\ndf['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )\n\ndf['new_column'] = 0\ncounter = 0\n\nfor i, row, in df.iterrows():\n if row.P == 1:\n counter += 1\n else:\n counter = 0\n df.loc[i, 'new_column'] = counter\n\ndf.new_column = df.new_column * [1 if x == 0 else 0 for x in df.new_column.shift(-1) ]\n Date val1 val2 P new_column\n0 2015-02-24 294 68 0 0\n1 2015-02-25 155 31 0 0\n2 2015-02-26 168 290 1 1\n3 2015-02-27 273 108 0 0\n4 2015-02-28 55 9 0 0\n5 2015-03-01 273 123 0 0\n6 2015-03-02 200 46 0 0\n7 2015-03-03 80 83 0 0\n8 2015-03-04 181 208 1 1\n9 2015-03-05 195 41 0 0\n10 2015-03-06 50 261 1 0\n11 2015-03-07 50 177 1 2\n12 2015-03-08 215 60 0 0\n13 2015-03-09 13 290 1 1\n14 2015-03-10 208 41 0 0\n15 2015-03-11 49 263 1 0\n16 2015-03-12 171 244 1 0\n17 2015-03-13 218 266 1 0\n18 2015-03-14 188 219 1 4\n19 2015-03-15 232 171 0 0\n20 2015-03-16 116 196 0 0\n21 2015-03-17 262 102 0 0\n22 2015-03-18 263 159 0 0\n23 2015-03-19 227 160 0 0\n24 2015-03-20 103 236 1 0\n25 2015-03-21 55 104 1 0\n26 2015-03-22 97 109 1 0\n27 2015-03-23 38 118 1 4\n28 2015-03-24 163 116 0 0\n29 2015-03-25 256 16 0 0\n" }, { "answer_id": 74571917, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "df['new_column'] = (df.P != df.P.shift()).cumsum() #get an id according to P\nmask=df.groupby('new_column')['P'].sum() #what is the total value for each group\n\nduplicated = df.duplicated('new_column',keep='last')\ndf.loc[~duplicated, ['new_column']] = np.nan #set nan to last rows for each group. We will replace nans with mask\n\ndf['new_column'] = df['new_column'].astype(str).replace('\\d+', 0,regex=True).replace('nan',np.nan) #convert not nans to zero\nmask.index=df[df['new_column'].isnull()].index.to_list()\n#If you want to fill the nan values ​​with a series, the index values ​​must be the same. So I replace the index values ​​of the mask series with the index numbers of the nan values ​​in df.\n\ndf['new_column']=df['new_column'].fillna(mask).astype(int)\ndf\n'''\n Date val1 val2 P new_column\n0 2015-02-24 294 68 0 0\n1 2015-02-25 155 31 0 0\n2 2015-02-26 168 290 1 1\n3 2015-02-27 273 108 0 0\n4 2015-02-28 55 9 0 0\n5 2015-03-01 273 123 0 0\n6 2015-03-02 200 46 0 0\n7 2015-03-03 80 83 0 0\n8 2015-03-04 181 208 1 1\n9 2015-03-05 195 41 0 0\n10 2015-03-06 50 261 1 1\n11 2015-03-07 50 177 0 0\n12 2015-03-08 215 60 1 0\n13 2015-03-09 13 290 1 2\n14 2015-03-10 208 41 0 0\n15 2015-03-11 49 263 1 0\n16 2015-03-12 171 244 1 0\n17 2015-03-13 218 266 1 0\n18 2015-03-14 188 219 1 4\n19 2015-03-15 232 171 0 0\n20 2015-03-16 116 196 0 0\n21 2015-03-17 262 102 0 0\n22 2015-03-18 263 159 0 0\n23 2015-03-19 227 160 0 0\n24 2015-03-20 103 236 1 0\n25 2015-03-21 55 104 1 0\n26 2015-03-22 97 109 1 0\n27 2015-03-23 38 118 1 4\n28 2015-03-24 163 116 0 0\n29 2015-03-25 256 16 0 0\n\n'''\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14517795/" ]
74,567,993
<blockquote> <p>Is word &quot;python&quot; and 'python' are different expression??</p> </blockquote> <p>I want to know the differnecce between the type of the expressions &quot;python&quot; and ’python’</p>
[ { "answer_id": 74568046, "author": "njt121", "author_id": 20595651, "author_profile": "https://Stackoverflow.com/users/20595651", "pm_score": 0, "selected": false, "text": "'python's' \n \"python's\"\n" }, { "answer_id": 74568092, "author": "Minhaj98", "author_id": 10752983, "author_profile": "https://Stackoverflow.com/users/10752983", "pm_score": 1, "selected": false, "text": "type(\"python\") type('python') if(\"python\" == 'python'): print(\"True\") else: print(\"False\")" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74567993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20173161/" ]
74,568,013
<p>I installed <code>chartjs</code> and <code>react-chartjs-2</code> using <code>yarn add react-chartjs-2 chart.js</code>. However, when I import any components from the <code>react-chartjs-2</code> library, this error is thrown:</p> <pre><code>The path &quot;react-chartjs-2&quot; is imported in [path]\chart.tsx but &quot;react-chartjs-2&quot; was not found in your node_modules. Did you forget to install it? </code></pre> <p>Anyone has any ideas what is the problem here?</p> <p>I tried this <a href="https://react-chartjs-2.js.org/faq/esm-only/" rel="nofollow noreferrer">method</a> by adding this into <code>package.json</code> but still didn't work:</p> <pre><code>{ &quot;type&quot;: &quot;module&quot; } </code></pre> <p>I also tried using this <code>npx rmx-cli get-esm-packages react-chartjs-2</code> to add the dependencies to my serverDependenciesToBundle, still no work.</p>
[ { "answer_id": 74568046, "author": "njt121", "author_id": 20595651, "author_profile": "https://Stackoverflow.com/users/20595651", "pm_score": 0, "selected": false, "text": "'python's' \n \"python's\"\n" }, { "answer_id": 74568092, "author": "Minhaj98", "author_id": 10752983, "author_profile": "https://Stackoverflow.com/users/10752983", "pm_score": 1, "selected": false, "text": "type(\"python\") type('python') if(\"python\" == 'python'): print(\"True\") else: print(\"False\")" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20586887/" ]
74,568,043
<p>I want to know why the second print function can print a? and the third print function not print a?</p> <pre><code>#include &lt;stdio.h&gt; int main() { int i = 97; // a printf(&amp;i); // a:print content in address &amp;i printf(&quot;\n%s\n&quot;, &amp;i); // why print a? printf(&quot;%c\n&quot;, &amp;i); // why not print a? } </code></pre> <p>I want to understand printf function from pointer and memory. Thank you</p>
[ { "answer_id": 74568071, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "%c" }, { "answer_id": 74568232, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 2, "selected": false, "text": "printf(&i); // a:print content in address &i\n printf() const char * int * printf() i a int 97 0x61, 0x00, 0x00, 0x00\n 0x00, 0x00, 0x00, 0x61\n printf() 0x00 printf(\"\\n%s\\n\", &i); // why print a?\n %s printf() printf(\"%c\\n\", &i); // why not print a?\n %c printf() printf() char printf()" }, { "answer_id": 74568239, "author": "zwol", "author_id": 388520, "author_profile": "https://Stackoverflow.com/users/388520", "pm_score": 2, "selected": false, "text": "int i printf printf(\"%c\\n\", i); // pass the _value_, not the address of i\n scanf i scanf printf unsigned int i = 'a'; // == 97, assuming ASCII\nprintf(\"%s\\n\", (char *)&i);\n int 'a' int int \"a\" printf \"a\" \"\" printf printf printf printf a %c" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595610/" ]
74,568,049
<p>Am a bit lost and been scratching my head for a couple of days, I am getting this error</p> <blockquote> <p>Null check operator used on a null value</p> </blockquote> <p>On this piece of code</p> <pre><code> percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100; </code></pre> <p>the section inside here <code>(scores[section] ?? 0</code> is throwing a null pointer, but the value has data on the code above. Here is a more detailed code</p> <pre><code> num getSectionScore(int section) { log(&quot;getSectionScore($section) called&quot;); var data = scores[section] ?? 0; log(&quot;getSectionScoredata($data) called&quot;); return scores[section] ?? 0; } num getSectionPtsPoss(int section) { return totalPerSection[section]!; } String getPercentage(int section) { log(&quot;getPercentage($section) called&quot;); num percent = 0; try { percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100; } on NoSuchMethodError catch (_) { } if (percent % 1 == 0.0) { // if number is an int, return it as is return percent.truncate().toString(); } else if (percent % 10 == 0.0) { // else if num comes out to an even tenth (ex 0.1), return with 1 decimal return percent.toStringAsFixed(1); } else { return percent.toStringAsFixed(2); } } </code></pre> <p>This the function am using to get the sections and scores. When I do a console log on this bit here</p> <pre><code>var data = scores[section] ?? 0; log(&quot;getSectionScoredata($data) called&quot;); </code></pre> <p>no null pointer is getting thrown, as when the <code>scores[section]</code> is found to be null, 0 is being passed. Why am I getting the error on this line <code>percent = (scores[section] ?? 0</code> and I am passing a default value if the section is found to be null .</p> <p>Any help on what am doing wrong is appreciated.</p>
[ { "answer_id": 74568071, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "%c" }, { "answer_id": 74568232, "author": "Jeremy Friesner", "author_id": 131930, "author_profile": "https://Stackoverflow.com/users/131930", "pm_score": 2, "selected": false, "text": "printf(&i); // a:print content in address &i\n printf() const char * int * printf() i a int 97 0x61, 0x00, 0x00, 0x00\n 0x00, 0x00, 0x00, 0x61\n printf() 0x00 printf(\"\\n%s\\n\", &i); // why print a?\n %s printf() printf(\"%c\\n\", &i); // why not print a?\n %c printf() printf() char printf()" }, { "answer_id": 74568239, "author": "zwol", "author_id": 388520, "author_profile": "https://Stackoverflow.com/users/388520", "pm_score": 2, "selected": false, "text": "int i printf printf(\"%c\\n\", i); // pass the _value_, not the address of i\n scanf i scanf printf unsigned int i = 'a'; // == 97, assuming ASCII\nprintf(\"%s\\n\", (char *)&i);\n int 'a' int int \"a\" printf \"a\" \"\" printf printf printf printf a %c" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14236206/" ]
74,568,063
<p>I would like to find out the most utilized location for the date of 2/1/2022.</p> <h2>Data</h2> <pre><code>ID location total marks_free marks_utilized date 1 NY 6 5 1 2/1/2022 2 NY 10 5 5 2/1/2022 3 NY 2 1 1 2/1/2022 4 CA 5 4 1 2/1/2022 5 CA 6 5 1 2/1/2022 6 CA 10 10 0 2/1/2022 7 NY 6 6 0 3/1/2022 8 NY 10 10 0 3/1/2022 9 NY 2 1 1 3/1/2022 10 CA 5 4 1 3/1/2022 11 CA 6 5 1 3/1/2022 12 CA 10 10 0 3/1/2022 </code></pre> <h2>Desired</h2> <pre><code>location marks_utilized date NY 38% 2/1/2022 </code></pre> <h2>Logic</h2> <pre><code>filter to 2/1/2022, groupby location for instance lets take NY sum(marks_utilized) / sum(total) * 100 7/18 *100 = 38% </code></pre> <h2>Doing</h2> <pre><code># filter to 2/1/2022 df1 = df.groupby(['location', 'date']).agg({'marks_utilized': 'sum', 'total': 'sum'}) df1['marks_utilized'] = df['marks_utilized'] / df['total'] * 100 </code></pre> <p>Still researching this.</p>
[ { "answer_id": 74568148, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 1, "selected": false, "text": "df.groupby(['location','date']).apply(lambda x : x['marks_utilized'].sum()/x['total'].sum()).\\\n mul(100).reset_index(name = 'marks_utilized')\nOut[279]: \n location date marks_utilized\n0 CA 3/1/2022 9.523810\n1 NY 2/1/2022 38.888889\n" }, { "answer_id": 74568165, "author": "hide1nbush", "author_id": 19825642, "author_profile": "https://Stackoverflow.com/users/19825642", "pm_score": 3, "selected": true, "text": "df1['marks_utilized'] = df['marks_utilized'] / df['total'] * 100 df1['marks_utilized'] = df1['marks_utilized'] / df1['total'] * 100 2/1/2022 df groupby df1.to_string(formatters={'marks_utilized': '{:,.2f}'.format} float ID,location,total,marks_free,marks_utilized,date\n1,NY,6,5,1,2/1/2022\n2,NY,10,5,5,2/1/2022\n3,NY,2,1,1,2/1/2022\n4,CA,5,4,1,3/1/2022\n5,CA,6,5,1,3/1/2022\n6,CA,10,10,0,3/1/2022\n import pandas as pd\n\ndf = pd.read_csv(\"test.csv\")\ndf1 = df.groupby(['location', 'date']).agg({'marks_utilized': 'sum', 'total': 'sum'})\ndf1['marks_utilized'] = df1['marks_utilized'] / df1['total']\nmax_row = df1.loc[df1['marks_utilized'].idxmax()]\nprint(max_row)\n marks_utilized 0.388889\ntotal 18.000000\nName: (NY, 2/1/2022), dtype: float64\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
74,568,074
<p>I have a useState called isPackage which is a boolean that starts as false. I use this hook in a simple JSX select, which when isPackage is true requires it to be enabled but when it is false it is disabled. The problem starts from the rendering since although usPackage is false, the select is shown enabled. This is my code:</p> <p>UseState:</p> <pre><code>const [isPackage, setIsPackage] = useState(false) </code></pre> <p>JSX:</p> <pre><code> &lt;select disabled = { isPackage ? true : false }&gt; </code></pre> <p>I change the state of isPackage using this function:</p> <pre><code>const handlerPresentationSelected = () =&gt; { setIsPackage(!isPackage) } </code></pre> <p>If I make the first change using the function above, it is executed correctly to pass isPackage to true, when I use the function again it correctly changes to false, however the select is always enabled.</p>
[ { "answer_id": 74568148, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 1, "selected": false, "text": "df.groupby(['location','date']).apply(lambda x : x['marks_utilized'].sum()/x['total'].sum()).\\\n mul(100).reset_index(name = 'marks_utilized')\nOut[279]: \n location date marks_utilized\n0 CA 3/1/2022 9.523810\n1 NY 2/1/2022 38.888889\n" }, { "answer_id": 74568165, "author": "hide1nbush", "author_id": 19825642, "author_profile": "https://Stackoverflow.com/users/19825642", "pm_score": 3, "selected": true, "text": "df1['marks_utilized'] = df['marks_utilized'] / df['total'] * 100 df1['marks_utilized'] = df1['marks_utilized'] / df1['total'] * 100 2/1/2022 df groupby df1.to_string(formatters={'marks_utilized': '{:,.2f}'.format} float ID,location,total,marks_free,marks_utilized,date\n1,NY,6,5,1,2/1/2022\n2,NY,10,5,5,2/1/2022\n3,NY,2,1,1,2/1/2022\n4,CA,5,4,1,3/1/2022\n5,CA,6,5,1,3/1/2022\n6,CA,10,10,0,3/1/2022\n import pandas as pd\n\ndf = pd.read_csv(\"test.csv\")\ndf1 = df.groupby(['location', 'date']).agg({'marks_utilized': 'sum', 'total': 'sum'})\ndf1['marks_utilized'] = df1['marks_utilized'] / df1['total']\nmax_row = df1.loc[df1['marks_utilized'].idxmax()]\nprint(max_row)\n marks_utilized 0.388889\ntotal 18.000000\nName: (NY, 2/1/2022), dtype: float64\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8977748/" ]
74,568,085
<p>Could you please tell me how can I remove &quot;)&quot; from strings in a list without converting the list to a string? Example:</p> <p>Input:</p> <pre><code>list =[ 'ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end 'CONDDDD 7,000 4DJVBDISJEVV)'] # there is a parenthesis at the end </code></pre> <p>Expected output:</p> <pre><code>list =[ 'ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ', # parenthesis is removed 'CONDDDD 7,000 4DJVBDISJEVV'] # parenthesis is removed </code></pre> <p>I know how to do it by converting list to str like following:</p> <pre><code>a = str(list) a = a.replace(&quot;)&quot;,&quot;&quot;) print(a) </code></pre> <p>However, since I need convert it to a dataframe later... I want to keep it as list. Please let me know if you need any clarificaiton for my question. This is my first time to post a question.</p>
[ { "answer_id": 74568148, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 1, "selected": false, "text": "df.groupby(['location','date']).apply(lambda x : x['marks_utilized'].sum()/x['total'].sum()).\\\n mul(100).reset_index(name = 'marks_utilized')\nOut[279]: \n location date marks_utilized\n0 CA 3/1/2022 9.523810\n1 NY 2/1/2022 38.888889\n" }, { "answer_id": 74568165, "author": "hide1nbush", "author_id": 19825642, "author_profile": "https://Stackoverflow.com/users/19825642", "pm_score": 3, "selected": true, "text": "df1['marks_utilized'] = df['marks_utilized'] / df['total'] * 100 df1['marks_utilized'] = df1['marks_utilized'] / df1['total'] * 100 2/1/2022 df groupby df1.to_string(formatters={'marks_utilized': '{:,.2f}'.format} float ID,location,total,marks_free,marks_utilized,date\n1,NY,6,5,1,2/1/2022\n2,NY,10,5,5,2/1/2022\n3,NY,2,1,1,2/1/2022\n4,CA,5,4,1,3/1/2022\n5,CA,6,5,1,3/1/2022\n6,CA,10,10,0,3/1/2022\n import pandas as pd\n\ndf = pd.read_csv(\"test.csv\")\ndf1 = df.groupby(['location', 'date']).agg({'marks_utilized': 'sum', 'total': 'sum'})\ndf1['marks_utilized'] = df1['marks_utilized'] / df1['total']\nmax_row = df1.loc[df1['marks_utilized'].idxmax()]\nprint(max_row)\n marks_utilized 0.388889\ntotal 18.000000\nName: (NY, 2/1/2022), dtype: float64\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470864/" ]
74,568,104
<p>So i'm trying to make a program which create and print an array made of 29 index with 5 of those being &quot;A&quot; and the 24 others being &quot;-&quot;. I've ran across the problem where it's either giving me an outofbound error or just not putting 5 &quot;A&quot; on the board.</p> <p>Here is what i've tried so far.</p> <pre><code> static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{ //ADD &quot;A&quot; TO RANDOM INDEX IN BOARD int x = 5; while (checkForAInArray(board)==false) { for (int i = 0; i &lt; x; i++) { int j = (int)(Math.random()*board.length); while(board[j-1].equals(&quot;A&quot;) || board[j+1].equals(&quot;A&quot;)){ //Make sure there's no A beside another &quot;A&quot; j = (int)(Math.random()*board.length); } board[j] = &quot;A&quot;; } x = CountAInArray(board); } return board; } static boolean checkForAInArray(String[] board){ //Make sure there is 5 &quot;A&quot; in the program int countOfA = 0; for (int i = 0; i &lt; board.length; i++) { if(board[i].equals(&quot;A&quot;)){ countOfA++; } } if(countOfA==5){ return true; } else{ return false; } } static int CountAInArray(String[] board){ //Control the number of time the For-loop of </code></pre> <p>placeRandomAppleAroundBoard</p> <pre><code>iterate, which is 5 based and then change depending on how much &quot;A&quot; there's on the board int countOfA = 0; for (int i = 0; i &lt; board.length; i++) { if(board[i].equals(&quot;A&quot;)){ countOfA++; } } if(countOfA==0){ return 5; } else{ return 5 - countOfA; } } </code></pre> <p>So as you can see, i've tried to control the number of time the ForLoop add &quot;A&quot; in the board, that didn't work. I've also tried check for the number of &quot;A&quot; already present in the board but that didn't seem to do the tricks</p> <p>I am expecting a board printed like so :</p> <pre><code>static void printboard(String[] board){ System.out.println(board[0] + &quot;|&quot; + board[1] + &quot;|&quot; + board[2] + &quot;|&quot; + board[3] + &quot;|&quot; + board[4] + &quot;|&quot; + board[5] + &quot;|&quot; + board[6] + &quot;|&quot; + board[7] + &quot;|&quot; + board[8] + &quot;|&quot; + board[9]); System.out.println(board[10] + &quot;|&quot; + board[11] + &quot;|&quot; + board[12] + &quot;|&quot; + board[13] + &quot;|&quot; + board[14] + &quot;|&quot; + board[15] + &quot;|&quot; + board[16] + &quot;|&quot; + board[17] + &quot;|&quot; + board[18] + &quot;|&quot; + board[19]); System.out.println(board[20] + &quot;|&quot; + board[21] + &quot;|&quot; + board[22] + &quot;|&quot; + board[23] + &quot;|&quot; + board[24] + &quot;|&quot; + board[25] + &quot;|&quot; + board[26] + &quot;|&quot; + board[27] + &quot;|&quot; + board[28] + &quot;|&quot; + board[29]); } </code></pre> <p>Thanks for you're help!!</p>
[ { "answer_id": 74568354, "author": "william beaudin", "author_id": 20162945, "author_profile": "https://Stackoverflow.com/users/20162945", "pm_score": 1, "selected": false, "text": "static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{\n int iterationNumber = checkForNumberOfAInArray(board);\n for (int i = 0; i < iterationNumber; i++) {\n int j = (int)(Math.random()*board.length);\n \n while(board[j-1].equals(\"A\") || board[j+1].equals(\"A\") || board[j].equals(\"A\")){\n j = (int)(Math.random()*board.length);\n }\n board[j] = \"A\";\n }\n return board;\n}\n\nstatic int checkForNumberOfAInArray(String[] board){\n int countOfA = 0;\n\n for (String x : board) {\n if(x == \"A\"){\n countOfA++;\n }\n }\n\n System.out.println(countOfA);\n return (5 - countOfA);\n}\n" }, { "answer_id": 74572399, "author": "g00se", "author_id": 16376827, "author_profile": "https://Stackoverflow.com/users/16376827", "pm_score": 0, "selected": false, "text": " String[] board = new String[29];\n Arrays.fill(board, \"-\");\n for(int i = 0;i < 5;i++) { \n board[i] = \"A\";\n }\n Collections.shuffle(Arrays.asList(board));\n System.out.println(Arrays.toString(board));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20162945/" ]
74,568,130
<p>Here is the code</p> <pre><code>&lt;?php $servername = &quot;localhost&quot;; $usrname = &quot;root&quot;; $pwd = &quot;&quot;; $db = &quot;test_db&quot;; // connect to the database $conn= mysqli_connect($servername, $usrname, $pwd,$db); if (!$conn){ die('connection failed' . mysqli_connect_error()); } // Create database $sql = &quot;CREATE DATABASE IF NOT EXISTS test_db&quot;; if (mysqli_query($conn, $sql)) { echo &quot;Database created successfully&lt;br&gt;&quot;; } else { echo &quot;Error creating database: &quot; . mysqli_error($conn); } ?&gt; </code></pre> <p>I am not sure what is going on as I am sure i made no errors while typing. As it keeps showing me that there is an unknown database despite the fact i made a CREATE DATABASE statement. I do not know if there is something else i need to do but by all measures the code should work. It is supposed to echo the &quot;Database created successfully&quot; or the error message.</p>
[ { "answer_id": 74568354, "author": "william beaudin", "author_id": 20162945, "author_profile": "https://Stackoverflow.com/users/20162945", "pm_score": 1, "selected": false, "text": "static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{\n int iterationNumber = checkForNumberOfAInArray(board);\n for (int i = 0; i < iterationNumber; i++) {\n int j = (int)(Math.random()*board.length);\n \n while(board[j-1].equals(\"A\") || board[j+1].equals(\"A\") || board[j].equals(\"A\")){\n j = (int)(Math.random()*board.length);\n }\n board[j] = \"A\";\n }\n return board;\n}\n\nstatic int checkForNumberOfAInArray(String[] board){\n int countOfA = 0;\n\n for (String x : board) {\n if(x == \"A\"){\n countOfA++;\n }\n }\n\n System.out.println(countOfA);\n return (5 - countOfA);\n}\n" }, { "answer_id": 74572399, "author": "g00se", "author_id": 16376827, "author_profile": "https://Stackoverflow.com/users/16376827", "pm_score": 0, "selected": false, "text": " String[] board = new String[29];\n Arrays.fill(board, \"-\");\n for(int i = 0;i < 5;i++) { \n board[i] = \"A\";\n }\n Collections.shuffle(Arrays.asList(board));\n System.out.println(Arrays.toString(board));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636544/" ]
74,568,158
<p>I need some help combing the styling of this span-button which is provided by the website I use. I don't think I can change the button type to another type, and since im using Squarespace to add the button to the site, the whole code needs to be in HTML.</p> <p>The code for the button is provided, and a link to how I want the button to look. Im looking forward to your guys' ideas and ways to do it!</p> <p>Ive tried to style it using different ways, but can't seem to understand how to exactly implement the css into the span-element.</p> <p>This is the provided code for the button:</p> <pre><code>&lt;span class=&quot;glf-button&quot; data-glf-cuid=&quot;44e34391-d2c4-489d-90d7-22b985839fe4&quot; data-glf-ruid=&quot;8c4c9138-a45f-41bb-8e6b-042c85a98586&quot; &gt; Se Meny &amp; Bestill&lt;/span&gt; &lt;script src=&quot;https://www.fbgcdn.com/embedder/js/ewm2.js&quot; defer async &gt;&lt;/script&gt; </code></pre> <p>Here you can find the desired styling of the button: <a href="https://codepen.io/romeg33/pen/mrdGMe" rel="nofollow noreferrer">https://codepen.io/romeg33/pen/mrdGMe</a></p> <pre><code>&lt;div class=&quot;block-center&quot;&gt; &lt;button class=&quot;btn&quot; role=&quot;button&quot;&gt;&lt;span&gt;Hover and click!&lt;/span&gt;&lt;/button&gt; &lt;/div&gt; </code></pre> <pre><code>@import 'https://fonts.googleapis.com/css?family=Roboto:300'; body { background: #F5F5F5; } .block-center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } $btn-color: #03A9F4; $line-color: #0288D1; $txt-color: #fff; $btn-font-family: 'Roboto', sans-serif; $btn-font-size: 24px; $transition-in: width .2s cubic-bezier(0.770, 0.000, 0.175, 1.000), height .2s .2s cubic-bezier(0.770, 0.000, 0.175, 1.000), border-color .4s; $transition-out: width .4s cubic-bezier(0.770, 0.000, 0.175, 1.000), height .2s .4s cubic-bezier(0.770, 0.000, 0.175, 1.000); .btn { position: relative; padding: 15px 20px; background-color: $btn-color; border: none; text-decoration: none; color: $txt-color; font-family: $btn-font-family; font-size: $btn-font-size; letter-spacing: 1px; z-index: 1; cursor: pointer; outline: none; &amp; span { position: relative; z-index: 2; } &amp;:before { content: ''; position: absolute; box-sizing: border-box; border-bottom: 4px solid transparent; left: 0; bottom: 0; width: 0; height: 4px; background-color: $line-color; transition: $transition-out; } &amp;:hover { &amp;:before { width: 100%; height: 100%; transition: $transition-in; } } &amp;:active { &amp;:before { border-bottom: 4px solid $btn-color; } } } </code></pre>
[ { "answer_id": 74568354, "author": "william beaudin", "author_id": 20162945, "author_profile": "https://Stackoverflow.com/users/20162945", "pm_score": 1, "selected": false, "text": "static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{\n int iterationNumber = checkForNumberOfAInArray(board);\n for (int i = 0; i < iterationNumber; i++) {\n int j = (int)(Math.random()*board.length);\n \n while(board[j-1].equals(\"A\") || board[j+1].equals(\"A\") || board[j].equals(\"A\")){\n j = (int)(Math.random()*board.length);\n }\n board[j] = \"A\";\n }\n return board;\n}\n\nstatic int checkForNumberOfAInArray(String[] board){\n int countOfA = 0;\n\n for (String x : board) {\n if(x == \"A\"){\n countOfA++;\n }\n }\n\n System.out.println(countOfA);\n return (5 - countOfA);\n}\n" }, { "answer_id": 74572399, "author": "g00se", "author_id": 16376827, "author_profile": "https://Stackoverflow.com/users/16376827", "pm_score": 0, "selected": false, "text": " String[] board = new String[29];\n Arrays.fill(board, \"-\");\n for(int i = 0;i < 5;i++) { \n board[i] = \"A\";\n }\n Collections.shuffle(Arrays.asList(board));\n System.out.println(Arrays.toString(board));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14934468/" ]
74,568,182
<p>I am new to Terraform and its CDK. I am confuse about the following:</p> <p>When I try to run the <code>tf.json</code> generated through <code>cdktf synth</code> using <code>cdktf deploy</code>, <code>terraform plan</code> or <code>terraform apply</code>, the console keeps telling me that all attributes inside the <code>access_config</code> are required and emit errors, but I checked the <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance#nested_access_config" rel="nofollow noreferrer">documentation</a>, it is said that these field can be optional.</p> <p>So, I want to know is it a bug or the documentation is wrong ?</p>
[ { "answer_id": 74596588, "author": "Hong", "author_id": 13037561, "author_profile": "https://Stackoverflow.com/users/13037561", "pm_score": 0, "selected": false, "text": "access_config \"access_config\":[{\n \"nat_ip\":\"google_compute_address.some_name.address\",\n \"public_ptr_domain_name\":\"\",\n \"network_tier\":\"\"\n}]\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13037561/" ]
74,568,184
<p>I wish to add dollar symbol in front of all the values in my column.</p> <h2>Data</h2> <pre><code>ID Price aa 800 bb 2 cc 300 cc 4 </code></pre> <h2>Desired</h2> <pre><code>ID Price aa $800 bb $2 cc $300 cc $4 </code></pre> <h2>Doing</h2> <pre><code>df.loc[&quot;Price&quot;] ='$'+ df[&quot;Price&quot;].map('{:,.0f}'.format) </code></pre> <p>I believe I have to map this, not 100% sure. Any suggestion is appreciated.</p>
[ { "answer_id": 74568215, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "str.replace df[\"Price\"] = df[\"Price\"].astype(str).str.replace(r'^', '$', regex=True)\n" }, { "answer_id": 74568356, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 3, "selected": true, "text": "df[\"Price\"] = '$' + df[\"Price\"].astype(str)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942100/" ]
74,568,189
<p>I am trying to use netlify serverless functions with svelte/vite using netlify dev. Im running svelte 3.52.0, vite 3.2.3, node 16.14.0, netlify-cli 12.2.7 (Windows).</p> <p>When I run netlify dev and choose either &quot;Svelte npm run dev&quot; or Svelte npm run build it &quot;hangs&quot; constantly displaying &quot;Waiting for framework port 5173&quot; and states this can be configured using 'targetPort' property in netlify.toml.</p> <p>So in netlify.toml I have</p> <pre><code>[build] command = &quot;npm run build&quot; publish=&quot;dist&quot; functions=&quot;functions&quot; [dev] targetPort=5173 port=8888 </code></pre> <p>But it does the same. It &quot;works&quot; (&quot;* *&quot;) if I choose any of the three vite options but then the serverless function I set up is giving me: <em>Request from ::1: GET /.netlify/functions/getProjects Response with status 404 in 2ms.</em></p> <p>My App.svelte (not doing anything with data yet but setup below was to test)</p> <pre><code>&lt;script&gt; async function myProjects() { let projects = [] const url = `/.netlify/functions/getProjects` const res = await fetch(url) .then(r =&gt; r.json()) .then(data =&gt; { projects = data }) } &lt;/script&gt; &lt;main&gt; &lt;button on:click={myProjects}&gt;MyProjects&lt;/button&gt; &lt;/main&gt; </code></pre> <p>getProjects.js is in netlify\functions\getProjects folder and is:</p> <pre><code>const { MongoClient } = require('mongodb') require('dotenv').config() const mongoClient = new MongoClient(process.env.MONGODB_URI) const clientPromise = mongoClient.connect() const handler = async event =&gt; { try { const database = (await clientPromise).db(process.env.MONGODB_DATABASE) const collection = database.collection(process.env.MONGODB_COLLECTION) const results = await collection.find({}).limit(100).toArray() return { statuscode: 200, body: JSON.stringify(results) } } catch (error) { return { statusCode: 500, body: error.toString() } } } module.exports = { handler } </code></pre> <p>All the .env settings are correct and work with an express server so these should be good.</p> <p>Any thoughts/suggestions appreciated.</p>
[ { "answer_id": 74606842, "author": "Pick Avana", "author_id": 10936092, "author_profile": "https://Stackoverflow.com/users/10936092", "pm_score": 1, "selected": true, "text": "[build]\n publish=\"dist\"\n[dev]\n command = \"npm run dev\"\n targetPort=5173\n port=8888\n[functions]\nnode_bundler = \"esbuild\"\n const { MongoClient } = require('mongodb')\nrequire('dotenv').config()\n\nconst mongoClient = new MongoClient(process.env.MONGODB_URI)\nconst clientPromise = mongoClient.connect()\nif (clientPromise) {\n console.log('Connected to Mongodb')\n} else {\n console.log('NOT Connected toMongodb')\n}\n// terminal shows connected\n//\nexport const handler = async (event, context) => {\n //\n const database = (await clientPromise).db(process.env.MONGODB_DATABASE)\n // console.log('after await promise')\n const collection = database.collection(process.env.MONGODB_COLLECTION)\n //\n try {\n const data = await collection.find({}).limit(100).toArray()\n // console.log('my results: ', data)\n return {\n statusCode: 200,\n body: JSON.stringify(data)\n }\n } catch (error) {\n return { statusCode: 500, body: error.toString() }\n }\n}\n <script>\n import projects from './stores/projects'\n\n function showProjects() {\n console.log($projects)\n }\n</script>\n\n<main>\n <button on:click={showProjects}>MyProjects</button>\n</main>\n import { writable } from 'svelte/store'\n\n// import Api functions\nimport { getProjects } from '../backend/Api'\n\nconst store = writable([], () => {\n setProjects()\n return () => {}\n})\n\nasync function setProjects() {\n let projects = await getProjects()\n if (projects) {\n store.set(projects)\n }\n}\n\n//export default store\nconst customProjectStore = {\n subscribe: store.subscribe\n}\n\nexport default customProjectStore\n export async function getProjects() {\n let projects = []\n const url = `/.netlify/functions/getProjects`\n const res = await fetch(url)\n .then(r => r.json())\n .then(data => {\n projects = data\n })\n return projects\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10936092/" ]
74,568,196
<p>I want to search a list of group of strings inside a text file (.txt or .log).</p> <ol> <li>it must include group A or B (or CDE..).</li> <li>group A OR B each words need in the same line but not near by. (eg. [&quot;123456&quot;, &quot;Login&quot;] or [&quot;123457&quot;, &quot;Login&quot;] if in the same line then save it to a new txt file.</li> </ol> <p>Some of example output line:</p> <pre><code>20221110,1668057560.965,AE111,123457,0,&quot;Action=Account Login,XXX,XXX&quot;,XXX,XXX 20221110,1668057560.965,AE112,123458,0,&quot;Action=Account Login,XXX,XXX&quot;,XXX,XXX 20221111,1668057560.965,AE113,123458,0,&quot;Action=Order,XXX,XXX&quot;,XXX,XXX </code></pre> <p>below is my code:</p> <pre><code>import os, re path = &quot;Log\\&quot; file_list = [path + f for f in os.listdir(path) if f.endswith('.log')] keep_phrases1 = [&quot;123456&quot;, &quot;Login&quot;] keep_phrases2 = [&quot;123457&quot;, &quot;Login&quot;] pat = r&quot;\b.*?\b&quot;.join([re.escape(word) for word in keep_phrases1]) pat = re.compile(r&quot;\b&quot; + pat + r&quot;\b&quot;) pat2 = r&quot;\b.*?\b&quot;.join([re.escape(word) for word in keep_phrases2]) pat2 = re.compile(r&quot;\b&quot; + pat2 + r&quot;\b&quot;) print(pat2,pat) if len(file_list) != 0: for infile in sorted(file_list): with open(infile, encoding=&quot;latin-1&quot;) as f: f = f.readlines() for line in f: found1 = pat.search(line) found2 = pat2.search(line) if found1 or found2: with open(outfile, &quot;a&quot;) as wf: wf.write(line) </code></pre> <p>It's works for me but not easy to add more group of words. And I think the code is not good for understand?</p> <p>My problems is How can I simplify the code? How can I easier to add other group to search? e.g. [&quot;123458&quot;, &quot;Login&quot;] [&quot;123456&quot;, &quot;order&quot;] [&quot;123457&quot;, &quot;order&quot;]</p>
[ { "answer_id": 74606842, "author": "Pick Avana", "author_id": 10936092, "author_profile": "https://Stackoverflow.com/users/10936092", "pm_score": 1, "selected": true, "text": "[build]\n publish=\"dist\"\n[dev]\n command = \"npm run dev\"\n targetPort=5173\n port=8888\n[functions]\nnode_bundler = \"esbuild\"\n const { MongoClient } = require('mongodb')\nrequire('dotenv').config()\n\nconst mongoClient = new MongoClient(process.env.MONGODB_URI)\nconst clientPromise = mongoClient.connect()\nif (clientPromise) {\n console.log('Connected to Mongodb')\n} else {\n console.log('NOT Connected toMongodb')\n}\n// terminal shows connected\n//\nexport const handler = async (event, context) => {\n //\n const database = (await clientPromise).db(process.env.MONGODB_DATABASE)\n // console.log('after await promise')\n const collection = database.collection(process.env.MONGODB_COLLECTION)\n //\n try {\n const data = await collection.find({}).limit(100).toArray()\n // console.log('my results: ', data)\n return {\n statusCode: 200,\n body: JSON.stringify(data)\n }\n } catch (error) {\n return { statusCode: 500, body: error.toString() }\n }\n}\n <script>\n import projects from './stores/projects'\n\n function showProjects() {\n console.log($projects)\n }\n</script>\n\n<main>\n <button on:click={showProjects}>MyProjects</button>\n</main>\n import { writable } from 'svelte/store'\n\n// import Api functions\nimport { getProjects } from '../backend/Api'\n\nconst store = writable([], () => {\n setProjects()\n return () => {}\n})\n\nasync function setProjects() {\n let projects = await getProjects()\n if (projects) {\n store.set(projects)\n }\n}\n\n//export default store\nconst customProjectStore = {\n subscribe: store.subscribe\n}\n\nexport default customProjectStore\n export async function getProjects() {\n let projects = []\n const url = `/.netlify/functions/getProjects`\n const res = await fetch(url)\n .then(r => r.json())\n .then(data => {\n projects = data\n })\n return projects\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19646944/" ]
74,568,229
<p>i am making a digital clock but my javascript code is not working but console.log is working i have checked my code i can't find any error java script : <a href="https://i.stack.imgur.com/vXByd.png" rel="nofollow noreferrer">enter image description here</a> and the java script is working bec u can see in the website console.log is working website <a href="https://i.stack.imgur.com/RoZB3.png" rel="nofollow noreferrer">enter image description here</a> and i have use css and html to make it nice this is html code : <a href="https://i.stack.imgur.com/zI3Kx.png" rel="nofollow noreferrer">enter image description here</a></p> <p>and i am beginner in java script</p> <p>to fix my code why it is not working</p>
[ { "answer_id": 74606842, "author": "Pick Avana", "author_id": 10936092, "author_profile": "https://Stackoverflow.com/users/10936092", "pm_score": 1, "selected": true, "text": "[build]\n publish=\"dist\"\n[dev]\n command = \"npm run dev\"\n targetPort=5173\n port=8888\n[functions]\nnode_bundler = \"esbuild\"\n const { MongoClient } = require('mongodb')\nrequire('dotenv').config()\n\nconst mongoClient = new MongoClient(process.env.MONGODB_URI)\nconst clientPromise = mongoClient.connect()\nif (clientPromise) {\n console.log('Connected to Mongodb')\n} else {\n console.log('NOT Connected toMongodb')\n}\n// terminal shows connected\n//\nexport const handler = async (event, context) => {\n //\n const database = (await clientPromise).db(process.env.MONGODB_DATABASE)\n // console.log('after await promise')\n const collection = database.collection(process.env.MONGODB_COLLECTION)\n //\n try {\n const data = await collection.find({}).limit(100).toArray()\n // console.log('my results: ', data)\n return {\n statusCode: 200,\n body: JSON.stringify(data)\n }\n } catch (error) {\n return { statusCode: 500, body: error.toString() }\n }\n}\n <script>\n import projects from './stores/projects'\n\n function showProjects() {\n console.log($projects)\n }\n</script>\n\n<main>\n <button on:click={showProjects}>MyProjects</button>\n</main>\n import { writable } from 'svelte/store'\n\n// import Api functions\nimport { getProjects } from '../backend/Api'\n\nconst store = writable([], () => {\n setProjects()\n return () => {}\n})\n\nasync function setProjects() {\n let projects = await getProjects()\n if (projects) {\n store.set(projects)\n }\n}\n\n//export default store\nconst customProjectStore = {\n subscribe: store.subscribe\n}\n\nexport default customProjectStore\n export async function getProjects() {\n let projects = []\n const url = `/.netlify/functions/getProjects`\n const res = await fetch(url)\n .then(r => r.json())\n .then(data => {\n projects = data\n })\n return projects\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595835/" ]
74,568,332
<p>I pass in a string, &quot;--pl-&quot; into the function, wordle. I would like the function to return a set of strings with all possible 5 letter words with 'p' as 3rd letter and 'l' as 4th letter. This would mean that the set would return 26^3 different strings.</p> <p>I am trying to use recursion to do this but am not sure how to.</p> <pre><code> #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;map&gt; #include &lt;set&gt; // #include &quot;wordle.h&quot; // #include &quot;dict-eng.h&quot; using namespace std; // MOST UP TO DATE // Add prototypes of helper functions here // Definition of primary wordle function set&lt;string&gt; wordle(string&amp; in, string&amp; floating, set&lt;string&gt;&amp; dict){ set&lt;string&gt; possibleList; int length = in.length(); // iterate over each letter for(int i = 0; i&lt;length;i++){ // only if - if (in[i] == '-'){ for(int j = 97; j&lt;=122; j++){ in[i]=char(j); possibleList.insert(in); } set&lt;string&gt;::iterator itr; for (itr = possibleList.begin(); itr != possibleList.end(); itr++) { auto S = *itr; //copy of *iter wordle(S, floating, dict); //use S } } } // if we reach here, that means that we now have all possibilities in the set return possibleList; } // end of function int main(){ string in = &quot;--pl-&quot;; string floating = &quot;ae&quot;; set&lt;string&gt; dict; // set with 6 strings, should only return 2 of these dict.insert(&quot;joshua&quot;); // same dict.insert(&quot;phone&quot;); //diff dict.insert(&quot;apple&quot;); //same dict.insert(&quot;aepll&quot;); //same dict.insert(&quot;eapll&quot;); //same dict.insert(&quot;ae&quot;); // diff set&lt;string&gt; finalSet = wordle(in, floating, dict); cout &lt;&lt; &quot;got here&quot; &lt;&lt; endl; set&lt;string&gt;::iterator itr; for (itr = finalSet.begin(); itr != finalSet.end(); itr++) { cout &lt;&lt; *itr &lt;&lt; endl; } return 0; // how this works: // take all possible strings of the form of size n // then remove all requirements not met } </code></pre> <p>What is happening is that it prints the following:</p> <p>got here a-pl- b-pl- c-pl- d-pl- e-pl- f-pl- g-pl- h-pl- i-pl- j-pl- k-pl- l-pl- m-pl- n-pl- o-pl- p-pl- q-pl- r-pl- s-pl- t-pl- u-pl- v-pl- w-pl- x-pl- y-pl- z-pl- zapl- zbpl- zcpl- zdpl- zepl- zfpl- zgpl- zhpl- zipl- zjpl- zkpl- zlpl- zmpl- znpl- zopl- zppl- zqpl- zrpl- zspl- ztpl- zupl- zvpl- zwpl- zxpl- zypl- zzpl- zzpla zzplb zzplc zzpld zzple zzplf zzplg zzplh zzpli zzplj zzplk zzpll zzplm zzpln zzplo zzplp zzplq zzplr zzpls zzplt zzplu zzplv zzplw zzplx zzply zzplz</p>
[ { "answer_id": 74568525, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "floating dict #include <vector>\n#include <string>\n\nstd::vector<std::string> combine(\n const std::vector<std::string>& acc, const std::string& next) {\n std::vector<std::string> result;\n for (const auto& x: acc) {\n for (auto y: next) {\n result.push_back(x + y);\n }\n }\n return result;\n}\n\nstd::string symbols = \"abcdefghijklmnopqrstuvwxyz\";\n\nstd::vector<std::string> wordle(const std::string& in) {\n std::vector<std::string> result{\"\"};\n for (auto c: in) {\n result = combine(\n result,\n c == '-'? symbols : std::string(1, c));\n }\n return result;\n}\n wordle(\"---pl-\")" }, { "answer_id": 74568660, "author": "Amega", "author_id": 2054918, "author_profile": "https://Stackoverflow.com/users/2054918", "pm_score": 1, "selected": true, "text": "wordle possibleList wordle possibleList possibleList _ _ _ _ FUNCTION wordleRecursive(str, start=0):\n possibleList = []\n foundPlaceHolder = False\n \n FOR (i=start; i<str.length; i++):\n IF str[i] == '_':\n foundPlaceHolder = True\n FOR (j=97; j<122; j++):\n newStr = copy(str)\n newStr[i] = char(j)\n nestedList = wordleRecursive(newStr, i + 1)\n possibleList = merge(possibleList, nestedList)\n \n // We need to find only first occurance\n BREAK \n\n // This is needed if the substring does not contain \"_\" anymore\n // in this case we need to return the list with a single item,\n // Containing the str itself.\n IF NOT foundPlaceHolder:\n possibleList = [str]\n\n RETURN possibleList\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585987/" ]
74,568,352
<p>tl;dr questions:</p> <ol> <li>how to parse MIME content into threads (thus lists of individual replies &amp; forwards)</li> <li>any libraries that do that?</li> <li>Does Mime-Version: 1.0 standardize the way threads are represented?</li> </ol> <p>I'm analyzing enron dataset (<a href="https://www.cs.cmu.edu/%7E./enron/" rel="nofollow noreferrer">https://www.cs.cmu.edu/~./enron/</a>, you can also browse the documents here: <a href="http://www.enron-mail.com/email/" rel="nofollow noreferrer">http://www.enron-mail.com/email/</a>) This dataset is a collection of ~500K emails. Emails are represented as Mime-Version: 1.0 files, there are no attachments.</p> <p>This is a typical file:</p> <pre><code>Message-ID: &lt;4250772.1075857358369.JavaMail.evans@thyme&gt;^M Date: Tue, 12 Dec 2000 09:19:00 -0800 (PST)^M From: david.portz@enron.com^M To: clint.dean@enron.com^M Subject: City of Bryan Dec parking transactions^M Cc: doug.gilbert-smith@enron.com, elizabeth.sager@enron.com, ^M melissa.murphy@enron.com^M Mime-Version: 1.0^M Content-Type: text/plain; charset=us-ascii^M Content-Transfer-Encoding: 7bit^M Bcc: doug.gilbert-smith@enron.com, elizabeth.sager@enron.com, ^M melissa.murphy@enron.com^M X-From: David Portz^M X-To: Clint Dean^M X-cc: Doug Gilbert-Smith, Elizabeth Sager, Melissa Ann Murphy^M X-bcc: ^M X-Folder: \Clint_Dean_Dec2000\Notes Folders\Notes inbox^M X-Origin: Dean-C^M X-FileName: cdean.nsf^M ^M Following discussions with you and Doug, attached is a draft parking transaction agreement for your review and, if acceptable, for circualtion to the counterparty. Please call me with any questions. --David </code></pre> <p>There is a handy, widely adopted python library that makes life easier in parsing those kind of files:</p> <pre><code>import email import email.policy parsed_email = email.message_from_string(open(filename, 'r').read(), policy=email.policy.default) body = parsed_email.get_payload() from_field = parsed_email['From'] ... </code></pre> <p>However, I didn't find a reliable way to further parse email content to threads: sub_email_1 -&gt; sub_email_2 -&gt; ... &gt; sub_email_n, etc. <code>get_payload</code> returns everything, all together.</p> <p>Here is an example of MIME with threads: <a href="https://justpaste.it/bf5zr" rel="nofollow noreferrer">https://justpaste.it/bf5zr</a> (the file is 233 lines, so pasted separately). There is clearly a thread:</p> <ol> <li>Christi L Nicolay sent email on 04/30/2001 02:20 PM</li> <li>later Christi L Nicolay replied to its own email on 05/03/2001 09:23 PM</li> <li>Lloyd Will replied to that thread on 05/03/2001 09:26 PM</li> <li>Christi L Nicolay replied on 05/07/2001 11:47 AM</li> <li>Tom May forwarded the whole thread on Mon, 7 May 2001 06:58:00 -0700</li> </ol> <p>Any library / existing solution that could do that? Looking at glance into the data, I got impression that there are numerous tiny variants how those threads are organized. Sometimes there are nested <code>&gt; &gt;</code> fields accompanying sub-emails, sometimes there is <code>---Original Message---</code> message, etc. It seems way less defined than MIME header fields.</p> <p>I can write some regex-backed python script that parses one email or another, but it will not work universally for the whole Enron dataset. Some more examples of threads from the Enron dataset:</p> <p><a href="http://www.enron-mail.com/email/mann-k/discussion_threads/FW_Salmon_Energy_Turbine_Agreement_5.html" rel="nofollow noreferrer">http://www.enron-mail.com/email/mann-k/discussion_threads/FW_Salmon_Energy_Turbine_Agreement_5.html</a></p> <p><a href="http://www.enron-mail.com/email/brawner-s/discussion_threads/Fw_Fw_TIGHT_SKIRTS_AND_TEXANS_2.html" rel="nofollow noreferrer">http://www.enron-mail.com/email/brawner-s/discussion_threads/Fw_Fw_TIGHT_SKIRTS_AND_TEXANS_2.html</a></p> <p><a href="http://www.enron-mail.com/email/brawner-s/_sent_mail/Fw_Time_Friends_3.html" rel="nofollow noreferrer">http://www.enron-mail.com/email/brawner-s/_sent_mail/Fw_Time_Friends_3.html</a></p> <p>That led me to question #3: whether the mime format standardizes threads at all.</p>
[ { "answer_id": 74568525, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "floating dict #include <vector>\n#include <string>\n\nstd::vector<std::string> combine(\n const std::vector<std::string>& acc, const std::string& next) {\n std::vector<std::string> result;\n for (const auto& x: acc) {\n for (auto y: next) {\n result.push_back(x + y);\n }\n }\n return result;\n}\n\nstd::string symbols = \"abcdefghijklmnopqrstuvwxyz\";\n\nstd::vector<std::string> wordle(const std::string& in) {\n std::vector<std::string> result{\"\"};\n for (auto c: in) {\n result = combine(\n result,\n c == '-'? symbols : std::string(1, c));\n }\n return result;\n}\n wordle(\"---pl-\")" }, { "answer_id": 74568660, "author": "Amega", "author_id": 2054918, "author_profile": "https://Stackoverflow.com/users/2054918", "pm_score": 1, "selected": true, "text": "wordle possibleList wordle possibleList possibleList _ _ _ _ FUNCTION wordleRecursive(str, start=0):\n possibleList = []\n foundPlaceHolder = False\n \n FOR (i=start; i<str.length; i++):\n IF str[i] == '_':\n foundPlaceHolder = True\n FOR (j=97; j<122; j++):\n newStr = copy(str)\n newStr[i] = char(j)\n nestedList = wordleRecursive(newStr, i + 1)\n possibleList = merge(possibleList, nestedList)\n \n // We need to find only first occurance\n BREAK \n\n // This is needed if the substring does not contain \"_\" anymore\n // in this case we need to return the list with a single item,\n // Containing the str itself.\n IF NOT foundPlaceHolder:\n possibleList = [str]\n\n RETURN possibleList\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12314390/" ]
74,568,366
<p>I downloaded and run a C++ project for Digital-persona-sdk <a href="https://github.com/iamonuwa/Digital-Persona-SDK/" rel="nofollow noreferrer">https://github.com/iamonuwa/Digital-Persona-SDK/</a> finger print project.That have two projects in after install the sdk. That project only Capture and Verification function only written.Not written for get serial number. Does anyone have an sample program for solving this problem?</p>
[ { "answer_id": 74568525, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 1, "selected": false, "text": "floating dict #include <vector>\n#include <string>\n\nstd::vector<std::string> combine(\n const std::vector<std::string>& acc, const std::string& next) {\n std::vector<std::string> result;\n for (const auto& x: acc) {\n for (auto y: next) {\n result.push_back(x + y);\n }\n }\n return result;\n}\n\nstd::string symbols = \"abcdefghijklmnopqrstuvwxyz\";\n\nstd::vector<std::string> wordle(const std::string& in) {\n std::vector<std::string> result{\"\"};\n for (auto c: in) {\n result = combine(\n result,\n c == '-'? symbols : std::string(1, c));\n }\n return result;\n}\n wordle(\"---pl-\")" }, { "answer_id": 74568660, "author": "Amega", "author_id": 2054918, "author_profile": "https://Stackoverflow.com/users/2054918", "pm_score": 1, "selected": true, "text": "wordle possibleList wordle possibleList possibleList _ _ _ _ FUNCTION wordleRecursive(str, start=0):\n possibleList = []\n foundPlaceHolder = False\n \n FOR (i=start; i<str.length; i++):\n IF str[i] == '_':\n foundPlaceHolder = True\n FOR (j=97; j<122; j++):\n newStr = copy(str)\n newStr[i] = char(j)\n nestedList = wordleRecursive(newStr, i + 1)\n possibleList = merge(possibleList, nestedList)\n \n // We need to find only first occurance\n BREAK \n\n // This is needed if the substring does not contain \"_\" anymore\n // in this case we need to return the list with a single item,\n // Containing the str itself.\n IF NOT foundPlaceHolder:\n possibleList = [str]\n\n RETURN possibleList\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19718656/" ]
74,568,387
<p>I have <code>object</code> as following format :</p> <pre><code>let objs = [ {Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1'} {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3'} {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6'} ] </code></pre> <p>I want to achive an object as following :</p> <pre><code>{Name : 'Total', Y1 : '4', Y2 : '5',Y3 : '10'} </code></pre> <p>I’ve tired to create the object by using <strong>.reduce</strong> but think there are more effiecent way to create the object.</p> <pre><code>let a = objs.reduce((total, obj) =&gt; obj['Y1'] + total, 0) let b = objs.reduce((total, obj) =&gt; obj['Y2'] + total, 0) let c = objs.reduce((total, obj) =&gt; obj['Y3'] + total, 0) //then create new object and merge with exiting object </code></pre> <p>How can I achieve the object in more effiecent way?</p>
[ { "answer_id": 74568401, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "reduce reduce let objs = [\n {Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1'},\n {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3'},\n {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6'}\n ]\n \nlet result1 = objs.reduce((a,c) =>{\n a.Y1 += +c.Y1\n a.Y2 += +c.Y2\n a.Y3 += +c.Y3\n return a\n},{'Name':'Total','Y1':0,'Y2':0,'Y3':0})\nconsole.log(result1)\n\nlet result2 = objs.reduce((a,{Y1,Y2,Y3}) =>{\n a.Y1 += +Y1\n a.Y2 += +Y2\n a.Y3 += +Y3\n return a\n},{'Name':'Total','Y1':0,'Y2':0,'Y3':0})\nconsole.log(result2) let objs = [\n {Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1'},\n {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3'},\n {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6'}\n ]\n \nlet result = objs.reduce((a,c) =>{\n let keys = Object.keys(c).slice(1)\n keys.forEach(k => {\n a[k] += +c[k] \n })\n return a\n},{'Name':'Total','Y1':0,'Y2':0,'Y3':0})\nconsole.log(result)" }, { "answer_id": 74568488, "author": "Underdeveloper", "author_id": 18011249, "author_profile": "https://Stackoverflow.com/users/18011249", "pm_score": 0, "selected": false, "text": "let y1 = 0;\nlet y2 = 0;\nlet y3 = 0; \nlet objs = [\n {\"Name\" : 'A', \"Y1\" : '1', \"Y2\" : '1', \"Y3\" : '1'},\n {\"Name\" : 'B', \"Y1\" : '2', \"Y2\" : '3', \"Y3\" : '3'},\n {\"Name\" : 'C', \"Y1\" : '1', \"Y2\" : '1', \"Y3\" : '6'}\n]\n\nobjs.forEach((e)=>{\n y1 = y1 + parseInt(e[\"Y1\"]);\n y2 = y2 + parseInt(e[\"Y2\"]);\n y3 = y2 + parseInt(e[\"Y3\"]);\n});\n\nconsole.log(y1);\nconsole.log(y2);\nconsole.log(y3);" }, { "answer_id": 74568537, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 0, "selected": false, "text": "let objs = [\n {Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1', Y4: 'foo', Y5: '1'},\n {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3', Y4: '2'},\n {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6', Y5: 'bar'}\n ]\n \nlet result = objs.reduce((a,c) =>{\n const copy = {...c};\n delete copy.Name;\n const keys = Object.keys(copy)\n for (const k of keys) {\n const num = parseInt(c[k]);\n if (isNaN(num)) continue;\n if (a[k] === undefined) a[k] = 0;\n a[k] += num; \n }\n return a\n},{'Name':'Total'})\n\nconsole.log(result)" }, { "answer_id": 74568554, "author": "Mayank Gupta", "author_id": 17691526, "author_profile": "https://Stackoverflow.com/users/17691526", "pm_score": 0, "selected": false, "text": "let objs = [\n { Name: \"A\", Y1: \"1\", Y2: \"1\", Y3: \"1\" },\n { Name: \"B\", Y1: \"2\", Y2: \"3\", Y3: \"3\" },\n { Name: \"C\", Y1: \"1\", Y2: \"1\", Y3: \"6\" },\n ];\n let tempY1 = 0;\n let tempY2 = 0;\n let tempY3 = 0;\n for (let i = 0; i < objs.length; i++) {\n tempY1 += parseInt(objs[i].Y1);\n tempY2 += parseInt(objs[i].Y2);\n tempY3 += parseInt(objs[i].Y3);\n }\n let newObj = { name: \"total\", Y1: tempY1, Y2: tempY2, Y3: tempY3 };\n console.log(newObj);\n" }, { "answer_id": 74568963, "author": "Ori Drori", "author_id": 5157454, "author_profile": "https://Stackoverflow.com/users/5157454", "pm_score": 0, "selected": false, "text": "_.mergeWith() Name Name const objs = [{Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1'}, {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3'}, {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6'}]\n \nconst result = _.mergeWith({}, ...objs, (a = 0, b, key) => \n key === 'Name' ? 'Total' : a + +b\n)\n\nconsole.log(result) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js\" integrity=\"sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script> String() const objs = [{Name : 'A', Y1 : '1', Y2 : '1',Y3 : '1'}, {Name : 'B', Y1 : '2', Y2 : '3',Y3 : '3'}, {Name : 'C', Y1 : '1', Y2 : '1',Y3 : '6'}]\n \nconst result = _.mergeWith({}, ...objs, (a = 0, b, key) => \n key === 'Name' ? 'Total' : String(+a + +b)\n)\n\nconsole.log(result) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js\" integrity=\"sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script> +a + +b" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681701/" ]
74,568,388
<p>I have created a flask application of the soccer tournament. I am having issues with the form page, the submit button should display a text &quot;Hello&quot; + string + &quot;for submitting!&quot;. I created a additional html page named display that displays this. Once, I filled out the form it did not do nothing.</p> <pre><code>#import the flask module from flask import Flask, render_template, request,url_for app = Flask(__name__) @app.route(&quot;/&quot;) def home(): return render_template('home.html') @app.route(&quot;/teams&quot;) def teams(): return render_template('teams.html') @app.route(&quot;/form&quot;, methods = ['GET','POST']) def form(): #get the method of the post and the method of the get if request.method == &quot;POST&quot; and request.form.get('submit'): string = request.form.get('name') feedback = &quot;Hello&quot; + string + &quot;\n Thank you for submiting!&quot; return render_template('display.html').format(feedback = feedback) else: return render_template('form.html').format(feedback=&quot;&quot;) #run the program if __name__ == &quot;__main__&quot;: app.run() </code></pre> <p>Home html</p> <pre><code></code></pre>
[ { "answer_id": 74568443, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "{{feedback}} render_template render_template render_template(\"form.html\", feedback=feedback) name form.html comments teams.html" }, { "answer_id": 74568456, "author": "Abhishek G", "author_id": 12071682, "author_profile": "https://Stackoverflow.com/users/12071682", "pm_score": 1, "selected": false, "text": "if request.method == \"POST\" and request.form.get('submit'):\n if request.method == \"POST\" and request.form.get('user'):\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20482343/" ]
74,568,402
<p>I have a problem when creating express JS router.</p> <p>I can not passing req and res to my class method.</p> <p><strong>Not Work</strong> <code>app.get('/', controller.index)</code></p> <p><strong>Work</strong> <code>app.get('/', (res,req) =&gt; controller.index(req,res)</code></p> <p>The following is the flow of the routing that I made:<br /> app.js (Main file) &gt; /routes/index.js &gt; /routes/user.route.js &gt; /controllers/user.controller.js &gt; /services/user.services.js</p> <p><strong>app.js</strong></p> <pre><code>import express from 'express'; import cors from 'cors'; import routes from './routes'; import db from './models'; import dotenv from 'dotenv'; dotenv.config(); const app = express(); const port = process.env.PORT || 3001; app.use(cors()) app.use(express.json()); app.use(express.urlencoded({ extended: false })); // Database Initialize db.sequelize.sync() .then(() =&gt; { console.log(&quot; Database Connected.&quot;); }).catch((err) =&gt; { console.log(&quot;❌ Failed Connect to Database&quot;); }) // Router app.use(routes); //global dir global.__basedir = __dirname; app.enable(&quot;trust proxy&quot;); app.listen(port, () =&gt; { // logger.info(&quot;Checking the API status: Everything is OK&quot;); console.log(` App listening on port ${port}`); }) </code></pre> <p><strong>routes/index.js</strong></p> <pre><code>import express from &quot;express&quot;; import appRoutes from './app.routes'; import roleRoutes from './role.routes'; import userRoutes from './user.routes'; import authRoutes from './auth.routes'; const app = express(); // App Routes app.use('/app', appRoutes); // Role Routes app.use('/role', roleRoutes); // User Routes app.use('/user', userRoutes); // Auth Routes app.use('/auth', authRoutes); export default app; </code></pre> <p><strong>routes/user.routes.js</strong></p> <pre><code>import express from 'express'; import userController from '../controllers/user.controller'; import validateAuth from '../middlewares/validateAuth'; const app = express(); const controller = new userController; app.get('/', controller.index); export default app; </code></pre> <p><strong>controllers/user.controller.js</strong></p> <pre><code>import userServices from &quot;../services/user.services&quot;; import baseController from &quot;./base.controller&quot;; export default class userController extends baseController { constructor() { super(new userServices()); } } </code></pre> <p><strong>controllers/base.controller.js</strong></p> <pre><code>import response from &quot;../helpers/response&quot;; import lang from &quot;../helpers/lang&quot;; import dotenv from &quot;dotenv&quot;; dotenv.config(); export default class baseController { constructor(service) { this.service = service } /** * Index * Get all data with pagination */ async index(res, req) { try { const data = await this.service.paginate(req.query); if(data) { return response.success({ res, message: lang[process.env.LANG].DATA_LOADED, data }); } else { throw new Error(lang[process.env.LANG].REQUEST_FAILED); } } catch(err) { console.log(err) return response.error({ res, message: err.message, }); } } } </code></pre> <p><strong>services/user.services.js</strong></p> <pre><code>import baseServices from &quot;./base.services&quot;; import db from &quot;../models&quot;; export default class userServices extends baseServices { constructor() { const attributes = [ &quot;roleId&quot;, &quot;appId&quot;, &quot;username&quot;, &quot;password&quot;, &quot;name&quot;, &quot;phone&quot;, &quot;email&quot;, &quot;isActive&quot;, ]; super(db.user, attributes); } /** * Paginate * @param {{ * search: string, * limit: number, * offset: number, * sortBy: string, * orderBy: string, * user: object * }} data * return Promise */ paginate(data) { const { search, limit, page, sortBy, orderBy, user } = data; const offset = limit ? parseInt(limit) * parseInt(page) - parseInt(limit) : 0; let filter = {}; if (search) Object.assign(filter, { name: { [Op.like]: `%${search}%` } }); const condition = { where: filter ? filter : &quot;&quot;, order: sortBy ? [[sortBy, orderBy]] : [[&quot;name&quot;, &quot;asc&quot;]], limit: limit ? parseInt(limit) : 10, offset, include: [&quot;role&quot;, &quot;app&quot;] }; return this.model.findAndCountAll(condition); } } </code></pre> <p><strong>services/base.services.js</strong></p> <pre><code>import db from &quot;../models&quot;; const Op = db.Sequelize.Op; /** * Base Services Class */ export default class baseServices { constructor(model, attributes = []) { this.model = model; this.attributes = attributes } } </code></pre> <p><strong>Response</strong></p> <p><strong>Not Work</strong> <code>app.get('/', controller.index)</code><a href="https://i.stack.imgur.com/Rncao.png" rel="nofollow noreferrer"><br /> Error Response</a></p> <p><strong>Work</strong> <code>app.get('/', (res,req) =&gt; controller.index(req,res)</code></p> <p><a href="https://i.stack.imgur.com/qw1qp.png" rel="nofollow noreferrer">Success Response</a></p> <p>I was try to change <code>const app = express()</code> and <code>const app = express.Router()</code> but still have the same problem.</p>
[ { "answer_id": 74568443, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "{{feedback}} render_template render_template render_template(\"form.html\", feedback=feedback) name form.html comments teams.html" }, { "answer_id": 74568456, "author": "Abhishek G", "author_id": 12071682, "author_profile": "https://Stackoverflow.com/users/12071682", "pm_score": 1, "selected": false, "text": "if request.method == \"POST\" and request.form.get('submit'):\n if request.method == \"POST\" and request.form.get('user'):\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3354612/" ]
74,568,411
<p>Finding examples for ICU is difficult, but here is what I'm trying to do. I need to be able to carve graphemes out of strings. In order to do this, I need to get the sequence of grapheme lengths in bytes from the string, so I'm trying to do this using a BreakIterator.</p> <p>I decided to test this with 3 characters. <code>$</code> is one byte in UTF8, <code>£</code> is two bytes in UTF8, and <code>円</code> is 3 bytes in UTF8.</p> <p>I expected that calling <code>iter-&gt;current()</code> would return the byte offset within the string, but it does not. It returns an incrementing &quot;count&quot; of some sort, but that does not correspond to the code point position within the string, much less the overall grapheme length.</p> <p>The <a href="https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classicu_1_1CharacterIterator.html#a43a3dc93fd75548bb24507ebcf9b7d12" rel="nofollow noreferrer">documentation that I found</a> as well as <a href="https://stackoverflow.com/questions/28304321/breakiterator-icu-get-byte-length-of-grapheme-cluster">another SO question</a>, however, implies that it should be returning the byte offset. In my example, the string is 8 bytes long, but only contains 5 graphemes. The loop stops (correctly) after processing the last grapheme but, as you can see from the output, <code>iter-&gt;current()</code> never increases by more than 1, even though the grapheme that it is processing is sometimes most certainly larger than one byte long.</p> <p>Here is the code and output.</p> <p>Setup: Ubuntu 22.04 (WSL2) ICU Installed via apt: <code>icu-devtools</code>, <code>libicu-dev</code>, and <code>libicu70</code> My C++ program's compile string:</p> <pre><code>g++ -std=c++20 main2.cpp `pkg-config --libs --cflags icu-i18n icu-uc icu-io` </code></pre> <p>Minimal file:</p> <pre><code>#include &lt;memory&gt; #include &lt;cassert&gt; #include &lt;cstring&gt; #include &lt;iostream&gt; #include &lt;unicode/uconfig.h&gt; #include &lt;unicode/ustring.h&gt; #include &lt;unicode/brkiter.h&gt; using namespace std; int main() { const char * s = &quot;$\u00A3$\u5186$&quot;; UErrorCode err = U_ZERO_ERROR; unique_ptr&lt;icu::BreakIterator&gt; iter(icu::BreakIterator::createCharacterInstance(icu::Locale::getDefault(), err)); assert(U_SUCCESS(err)); iter-&gt;setText(s); auto current = iter-&gt;current(); while (iter-&gt;next() != icu::BreakIterator::DONE) { cout &lt;&lt; current &lt;&lt; endl; current = iter-&gt;current(); } cout &lt;&lt; current &lt;&lt; endl; cout &lt;&lt; &quot;String length : &quot; &lt;&lt; strlen(s) &lt;&lt; endl; cout &lt;&lt; &quot;String contents: &quot; &lt;&lt; s &lt;&lt; endl; return 0; } </code></pre> <p>Output: <a href="https://i.stack.imgur.com/50FOa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/50FOa.png" alt="Output of code execution, showing that iter-&gt;current() only increases by one each time throught the loop" /></a></p> <p>I would have expected the list to be:</p> <pre><code>0 1 3 4 7 8 </code></pre> <p>I've been staring at this for a few days... am I just missing something painfully obvious?</p>
[ { "answer_id": 74568443, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "{{feedback}} render_template render_template render_template(\"form.html\", feedback=feedback) name form.html comments teams.html" }, { "answer_id": 74568456, "author": "Abhishek G", "author_id": 12071682, "author_profile": "https://Stackoverflow.com/users/12071682", "pm_score": 1, "selected": false, "text": "if request.method == \"POST\" and request.form.get('submit'):\n if request.method == \"POST\" and request.form.get('user'):\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821565/" ]
74,568,425
<p>I am trying to create a program which takes an input of a list of lists, and gives an output of lists with only distinct elements. For example, if I had this list:</p> <pre><code>[[1,2,3,4],[1,3,6,7],[5,8,9]] </code></pre> <p>my output should just be</p> <pre><code>[5,8,9] </code></pre> <p>because only [5,8,9] contain elements which are not found in any other list.</p> <p>I have created a program which seems to work, but I was wondering if there is a more reliable way to get unique values.</p> <pre><code>viablepath=[[1,2,3,4],[1,3,6,7],[5,8,9]] unique=[] flattenedpath=[] for element in viablepath: if element[0] not in flattenedpath: unique.append(element) if element[0] in flattenedpath: for list in unique: if element[0] in list: unique.remove(list) for item in element: flattenedpath.append(item) print(flattenedpath) print(unique) enter code here </code></pre> <p>This code works by basically flattening the input list of lists and appending to unique any value that is not found in list of lists to unique.</p> <p>i have no idea if that is a reliable strategy if im working with larger data sets which includes around 50 lists within a single list.</p>
[ { "answer_id": 74568502, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 1, "selected": false, "text": "collections.Counter itertools.chain.from_iterable from collections import Counter\nfrom itertools import chain\n\nlists = [[1, 2, 3, 4], [1, 3, 6, 7], [5, 8, 9]]\ncounts = Counter(chain.from_iterable(lists))\n\nunique = [\n element\n for element in lists\n if all(counts[e] == 1 for e in element)\n]\n\nprint(unique)\n# [[5, 8, 9]]\n" }, { "answer_id": 74568599, "author": "Ali Al Hadi", "author_id": 20596013, "author_profile": "https://Stackoverflow.com/users/20596013", "pm_score": 0, "selected": false, "text": "def is_unique(list_of_numbers,numbers_frequency):\n for number in list_of_numbers:\n if numbers_frequency[number] > 1 :\n return False\n return True\n\ndef find_unique_lists(list_of_lists):\n numbers_frequency = {}\n\n for list_of_numbers in list_of_lists:\n for number in list_of_numbers:\n if number not in numbers_frequency:\n numbers_frequency[number] = 0\n\n numbers_frequency[number] += 1\n\n result = []\n for list_of_numbers in list_of_lists:\n if is_unique(list_of_numbers,numbers_frequency):\n result.append(list_of_numbers)\n\n return result\n\ninput_1 = [ [1,2,3,4],\n [1,3,6,7],\n [5,8,9] ]\nexpected_output1 = [[5,8,9]]\n\ninput_2 = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\nexpected_output2 = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\ninput_3 = [[10,13,14],\n [10,11,12],\n [8,9,10]]\n\nexpected_output3 = []\n\ninput_4 = [[1,2,3,i] for i in range(100)]\ninput_4.append([100,200,300])\ninput_4.append([101,110,111])\n\nexpected_output4 = [[100,200,300],\n [101,110,111]]\n\nprint(find_unique_lists(input_1) == expected_output1 )\nprint(find_unique_lists(input_2) == expected_output2 )\nprint(find_unique_lists(input_3) == expected_output3 )\nprint(find_unique_lists(input_4) == expected_output4 )\n\n#output\n#True\n#True\n#True\n#True\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19286514/" ]
74,568,430
<p>I have some 2d double-type arrays in my c code and I want to select between them. The solution I have used so far is to create another 2d array and fill it with a for{ for{}}.</p> <pre><code>if (some condition) for() for() temp[i][j]=arr1[i][j]; else if (another condition) for() for() temp[i][j]=arr2[i][j]; ... </code></pre> <p>Now I have tried the following code</p> <pre><code>double (*temp)[4][4]; double arr1[4][4],arr2[4][4]; if (some condition) temp = &amp;arr1; else if (another condition) temp = &amp;arr2; </code></pre> <p>The problem with the latest code is that it only assigns the first row and other rows seemingly get incorrect addresses. What should I do to correct my code?</p>
[ { "answer_id": 74568510, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": false, "text": "double (*temp)[4][4]; * [][] #include <stdio.h>\n\n#define ROWS 4\n#define COLS 4\n\nint main(void) {\n double (*temp)[ROWS][COLS];\n double arr1[][COLS] = {\n { 1, 1, 1, 1 },\n { 1, 1, 1, 1 },\n { 1, 1, 1, 1 },\n { 1, 1, 1, 1 }\n };\n double arr2[][COLS] = {\n { 2, 2, 2, 2 },\n { 2, 2, 2, 2 },\n { 2, 2, 2, 2 },\n { 2, 2, 2, 2 }\n };\n if (1)\n temp = &arr1;\n else\n temp = &arr2;\n\n (*temp)[1][0] = 3;\n for(size_t r = 0; r < ROWS; r++) {\n for(size_t c = 0; c < COLS; c++) {\n printf(\"%lf%s\", (*temp)[r][c], c + 1 < COLS ? \", \" : \"\\n\");\n }\n }\n}\n 1.000000, 1.000000, 1.000000, 1.000000\n3.000000, 1.000000, 1.000000, 1.000000\n1.000000, 1.000000, 1.000000, 1.000000\n1.000000, 1.000000, 1.000000, 1.000000\n" }, { "answer_id": 74570510, "author": "MFeng", "author_id": 20558711, "author_profile": "https://Stackoverflow.com/users/20558711", "pm_score": 1, "selected": true, "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#define COL_COUNT 4\n\nint main(int argc, const char * argv[]) {\n\n //double (*temp)[4][COL_COUNT];\n double (*temp)[COL_COUNT];// not need \"row\"\n double array1[4][COL_COUNT];\n double array2[4][COL_COUNT];\n \n int i,j;\n int nCount = 0;\n for (i=0; i<4; i++) {//init some data\n for (j=0; j<COL_COUNT; j++) {\n array1[i][j] = nCount;\n nCount++;\n }\n }\n for (i=0; i<4; i++) {//init some data\n for (j=0; j<COL_COUNT; j++) {\n array2[i][j] = nCount;\n nCount++;\n }\n }\n printf(\"array1 = \\n\");\n temp = array1;\n for (i=0; i<4; i++) {//printf the array1 data\n for (j=0; j<COL_COUNT; j++) {\n printf(\"%6.0lf \",temp[i][j]);\n }\n printf(\"\\n\");\n }\n printf(\"array2 = \\n\");\n temp = array2;\n for (i=0; i<4; i++) {//printf the array2 data\n for (j=0; j<COL_COUNT; j++) {\n printf(\"%6.0lf \",temp[i][j]);\n }\n printf(\"\\n\");\n }\n \n return 0;\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14761672/" ]
74,568,469
<p>I have been trying to solve printing down left side star(*) pattern in Javascript using recursion, i think my logic is correct but my syntax and concept might be wrong</p> <pre><code>// * * * * * // * * * * // * * * // * * // * </code></pre> <p>This is my code solution so far</p> <pre><code>var triangle = function (row, col) { if(row == 0){ return } if(col &lt; row){ console.log(&quot;*&quot;) triangle(row, col + 1) }else{ console.log(&quot;\n&quot;) triangle(row - 1, 0) } } triangle(4, 0) </code></pre> <p>output</p> <pre><code>* * * * * * * * * * </code></pre> <p>But i want the output to be</p> <pre><code>* * * * * * * * * * * * * * * </code></pre>
[ { "answer_id": 74568530, "author": "Hao Wu", "author_id": 10289265, "author_profile": "https://Stackoverflow.com/users/10289265", "pm_score": 1, "selected": false, "text": "console.log() document.write var triangle = function (row, col) {\n if(row == 0){\n return\n }\n if(col < row){\n document.write(\"*\")\n triangle(row, col + 1)\n }else{\n document.write(\"<br/>\")\n triangle(row - 1, 0)\n }\n}\ntriangle(4, 0) console.log() var triangle = function (row, col, stream = '') {\n if(row == 0){\n return\n }\n if(col < row){\n stream += '*'\n triangle(row, col + 1, stream)\n }else{\n console.log(stream)\n stream = ''\n triangle(row - 1, 0, stream)\n }\n}\ntriangle(4, 0)" }, { "answer_id": 74568542, "author": "Maulik", "author_id": 20581202, "author_profile": "https://Stackoverflow.com/users/20581202", "pm_score": 0, "selected": false, "text": " function triangle(row){\n var print=\"\";\n if(row==0){\n return;\n }\n for(var i=0;i<row;i++){\n print+=\"* \"\n }\n console.log(print);\n triangle(row-1);\n \n }\n triangle(5);" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570550/" ]
74,568,506
<p>By running this program on my computer, I'm getting same addresses. I'm for case of <code>array</code> and <code>&amp;array[0]</code> I understand that name of <code>array</code> points to the address of first item in the <code>array</code>. And both of them are same.</p> <p>But I'm <strong><em>unable</em></strong> to understand why name of <code>array</code> and <code>&amp;array</code> points to the same address. What comes in my mind about this is that it will print the address of that pionter in which address of first item in array is stored.</p> <h3>Code</h3> <pre><code>#include &lt;stdio.h&gt; int main() { char arr[3]; printf(&quot;array = %p\n&quot;, arr); printf(&quot;&amp;array[0] = %p\n&quot;, &amp;arr[0]); printf(&quot;&amp;array = %p\n&quot;, &amp;arr); return 0; } </code></pre> <h3>Output</h3> <pre><code>array = 0061FF1D &amp;array[0] = 0061FF1D &amp;array = 0061FF1D </code></pre>
[ { "answer_id": 74568566, "author": "dbush", "author_id": 1687119, "author_profile": "https://Stackoverflow.com/users/1687119", "pm_score": 4, "selected": true, "text": "array sizeof & array &array[0] &array &array[0] char * &array char (*)[3] char" }, { "answer_id": 74569001, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "1 + 2 1.0 + 2.0 printf(\"%p\\n\", arr); printf(\"%p\\n\", &arr); printf(\"%p\\n\", &arr[0]); arr &arr" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15672315/" ]
74,568,521
<p>I want to get the name of all tags of nested tag. here is the code that I tried</p> <pre><code>soup = BeautifulSoup(''' &lt;AlternativeIdentifiers&gt; &lt;NationalLocationCode&gt;513100&lt;/NationalLocationCode&gt; &lt;/AlternativeIdentifiers&gt; &lt;Name&gt;Abbey Wood&lt;/Name&gt; &lt;SixteenCharacterName&gt;ABBEY WOOD.&lt;/SixteenCharacterName&gt; &lt;Address&gt; &lt;com:PostalAddress&gt; &lt;add:A_5LineAddress&gt; &lt;add:Line&gt;Abbey Wood station&lt;/add:Line&gt; &lt;add:Line&gt;Wilton Road&lt;/add:Line&gt; &lt;add:Line&gt;Abbey Wood&lt;/add:Line&gt; &lt;add:Line&gt;Greater London&lt;/add:Line&gt; &lt;add:PostCode&gt;SE2 9RH&lt;/add:PostCode&gt; &lt;/add:A_5LineAddress&gt; &lt;/com:PostalAddress&gt; &lt;/Address&gt; ''', &quot;lxml&quot;) tags = soup.find(&quot;AlternativeIdentifiers&quot;).name print(tags) </code></pre> <p>for example, it will print <strong>AlternativeIdentifiers</strong> but I want the inside tag name too which is <strong>NationalLocationCode</strong>. I tried using the for loop but got the error. Just for more clarification I have tried find_all and then use the for loop to traverse to get the tag name but it will print the entire tag not the tag.name</p>
[ { "answer_id": 74568632, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 1, "selected": true, "text": "find_all from bs4 import BeautifulSoup\n\nsoup = BeautifulSoup('''\n<AlternativeIdentifiers>\n <NationalLocationCode>513100</NationalLocationCode>\n</AlternativeIdentifiers>\n<Name>Abbey Wood</Name>\n<SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName>\n<Address>\n <com:PostalAddress>\n <add:A_5LineAddress>\n <add:Line>Abbey Wood station</add:Line>\n <add:Line>Wilton Road</add:Line>\n <add:Line>Abbey Wood</add:Line>\n <add:Line>Greater London</add:Line>\n <add:PostCode>SE2 9RH</add:PostCode>\n </add:A_5LineAddress>\n </com:PostalAddress>\n</Address>\n ''', \"xml\")\n\nfor tag in tags:\n print(tag.name)\n print(tag.find('NationalLocationCode').name)\n AlternativeIdentifiers\nNationalLocationCode\n" }, { "answer_id": 74568667, "author": "Tushar Mazumdar", "author_id": 4675838, "author_profile": "https://Stackoverflow.com/users/4675838", "pm_score": -1, "selected": false, "text": "print(soup)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17158889/" ]
74,568,573
<p>i want to get rid of if else with lookup or hashmap.</p> <p>currently I am using below code.</p> <pre><code>if min&lt;=60: print('The rating for time is 10') elif 60&lt;min&lt;=120: print('The rating for time is 8.34') elif 120&lt;min&lt;=180: print('The rating for time is 6.68') elif 180&lt;min&lt;=240: print('The rating for time is 5.02') elif 240&lt;min&lt;=300: print('The rating for time is 3.36') else: print('The rating for time is 1.7') </code></pre> <p>Please help me get rid of is else. Thank you</p>
[ { "answer_id": 74568632, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 1, "selected": true, "text": "find_all from bs4 import BeautifulSoup\n\nsoup = BeautifulSoup('''\n<AlternativeIdentifiers>\n <NationalLocationCode>513100</NationalLocationCode>\n</AlternativeIdentifiers>\n<Name>Abbey Wood</Name>\n<SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName>\n<Address>\n <com:PostalAddress>\n <add:A_5LineAddress>\n <add:Line>Abbey Wood station</add:Line>\n <add:Line>Wilton Road</add:Line>\n <add:Line>Abbey Wood</add:Line>\n <add:Line>Greater London</add:Line>\n <add:PostCode>SE2 9RH</add:PostCode>\n </add:A_5LineAddress>\n </com:PostalAddress>\n</Address>\n ''', \"xml\")\n\nfor tag in tags:\n print(tag.name)\n print(tag.find('NationalLocationCode').name)\n AlternativeIdentifiers\nNationalLocationCode\n" }, { "answer_id": 74568667, "author": "Tushar Mazumdar", "author_id": 4675838, "author_profile": "https://Stackoverflow.com/users/4675838", "pm_score": -1, "selected": false, "text": "print(soup)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595723/" ]
74,568,593
<p>I am trying to find files along with the matching password pattern under a given directory on linux using egrep. The pattern found in the files is typically as follows</p> <ol> <li><code>password=value</code></li> <li><code>pwd=value</code></li> <li><code>pass=value</code></li> </ol> <ul> <li><p>A file that is matched can contain atleast one of the above patterns for the password anywhere in the file.</p> </li> <li><p>There can be <strong>one of more spaces</strong> or <strong>none</strong> on either side of the <strong>=</strong> sign.</p> </li> <li><p>The value can either be enclosed in <strong>single</strong> or <strong>double</strong> or <strong>have no quotes</strong> surrounding it.</p> </li> <li><p>The value <strong>cannot</strong> begin with a <strong>curly brace {</strong> or a <strong>single</strong> <strong>ampersand</strong> <strong>&amp;</strong> or <strong><strong>double</strong> ampersand &amp;&amp;</strong></p> </li> </ul> <p>Examples of the patterns that <strong>should be</strong> matched in the files</p> <p><code>password = &quot;test123ABc#&amp;$&quot;</code></p> <p><code>pwd=test123ABc#&amp;$</code></p> <p><code>pwd = 'test123ABc#&amp;$'</code></p> <p><code>pass = 'test123456&amp;'</code></p> <p>Examples of patterns that <strong>should not</strong> be matched in the files</p> <p><code>password=&amp;testpw</code></p> <p><code>pwd = &quot;{test123@#&quot;</code></p> <p><code>password = &quot;&amp;&amp;test123&quot;</code></p> <p><code>pass={test123@</code></p> <p>I currently have this egrep command where i am trying to find the appropriate regex expression to carry out the above task. But the world of regex has just left me confused even though there are resources online. Appreciate any help on this.</p> <p><code>egrep -HRi &quot;&lt;regex expression&gt;&quot; &lt;path to directory&gt;</code></p>
[ { "answer_id": 74570173, "author": "Abhishek G", "author_id": 12071682, "author_profile": "https://Stackoverflow.com/users/12071682", "pm_score": 1, "selected": true, "text": "(password|pwd|pass) *= *+((?=\".*\")\"[^&{][^\\s]*\"|(?='.*')'[^&{][^\\s]*'|(?=[^\"'{&].*)[^\\s]*)$\n (password|pwd|pass) *= *+((?=\".*\")\"[^&{][^\\s]*\"|(?='.*')'[^&{][^\\s]*'|(?=[^\"'{&].*)[^\\s]*)$ (password|pwd|pass) *= *+ = ((?=\".*\")\"[^&{][^\\s]*\"|(?='.*')'[^&{][^\\s]*'|(?=[^\"'{&].*)[^\\s]*)$ (?=\".*\")\"[^&{][^\\s]*\" (?=\".*\") \" \"[^&{][^\\s]*\" & { (?='.*')'[^&{][^\\s]*' (?='.*') ' '[^&{][^\\s]*' & { (?=[^\"'{&].*)[^\\s]* (?=[^\"'{&].*) \" ' { & [^\\s]* $" }, { "answer_id": 74577937, "author": "pchegoor", "author_id": 2417881, "author_profile": "https://Stackoverflow.com/users/2417881", "pm_score": 1, "selected": false, "text": "grep -RiP \"(password|pwd|pass) *= *+((?=\".*\")\\\"[^&{][^\\s]*\\\"|(?='.*')'[^&{][^\\s]*'|(?=[^\\\"'{&].*)[^\\s]*)\" *.txt\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2417881/" ]
74,568,603
<p>I have below sample javascript array object -</p> <pre><code>[ {id:&quot;B1&quot;,name:&quot;Belacost&quot;,group:&quot;Quim&quot;}, {id:&quot;B1&quot;,name:&quot;Medtown&quot;,group:&quot;Bik&quot;}, {id:&quot;B1&quot;,name:&quot;Regkim&quot;,group:&quot;Dum&quot;}, {id:&quot;C1&quot;,name:&quot;CSet&quot;,group:&quot;Core&quot;}, {id:&quot;D1&quot;,name:&quot;Merigo&quot;,group:&quot;Dian&quot;}, {id:&quot;D1&quot;,name:&quot;Chilland&quot;,group:&quot;Ground&quot;}, {id:&quot;N1&quot;,name:&quot;Fiwkow&quot;,group:&quot;Vig&quot;}, ] </code></pre> <p>In this array I want to make id as empty if it repeats.</p> <pre><code>Eg. [ {id:&quot;B1&quot;,name:&quot;Belacost&quot;,group:&quot;Quim&quot;}, //id is here since this is first time {id:&quot;&quot;,name:&quot;Medtown&quot;,group:&quot;Bik&quot;}, //id is blank since we already have B1 {id:&quot;&quot;,name:&quot;Regkim&quot;,group:&quot;Dum&quot;}, {id:&quot;C1&quot;,name:&quot;CSet&quot;,group:&quot;Core&quot;}, {id:&quot;D1&quot;,name:&quot;Merigo&quot;,group:&quot;Dian&quot;}, // id is here since D1 is first time {id:&quot;&quot;,name:&quot;Chilland&quot;,group:&quot;Ground&quot;}, //id is empty since we already have id D1 {id:&quot;N1&quot;,name:&quot;Fiwkow&quot;,group:&quot;Vig&quot;}, ] </code></pre> <p>I tried to achive it through map , but could not find repeat id.</p>
[ { "answer_id": 74568625, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 4, "selected": true, "text": "reduce const list = [ {id:\"B1\",name:\"Belacost\",group:\"Quim\"},\n {id:\"B1\",name:\"Medtown\",group:\"Bik\"},\n {id:\"B1\",name:\"Regkim\",group:\"Dum\"},\n {id:\"C1\",name:\"CSet\",group:\"Core\"},\n {id:\"D1\",name:\"Merigo\",group:\"Dian\"},\n {id:\"D1\",name:\"Chilland\",group:\"Ground\"},\n {id:\"N1\",name:\"Fiwkow\",group:\"Vig\"},\n]\n\n\nconst result = list.reduce((acc, item ) => { \n \n const isExisting = acc.some(i => i.id === item.id)\n \n if(isExisting){\n return [...acc, {...item, id: \"\"}]\n }\n \n return [...acc, item]\n\n}, [])\n\nconsole.log(result)" }, { "answer_id": 74568665, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "Array.map Array.some() let data = [ {id:\"B1\",name:\"Belacost\",group:\"Quim\"},\n {id:\"B1\",name:\"Medtown\",group:\"Bik\"},\n {id:\"B1\",name:\"Regkim\",group:\"Dum\"},\n {id:\"C1\",name:\"CSet\",group:\"Core\"},\n {id:\"D1\",name:\"Merigo\",group:\"Dian\"},\n {id:\"D1\",name:\"Chilland\",group:\"Ground\"},\n {id:\"N1\",name:\"Fiwkow\",group:\"Vig\"},\n]\n\nlet result = data.map((e,i,a) =>{\n let exists = a.slice(0,i).some(d => d.id === e.id)\n e.id = exists? \"\": e.id\n return e\n})\nconsole.log(result)" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536611/" ]
74,568,634
<p>so I was working on this <a href="https://leetcode.com/problems/binary-tree-level-order-traversal/description/" rel="nofollow noreferrer">leet code problem</a>.</p> <p>and here is the solution</p> <pre><code>var levelOrder = function(root) { let q = [root], ans = [] while (q[0]) { let qlen = q.length; let row = []; for (let i = 0; i &lt; qlen; i++) { let curr = q.shift() row.push(curr.val) if (curr.left) q.push(curr.left) if (curr.right) q.push(curr.right) } ans.push(row) } return ans }; </code></pre> <p>However, I am confused about the while loop. Why does it work when it's <code> while (q[0]) {</code> and not when I use <code> while (q.length) {</code></p> <p>it's pretty much the same thing no? could anyone help me understand? Thanks</p>
[ { "answer_id": 74568682, "author": "Jonathan Bernal", "author_id": 20596150, "author_profile": "https://Stackoverflow.com/users/20596150", "pm_score": 2, "selected": false, "text": "while(q[0]) q.shift()" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15453019/" ]
74,568,652
<p>I have a node application which handles JSON files: it reads, parses files and writes new files. And sometimes, by necessary, the files become a massive swarm. First, I think current reading speed looks reasonalbe, but writing speed seems little bit slow.</p> <p>I'd like to improve this processing speed.</p> <p>Before I touch this program, I'd tried multi-threading to my python application first, it does similar tasks but handles image files, and the threading successfully reduced its response time.</p> <p>I wonder if it's okay to use node's <code>worker_thread</code> to get the same effect. Because Node document says</p> <blockquote> <p>They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.</p> </blockquote> <p><a href="https://nodejs.org/api/worker_threads.html" rel="nofollow noreferrer">https://nodejs.org/api/worker_threads.html</a></p> <p>The problem is the truth that I don't know whether the current speed is the fastest which the node environment could show or still enhancable without <code>worker_thread</code>.</p> <p>These are my attempts for imporvemnt: My program reads and writes files one by one from a list of file's paths, with <code>fs-sync</code> functions - <code>readFileSync()</code>, <code>writeFileSync()</code>. First, I thought accessing many files synchronously is not node-ish, so I promisified <code>fs</code> functions(<code>readFile()</code>, <code>writeFile()</code>) and pushed to a list of promise objects. Then I call <code>await Promise.all(promisesList)</code>. But this didn't help at all. Even slower.</p> <p>For the second try, I gave up generating tones of promises, and made a single promise. It kept watching the number of processed files, and call <code>resolve()</code> when the number is equal with the length of total files.</p> <pre class="lang-js prettyprint-override"><code> const waiter = new Promise&lt;boolean&gt;((resolve, rejects) =&gt; { const loop: () =&gt; void = () =&gt; processedCount === fileLen ? resolve(true) : setTimeout(loop); loop(); }); </code></pre> <p>I had only waited this promise, and this was the slowest.</p> <p>Now I think this shows the &quot;asynchronous&quot; does not mean &quot;parallel&quot;. So, am I misunderstanding the document's explanation? And should I use <code>worker_threads</code> to improve the file IO speed in this case? Or is there any better solution? Maybe it could be the answer not to use Node for these kind of process, I'd love to but today is Nov 25th sadly...</p>
[ { "answer_id": 74569079, "author": "Davidsamuel", "author_id": 2918907, "author_profile": "https://Stackoverflow.com/users/2918907", "pm_score": 0, "selected": false, "text": "const fs = require('fs');\nlet sourceFileStream = fs.createReadStream('./file1.json')\nlet destinationFileStream = fs.createWriteStream('./temp/file1.json')\nsourceFileStream.pipe(destinationFileStream)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18340106/" ]
74,568,659
<p>How to change the color of a div tag in HTML with JavaScript code</p>
[ { "answer_id": 74568724, "author": "Mohammad Sultani", "author_id": 12753061, "author_profile": "https://Stackoverflow.com/users/12753061", "pm_score": 0, "selected": false, "text": "// selecting the html element using id\n\nvar div = document.getElementById(\"apple\");\ndiv.style.color = \"red\"; <div id=\"apple\">\n <p>some text</p>\n </div>" }, { "answer_id": 74568755, "author": "Mayank Gupta", "author_id": 17691526, "author_profile": "https://Stackoverflow.com/users/17691526", "pm_score": 2, "selected": true, "text": "<div id=\"myDiv\">\n //your code goes here\n</div>\n<script>\n document.getElementById(\"myDiv\").style.backgroundColor = \"red\";\n</script>\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19460211/" ]
74,568,737
<p>im new in flutter and i have this button error that wont navigate to different pages.</p> <p>so i have a &quot;HomePage&quot; that have a button to navigate to &quot;ReminderHomePage&quot;. but when i try to press it it show this error:</p> <pre><code>══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ The following assertion was thrown while handling a gesture: Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget. When the exception was thrown, this was the stack: C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_packages/flutter/src/widgets/navigator.dart 2554:9 &lt;fn&gt; packages/flutter/src/widgets/navigator.dart 2560:14 of packages/flutter/src/widgets/navigator.dart 2019:34 push packages/medreminder/home_page.dart 42:32 &lt;fn&gt; packages/flutter/src/material/ink_well.dart 1072:21 handleTap packages/flutter/src/gestures/recognizer.dart 253:24 invokeCallback packages/flutter/src/gestures/tap.dart 627:11 handleTapUp packages/flutter/src/gestures/tap.dart 306:5 [_checkUp] packages/flutter/src/gestures/tap.dart 239:7 handlePrimaryPointer packages/flutter/src/gestures/recognizer.dart 615:9 handleEvent packages/flutter/src/gestures/pointer_router.dart 98:12 [_dispatch] packages/flutter/src/gestures/pointer_router.dart 143:9 &lt;fn&gt; C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/linked_hash_map.dart 21:13 forEach packages/flutter/src/gestures/pointer_router.dart 141:17 [_dispatchEventToRoutes] packages/flutter/src/gestures/pointer_router.dart 127:7 route packages/flutter/src/gestures/binding.dart 460:19 handleEvent packages/flutter/src/gestures/binding.dart 440:14 dispatchEvent packages/flutter/src/rendering/binding.dart 337:11 dispatchEvent packages/flutter/src/gestures/binding.dart 395:7 [_handlePointerEventImmediately] packages/flutter/src/gestures/binding.dart 357:5 handlePointerEvent packages/flutter/src/gestures/binding.dart 314:7 [_flushPointerEventQueue] packages/flutter/src/gestures/binding.dart 295:7 [_handlePointerDataPacket] C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 1183:13 invoke1 C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 244:5 invokeOnPointerDataPacket C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 147:39 [_onPointerData] C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 653:20 &lt;fn&gt; C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 594:14 &lt;fn&gt; C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 288:16 loggedHandler C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 179:80 &lt;fn&gt; C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall Handler: &quot;onTap&quot; Recognizer: TapGestureRecognizer#02cb0 ════════════════════════════════════════════════════════════════════════════════════════════════════ </code></pre> <p>i dont know why this error occur and how to fix it, any help would mean so much to me.</p> <p>here is my &quot;HomePage&quot; code</p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_navigation/get_navigation.dart'; import 'Reminder/ui/home_reminder.dart'; import 'Reminder/ui/widgets/button.dart'; void main() { // debugPaintSizeEnabled = true; runApp(const HomePage()); } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Medicine Reminder App'), ), body: Column( children: [ Stack( children: [ Image.asset( 'images/MenuImg.jpg', width: 600, height: 200, fit: BoxFit.cover, ), ], ), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton( child: const Text('Button 1'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; const ReminderHomePage()), ); }, ), ElevatedButton( child: const Text('Button 2'), onPressed: () {}, ), ElevatedButton( child: const Text('Button 3'), onPressed: () {}, ), ], ), ], ), ), ); } } </code></pre> <p>and here is the &quot;ReminderHomePage&quot; that i want to navigate to</p> <pre><code>import 'package:date_picker_timeline/date_picker_timeline.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:medreminder/Reminder/services/notification_services.dart'; import 'package:medreminder/Reminder/services/theme_services.dart'; import 'package:intl/intl.dart'; import 'package:medreminder/Reminder/ui/theme.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/Reminder/ui/widgets/button.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/home_page.dart'; class ReminderHomePage extends StatefulWidget { const ReminderHomePage({super.key}); @override State&lt;ReminderHomePage&gt; createState() =&gt; _ReminderHomePageState(); } class _ReminderHomePageState extends State&lt;ReminderHomePage&gt; { DateTime _selectedDate = DateTime.now(); var notifyHelper; @override void initState() { // TODO: implement initState super.initState(); notifyHelper=NotifyHelper(); notifyHelper.initializeNotification(); } @override Widget build(BuildContext context) { return Scaffold( appBar: _appBar(), backgroundColor: context.theme.backgroundColor, body: Column( children: [ _addTaskBar(), _addDateBar(), ], ), ); } _addDateBar(){ return Container( margin: const EdgeInsets.only(top: 20, left: 20), child: DatePicker( DateTime.now(), height: 100, width: 80, initialSelectedDate: DateTime.now(), selectionColor: Color(0xFFAAB6FB), selectedTextColor: Colors.white, dateTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, color:Colors.grey ), ), dayTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color:Colors.grey ), ), monthTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color:Colors.grey ), ), onDateChange: (date){ _selectedDate=date; }, ), ); } _addTaskBar(){ return Container( margin: const EdgeInsets.only(left: 20, right: 20, top: 5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(DateFormat.yMMMMd().format(DateTime.now()), style: subHeadingStyle, ), Text(&quot;Today&quot;, style: headingStyle, ) ], ), ), MyButton(label: &quot;Add Reminder&quot;, onTap: ()=&gt;Get.to(AddReminderPage())) ], ), ); } _appBar(){ return AppBar( elevation: 0, backgroundColor: context.theme.backgroundColor, leading: GestureDetector( onTap: (){ ThemeService().switchTheme(); notifyHelper.displayNotification( title:&quot;Theme Changed!&quot;, body: Get.isDarkMode?&quot;Activated Light Theme!&quot;:&quot;Activated Dark Theme!&quot; ); notifyHelper.scheduledNotification(); }, child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round, size: 20, color:Get.isDarkMode ? Colors.white:Colors.black ), ), actions: [ CircleAvatar( backgroundImage: AssetImage( &quot;images/profile.png&quot; ), ), // Icon(Icons.person, // size: 20,), SizedBox(width: 20,), ], ); } } </code></pre> <p>thankyou.</p>
[ { "answer_id": 74568782, "author": "Jasmin Sojitra", "author_id": 11557906, "author_profile": "https://Stackoverflow.com/users/11557906", "pm_score": 0, "selected": false, "text": " Navigator.push(\n context,\n MaterialPageRoute(builder: (context) => const ReminderHomePage()),\n );\n" }, { "answer_id": 74568793, "author": "Risheek Mittal", "author_id": 16973338, "author_profile": "https://Stackoverflow.com/users/16973338", "pm_score": 2, "selected": true, "text": "onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Scaffold(\n body: ReminderHomePage()\n ),\n ),\n );\n },\n void main() {\n runApp(const MyApp()); //change the main method to call our root class\n}\n\nclass MyApp extends StatelessWidget { //add a new class on top of your main class\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const HomePage(), //call your old class in that new main class\n );\n }\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const ReminderHomePage(),\n ),\n );\n },\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,568,751
<p>I am facing this issue from yesterday. This is the exact error: Failed to start feature-config: A e2-micro VM instance is currently unavailable in the us-central1-a zone. Alternatively, you can try your request again with a different VM hardware configuration or at a later time. For more information, see the troubleshooting documentation.</p> <p><a href="https://i.stack.imgur.com/yaLJj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yaLJj.png" alt="This is the error that I get:-" /></a></p> <p>I had scheduled Google Compute Engine to TURN on &amp; off at specific time using Instance scheduler but now I am locked out of it. I cannot even create a machine image to deploy on another zone</p>
[ { "answer_id": 74605721, "author": "Ferregina", "author_id": 12265927, "author_profile": "https://Stackoverflow.com/users/12265927", "pm_score": 0, "selected": false, "text": "us-central1" }, { "answer_id": 74605955, "author": "Dharmaraj", "author_id": 13130697, "author_profile": "https://Stackoverflow.com/users/13130697", "pm_score": 0, "selected": false, "text": "us-central1" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337398/" ]
74,568,752
<p>I am trying to set the firstDay in the calendar in TableCalendar to be the first day of the current month. I am not sure how to set it.</p> <p>Here is how it is formated now:</p> <pre><code> TableCalendar( firstDay: DateTime.utc(2022, 11, 01), lastDay: DateTime.utc(2022, 11, 30), focusedDay: DateTime.now(), ), </code></pre> <p>Question how to set the firstDay to the first day of the current month?</p>
[ { "answer_id": 74568873, "author": "Paulo", "author_id": 15649348, "author_profile": "https://Stackoverflow.com/users/15649348", "pm_score": 2, "selected": true, "text": "var date = DateTime.now();\n\nTableCalendar(\n firstDay: DateTime.utc(date.year, date.month, 1),\n lastDay: DateTime.utc(date.year, date.month + 1, 0),\n currentDay: DateTime.utc(date.year, date.month, 1),\n focusedDay: DateTime.utc(date.year, date.month, 1),\n );\n" }, { "answer_id": 74568910, "author": "Irfan Ganatra", "author_id": 18817235, "author_profile": "https://Stackoverflow.com/users/18817235", "pm_score": 0, "selected": false, "text": "lastday = DateTime(date.year, date.month + 1, 0);\n\n " } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13176726/" ]
74,568,765
<p>I have two table, [table a] and [table b]. So basically, I need work_week from [table a] therefore I want to join the columns together, shift_begin_datetime from [table a] and shift_start_datetime from [table b] as both of them have the same data type but they have different name.</p> <pre><code>[table a] [table b] | shift_begin_datetime | work_week | | shift_start_datetime | ........ | | 2002-06-29 07:00:00 | 34 | | 2003-07-29 07:00:00 | ........ | | 2002-06-30 07:00:00 | 35 | | 2003-07-30 07:00:00 | ........ | | 2002-06-31 07:00:00 | 36 | | 2003-07-31 07:00:00 | ........ | </code></pre> <p>I want both of the column to be renamed as shift_start_dt and after combining the result should be something like this.</p> <pre><code>[result] | shift_start_dt | | 2002-06-29 07:00:00 | | 2002-06-30 07:00:00 | | 2002-06-31 07:00:00 | | 2003-07-29 07:00:00 | | 2003-07-30 07:00:00 | | 2003-07-31 07:00:00 | </code></pre> <p>And is it possible to display work_week and ........ (representing the rest of the data)?</p> <pre><code>| shift_start_dt | work_week | null? | | 2002-06-29 07:00:00 | 34 | null? | | 2002-06-30 07:00:00 | 35 | null? | | 2002-06-31 07:00:00 | 36 | ........ | | 2003-07-29 07:00:00 | null? | ........ | | 2003-07-30 07:00:00 | null? | ........ | | 2003-07-31 07:00:00 | null? | ........ | </code></pre> <p>I was also wondering if there is no data for the certain column, will it return as null?</p> <p>I have tried union all for both of the table into a temp table, but I do not know how can I get work_week out of it. But I think union cant allow me to get work_week out of it, therefore, I'm not sure what else solution I can do. Here's what I did:</p> <pre><code>select shift_start_datetime into #datetime from (select distinct shift_begin_datetime as shift_start_datetime from table a union all select distinct shift_start_datetime as shift_start_datetime from table b ) as dt </code></pre>
[ { "answer_id": 74569332, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 0, "selected": false, "text": "CAST select\n shift_begin_datetime as shift_start_dt,\n work_week,\n cast(null as varchar(100)) as b_name,\n cast(null as int) as b_amount\nfrom table_a\nunion all\nselect \n shift_start_datetime as shift_start_dt,\n null as work_week,\n name as b_name,\n amount as b_amount\nfrom table_b\norder by shift_start_dt;\n" }, { "answer_id": 74569435, "author": "user17443931", "author_id": 17443931, "author_profile": "https://Stackoverflow.com/users/17443931", "pm_score": 3, "selected": true, "text": "COALESCE FULL OUTER JOIN SELECT COALESCE(a.shift_begin_datetime, b.shift_start_datetime) AS shift_start_dt,\n a.work_week,\n b.otherFields\nFROM tableA AS a\nFULL OUTER JOIN tableB AS b \nON a.shift_begin_datetime = b.shift_start_datetime\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595724/" ]
74,568,772
<p>Hello I am fairly new to java! I really struggle to solve this error and I can't finde anything on the internet. if I do: <code>long test = (long) (2147483647 + 1);</code> it sets <em>test</em> to an int even though I used long. why?</p> <p>I tryed it using max int value but still it doesn't worked. <code>long test = (long) (Integer.MAX_VALUE + 1);</code></p>
[ { "answer_id": 74569332, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 0, "selected": false, "text": "CAST select\n shift_begin_datetime as shift_start_dt,\n work_week,\n cast(null as varchar(100)) as b_name,\n cast(null as int) as b_amount\nfrom table_a\nunion all\nselect \n shift_start_datetime as shift_start_dt,\n null as work_week,\n name as b_name,\n amount as b_amount\nfrom table_b\norder by shift_start_dt;\n" }, { "answer_id": 74569435, "author": "user17443931", "author_id": 17443931, "author_profile": "https://Stackoverflow.com/users/17443931", "pm_score": 3, "selected": true, "text": "COALESCE FULL OUTER JOIN SELECT COALESCE(a.shift_begin_datetime, b.shift_start_datetime) AS shift_start_dt,\n a.work_week,\n b.otherFields\nFROM tableA AS a\nFULL OUTER JOIN tableB AS b \nON a.shift_begin_datetime = b.shift_start_datetime\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20240448/" ]
74,568,785
<h2>I have a json variable looks like this</h2> <p>json_data=</p> <pre><code>[ { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chini.n@example.com&quot; } ] </code></pre> <p>would like to add aks9100 to the collections <br>expected result should be looks like this <br></p> <pre><code>[ { &quot;authType&quot;: &quot;ldap&quot;, &quot;password&quot;: &quot;&quot;, &quot;permissions&quot;: [ { &quot;collections&quot;: [ &quot;aks9099&quot;, &quot;aks9098&quot;, &quot;aks9100&quot; ], &quot;project&quot;: &quot;Central Project&quot; } ], &quot;role&quot;: &quot;devSecOps&quot;, &quot;username&quot;: &quot;chini.n@example.com&quot; } ] </code></pre> <p>thanks</p>
[ { "answer_id": 74569332, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 0, "selected": false, "text": "CAST select\n shift_begin_datetime as shift_start_dt,\n work_week,\n cast(null as varchar(100)) as b_name,\n cast(null as int) as b_amount\nfrom table_a\nunion all\nselect \n shift_start_datetime as shift_start_dt,\n null as work_week,\n name as b_name,\n amount as b_amount\nfrom table_b\norder by shift_start_dt;\n" }, { "answer_id": 74569435, "author": "user17443931", "author_id": 17443931, "author_profile": "https://Stackoverflow.com/users/17443931", "pm_score": 3, "selected": true, "text": "COALESCE FULL OUTER JOIN SELECT COALESCE(a.shift_begin_datetime, b.shift_start_datetime) AS shift_start_dt,\n a.work_week,\n b.otherFields\nFROM tableA AS a\nFULL OUTER JOIN tableB AS b \nON a.shift_begin_datetime = b.shift_start_datetime\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20252882/" ]
74,568,837
<p>I have a list of dataframes</p> <p>li = [df1, df2,..]</p> <p>All the dataframes in the list have common headers. I am appending the list of dataframes into a single df as follows:</p> <pre><code>path =&quot;...&quot; all_files=glob.glob(path+&quot;*.csv&quot;) all_files li = [] for filename in all_files: df=pd.read_csv(filename,index_col=None,header=None) li.append(df) </code></pre> <p>However, will there be multiple headers after appending the list of dfs into one? If so, How to keep only the first header and remove the rest?</p>
[ { "answer_id": 74569332, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 0, "selected": false, "text": "CAST select\n shift_begin_datetime as shift_start_dt,\n work_week,\n cast(null as varchar(100)) as b_name,\n cast(null as int) as b_amount\nfrom table_a\nunion all\nselect \n shift_start_datetime as shift_start_dt,\n null as work_week,\n name as b_name,\n amount as b_amount\nfrom table_b\norder by shift_start_dt;\n" }, { "answer_id": 74569435, "author": "user17443931", "author_id": 17443931, "author_profile": "https://Stackoverflow.com/users/17443931", "pm_score": 3, "selected": true, "text": "COALESCE FULL OUTER JOIN SELECT COALESCE(a.shift_begin_datetime, b.shift_start_datetime) AS shift_start_dt,\n a.work_week,\n b.otherFields\nFROM tableA AS a\nFULL OUTER JOIN tableB AS b \nON a.shift_begin_datetime = b.shift_start_datetime\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14703852/" ]
74,568,858
<p>i am trying to create a react native project i have 2 android devices 1 is running android 9 and 1 is running android 12 my app is getting is installing and running on device that has android 9 but my app is not running on android 12</p> <p>i get the following error</p> <pre><code>&gt; Task :app:installDebug Installing APK 'app-debug.apk' on '2201117PI - 12' for :app:debug &gt; Task :app:installDebug FAILED Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. </code></pre> <p><a href="https://i.stack.imgur.com/98cup.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/98cup.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/toWCo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/toWCo.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74649105, "author": "Marcos Veloso", "author_id": 13594410, "author_profile": "https://Stackoverflow.com/users/13594410", "pm_score": -1, "selected": false, "text": "android cd android\n .\\gradlew clean\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17814678/" ]
74,568,885
<p>I am working to create automatic Archiving system where i need to automatically sort the files folder wise. I am now able to create the folders automatically by mentioning the names of folder in excel sheet. Now i only need to copy the files with the similar names in that respective folder. E.g. A folder is created with the name &quot;Ashley Davidson&quot;, now all the files which are in one source folder and whose file names are starting with Ashley Davidson should get copy in this folder.</p> <p>Altogether there will be more than 500 folders which will be created and more than 10,000 files which needs to be copied in these folders every week.</p> <p>From the code mentioned below i can create automatic folders. Can anyone help and can provide a code which can copy the files based on similar name in these folders.</p> <p><strong>Important</strong> points are The names of Folders which i will mention in Excel sheet will be constant. however the starting names of <em><strong>Files</strong></em> will be similar but users add other words like date, age, sheet 1, sheet 2 etc. in file names too therefore Maybe List of Partial name concept will probably work here</p> <p>for examples please see print shots.</p> <p><a href="https://i.stack.imgur.com/59Acj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/59Acj.png" alt="Folder Names" /></a></p> <p>and example of file names</p> <p><a href="https://i.stack.imgur.com/vKybD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vKybD.png" alt="File Names" /></a></p> <p>the <strong>code</strong> i have to create automatic folders is mentioned below</p> <pre><code>Sub MakeFolders() Dim sh As Worksheet, lastR As Long, arr, i As Long, rootPath As String Set sh = ActiveSheet lastR = sh.Range(&quot;A&quot; &amp; sh.Rows.Count).End(xlUp).Row arr = sh.Range(&quot;A2:A&quot; &amp; lastR).Value2 rootPath = ThisWorkbook.Path &amp; &quot;\&quot; For i = 1 To UBound(arr) If arr(i, 1) &lt;&gt; &quot;&quot; And noIllegalChars(CStr(arr(i, 1))) Then If Dir(rootPath &amp; arr(i, 1), vbDirectory) = &quot;&quot; Then MkDir rootPath &amp; arr(i, 1) End If Else MsgBox &quot;Illegals characters or empty cell (&quot; &amp; sh.Range(&quot;A&quot; &amp; i + 1).Address &amp; &quot;)...&quot; End If Next i End Sub Function noIllegalChars(x As String) As Boolean Const illCh As String = &quot;*[\/\\&quot;&quot;:\*?]*&quot; If Not x Like illCh Then noIllegalChars = True End Function </code></pre> <p>I will really be thankful</p>
[ { "answer_id": 74649105, "author": "Marcos Veloso", "author_id": 13594410, "author_profile": "https://Stackoverflow.com/users/13594410", "pm_score": -1, "selected": false, "text": "android cd android\n .\\gradlew clean\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20141828/" ]
74,568,889
<p>I updated my android project from compileSdkVersion 31 to compileSdkVersion 33. I have the next code to launch the permissions that I need in the app, but it is not working</p> <pre><code>import android.Manifest import android.app.Activity import android.content.pm.PackageInfo import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import android.os.Build class Permissions(private val activity: Activity, private val permissionList: List&lt;String&gt;, val code: Int) { fun checkPermissions() { if (permissionsGranted() != PackageManager.PERMISSION_GRANTED) { requestPermissions() } } private fun permissionsGranted(): Int { var counter = 0 for (permission in permissionList) { counter += ContextCompat.checkSelfPermission(activity, permission) } return counter } private fun deniedPermission(): String { for (permission in permissionList) { if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_DENIED) return permission } return &quot;&quot; } private fun requestPermissions() { val permission = deniedPermission() if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { } else { ActivityCompat.requestPermissions(activity, permissionList.toTypedArray(), code) } } fun checkPermission(manifest: String): Boolean { val result = ContextCompat.checkSelfPermission(activity, manifest) return result == PackageManager.PERMISSION_GRANTED } fun checkPermissionActivity(state: Boolean, urlPath: String, kind : String){ val showRationale = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) { this.activity.shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE) &amp;&amp; this.activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE) } else { true } if (!showRationale) { return } else { return } } fun getAllPermissions(): List&lt;String&gt; { val granted = ArrayList&lt;String&gt;() val pi = activity.packageManager.getPackageInfo(activity.packageName, PackageManager.GET_PERMISSIONS) for (i in pi.requestedPermissions.indices) { if (pi.requestedPermissionsFlags[i] and PackageInfo.REQUESTED_PERMISSION_GRANTED != 0) { granted.add(pi.requestedPermissions[i]) } } return granted } } </code></pre> <p>The manifest is</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.co.retrofit.app&quot;&gt; &lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt; &lt;application android:name=&quot;.feature.RetrofitApplication&quot; android:allowBackup=&quot;true&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:networkSecurityConfig=&quot;@xml/network_security_config&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/AppTheme&quot; android:usesCleartextTraffic=&quot;true&quot;&gt; &lt;activity android:exported=&quot;true&quot; android:name=&quot;.feature.view.activities.Maintenance&quot; /&gt; &lt;activity android:name=&quot;.feature.view.activities.SplashActivity&quot; android:exported=&quot;true&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=&quot;.feature.view.activities.MainActivity&quot; android:exported=&quot;true&quot;/&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>I call the function when I click in one button</p> <pre><code>@Suppress(&quot;UNUSED_PARAMETER&quot;) private fun addAlbum(view: View){ val permissions = Permissions(this, arrayListOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 23) permissions.checkPermissions() } </code></pre> <p>or</p> <pre><code>@Suppress(&quot;UNUSED_PARAMETER&quot;) private fun addAlbum(view: View){ val permissions = Permissions(this, arrayListOf( Manifest.permission.CAMERA), 23) permissions.checkPermissions() } </code></pre> <p>If I rollback the updated, it is showing the permission that I need, but I need the compile in 33</p> <p><a href="https://i.stack.imgur.com/aqH8n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aqH8n.png" alt="evidence" /></a></p> <p>Now if I only update the compile SDK, it is not showing the popup</p> <p><a href="https://i.stack.imgur.com/Sm42z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sm42z.png" alt="Evidence" /></a></p>
[ { "answer_id": 74649105, "author": "Marcos Veloso", "author_id": 13594410, "author_profile": "https://Stackoverflow.com/users/13594410", "pm_score": -1, "selected": false, "text": "android cd android\n .\\gradlew clean\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7949704/" ]
74,568,890
<p>I have a react app and I want to persist the array of favorites when the page refreshes.</p> <p>The data is set correctly, I can see it in the dev tools. But when i refresh the page, the data is removed. Any ideas why this may be?</p> <p>Link to sandbox - <a href="https://codesandbox.io/s/sad-surf-sqgo0q?file=/src/App.js:368-378" rel="nofollow noreferrer">https://codesandbox.io/s/sad-surf-sqgo0q?file=/src/App.js:368-378</a></p> <pre><code>const App = () =&gt; { const [favourites, setFavourites] = useState([]); useEffect(() =&gt; { localStorage.setItem(&quot;favourites&quot;, JSON.stringify(favourites)); }, [favourites]); useEffect(() =&gt; { const favourites = JSON.parse(localStorage.getItem(&quot;favourites&quot;)); if (favourites) { setFavourites(favourites); } }, []); return ( &lt;FavContext.Provider value={{ favourites, setFavourites }}&gt; &lt;HashRouter&gt; &lt;Routes&gt; &lt;Route path={&quot;/&quot;} element={&lt;Dashboard /&gt;} /&gt; &lt;Route path={&quot;/favorites&quot;} element={&lt;Favorites /&gt;} /&gt; &lt;/Routes&gt; &lt;/HashRouter&gt; &lt;/FavContext.Provider&gt; ); }; export default App; </code></pre>
[ { "answer_id": 74649105, "author": "Marcos Veloso", "author_id": 13594410, "author_profile": "https://Stackoverflow.com/users/13594410", "pm_score": -1, "selected": false, "text": "android cd android\n .\\gradlew clean\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19932692/" ]
74,568,896
<p>I have this code to showing value from database as well as checking the checkbox that have the value :</p> <pre><code>&lt;?php $result = mysqli_query($kon,&quot;SELECT jenis FROM pasien WHERE nopemeriksaan = $nopemeriksaan&quot;); while($row = mysqli_fetch_array($result)) { $jenis = explode(&quot;,&quot;, $row['jenis']); print_r($jenis); ?&gt; &lt;input type=&quot;checkbox&quot; id=&quot;checkup&quot; name=&quot;jenis[]&quot; value=&quot;checkup&quot; &lt;?php if(in_array(&quot;checkup&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Check-Up&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;vaksinasi&quot; name=&quot;jenis[]&quot; value=&quot;vaksinasi&quot; &lt;?php if(in_array(&quot;vaksinasi&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Vaksinasi&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;usg&quot; name=&quot;jenis[]&quot; value=&quot;usg&quot; &lt;?php if(in_array(&quot;usg&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&quot;&gt; USG &lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;xray&quot; name=&quot;jenis[]&quot; value=&quot;xray&quot; &lt;?php if(in_array(&quot;xray&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; X-Ray &lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;sterilisasi&quot; name=&quot;jenis[]&quot; value=&quot;sterilisasi&quot; &lt;?php if(in_array(&quot;sterilisasi&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Sterilisasi&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;operasi&quot; name=&quot;jenis[]&quot; value=&quot;operasi&quot; &lt;?php if(in_array(&quot;operasi&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Tindakan Operasi&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;cekdarah&quot; name=&quot;jenis[]&quot; value=&quot;cekdarah&quot; &lt;?php if(in_array(&quot;cekdarah&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Cek Darah&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;lainnya&quot; name=&quot;jenis[]&quot; value=&quot;lainnya&quot; &lt;?php if(in_array(&quot;lainnya&quot;,$jenis)) echo 'checked=&quot;checked&quot;'; ?&gt;&gt; &lt;label&gt; Lainnya&lt;/label&gt;&lt;br&gt; &lt;?php } ?&gt; </code></pre> <p>But however, it always just checking one value even when the array itself has 2 value. Is there anything I write wrong or anything I miss? Thank You very much for your help.</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457503/" ]
74,568,913
<p>From a given list of strings I need to use LINQ to generate a new sequence of strings, where each string consists of the first and last characters of the corresponding string in the original list.</p> <p>Example:</p> <pre><code>stringList: new[] { &quot;ehgrtthrehrehrehre&quot;, &quot;fjjgoerugrjgrehg&quot;, &quot;jgnjirgbrnigeheruwqqeughweirjewew&quot; }, expected: new[] { &quot;ee&quot;, &quot;fg&quot;, &quot;jw&quot; }); </code></pre> <pre><code>list2 = stringList.Select(e =&gt; {e = &quot;&quot; + e[0] + e[e.Length - 1]; return e; }).ToList(); </code></pre> <p>This is what I've tried, it works, but I need to use LINQ to solve the problem and I'm not sure how to adapt my solution.</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569938/" ]
74,568,979
<p>I've recently upgraded a project from using spring-security <code>6.0.0-M6</code> to <code>6.0.0</code>, <a href="https://github.com/au-research/raido-v2/blob/f0b5de3e1c60fcf9450030564263f1bb0c682080/settings.gradle#L19" rel="nofollow noreferrer">gradle config</a> if you want to see it. This project does not use spring-boot.</p> <h1>Context</h1> <p>My <code>securityFilterChain</code> is configured via code and looks approximately like this:</p> <pre class="lang-java prettyprint-override"><code>http. authenticationManager(authnManager). securityContext().securityContextRepository(securityRepo). and(). authorizeRequests(). // &lt;-- DEPRECATED requestMatchers(RAID_V2_API + &quot;/**&quot;).fullyAuthenticated(). </code></pre> <p>The <a href="https://github.com/au-research/raido-v2/blob/f0b5de3e1c60fcf9450030564263f1bb0c682080/api-svc/spring/src/main/java/raido/apisvc/spring/config/RaidWebSecurityConfig.java#L53" rel="nofollow noreferrer">full codebase, starting with the FilterChain config</a>, is publicly available.</p> <p>Note that usage of <code>WebSecurityConfigurerAdapter </code> is <a href="https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter" rel="nofollow noreferrer">deprecated</a>, and I have not been using it since the original usage of <code>6.0.0-M6</code>. So calling stuff like <code>WebSecurityConfigurerAdapter.authenticationManagerBean()</code> won't work.</p> <p>This code works fine, but the call to <code>authorizeRequests()</code> causes a deprecation warning that I want to get rid of.</p> <h1>Problem</h1> <p>The deprecation tag says that I should use <code>authorizeHttpRequests()</code> instead, but when I do that - requests that require authorization (via the <code>fullyAuthenticated()</code> specification above) will be denied with a 403 error.</p> <h1>Analysis</h1> <p>It seems this happens because my <code>AuthenticationProvider</code> instances aren't being called, because the <code>ProviderManager</code> isn't being called. Since the AuthnProviders don't get called, the security context still contains the pre-auth token instead of a verified post-auth token, so the eventual call to <code>AuthorizationStrategy.isGranted()</code> ends up calling <code>isAuthenticated()</code> on the pre-auth token, which (correctly) returns false and the request is denied.</p> <h1>Question</h1> <p>How do I use the <code>authorizeHttpRequests()</code> method but still have the <code>ProviderManager</code> be called so that my security config works?</p> <p>My workaround is just to ignore the deprecation warning.</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/924597/" ]
74,568,981
<p>Is it possible to append a second child into the first appendchild created in a single line of code?</p> <p>Something like this:</p> <pre><code>document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text))); </code></pre> <p>This works fine, but i want to know why it doesn't work the same way in a single line of code.</p> <pre><code> let p = document.createElement('p'); p.appendChild(document.createTextNode('Some Text')); document.body.appendChild(p); </code></pre>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74568981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533111/" ]
74,569,048
<p>How I can scan my array within array if there is equal array element. I want to check if its true or false</p> <pre><code>// the array to be scan const array = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], ] // the new array const newArray = [0, 1, 2] </code></pre>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19172472/" ]
74,569,082
<p>I'm new to macOS development, so pardon my simplistic question. Say, if I have a function. Let's take <code>SCError</code> for example. From the <a href="https://developer.apple.com/documentation/systemconfiguration/1516922-scerror?language=objc" rel="nofollow noreferrer">documentation</a> I can see that I need to add:</p> <blockquote> <p>System Configuration framework</p> </blockquote> <p>But how do I know which header file to add, so that I don't get <code>Use of undeclared identifier 'SCError</code>'?</p> <p>PS. I'll give an example of a documentation that doesn't make me ask these questions. Say, <a href="https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror" rel="nofollow noreferrer">GetLastError</a>. It states at the bottom of the page:</p> <pre><code>Header: errhandlingapi.h (include Windows.h) </code></pre> <p>So it's clear for me what to do:</p> <pre><code>#include Windows.h </code></pre> <p>So what am I missing with the Apple documentation?</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843732/" ]
74,569,097
<p>Trying to create an archive to make a release apk of my app, and whenever I click archive all, it instantly says the archive is completed, nothing shows in the archive manager, and there are no errors or absolutely anything for that matter shown for output.</p> <p>I suspect it may have something to do with the versions as I was able to archive previously, but once I changed versions, I believe that is when the issue started. Also, the app builds and runs with no issue.</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11366868/" ]
74,569,100
<p>I am working on an already existing webpage and want to resize some elements using CSS media queries like width but i only have access to the script file, is there a way to do this without injecting CSS in my js file?</p> <p>As of now i've tried injecting my css file line by line in my js file</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12766362/" ]
74,569,126
<p>I have a function in my shell script that takes options. It works fine, until I try to pass '-n' option, then the function cannot read the arg.</p> <pre class="lang-bash prettyprint-override"><code>func () { for arg in &quot;$@&quot; do echo $arg done } func -p #works func -e #works func -n #doesn't work, func cannot read arg </code></pre> <p>Anyone has an idea of why this is happening?</p> <p>Tried: passing multiple options to the function, they all work, except '-n'. Expect: read '-n' as an argument in my function.</p>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20330157/" ]
74,569,129
<p>I am currently building a data visualization for a class using Vega and I would like to be able to print the data so I can see my transform results for debugging purposes. I have had no problem with this when the data is in JSON format but for whatever reason when the data is in CSV format the method returns null. This is the case even when I have a functioning visualization with successfully applied transforms, so I <em>know</em> the data is not null.</p> <p>Example code showing what I am trying to do</p> <pre><code>let spec = { &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega/v5.json&quot;, &quot;data&quot;: [ { &quot;name&quot;: &quot;data&quot;, &quot;url&quot;: &quot;link.csv&quot;, //removed class website link &quot;format&quot;: {&quot;type&quot;: &quot;csv&quot;, &quot;parse&quot;: &quot;auto&quot;} } ] }; let runtime = vega.parse(spec); let view = new vega.View(runtime) .logLevel(vega.Error) .renderer(&quot;svg&quot;) .initialize(&quot;#view&quot;) .hover(); let dd = view.data(&quot;data&quot;); //This method works fine with JSON, but not CSV console.log(dd); </code></pre>
[ { "answer_id": 74569783, "author": "bero", "author_id": 12552428, "author_profile": "https://Stackoverflow.com/users/12552428", "pm_score": 0, "selected": false, "text": "while($row = mysqli_fetch_array($result)) {\n $jenis = explode(\",\", $row['jenis']);\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13161316/" ]
74,569,136
<p>This is the code where I'm calling a function</p> <pre><code>masterCredsResponse.data.forEach((masterCred) =&gt; { // Check Login status masterCredsArray.push({ master: masterCred.parent, loginCheck: Promise.resolve(getSessionID()()) }) }) </code></pre> <p>Here I get</p> <pre><code>loginCheck: Promise { &lt;pending&gt; } </code></pre> <p>I'm seeing a lot of questions on this topic but unable to understand how to get it done. When I don't use loop but call it separately then it works like</p> <pre><code>let loginCheckReponse = await getSessionID()() </code></pre> <p>But i use this method in a loop that doesn't work</p> <pre><code>loginCheck: await getSessionID()() // Doesn't work </code></pre>
[ { "answer_id": 74569274, "author": "Jake Fried", "author_id": 4032930, "author_profile": "https://Stackoverflow.com/users/4032930", "pm_score": 2, "selected": false, "text": "Promise.resolve await forEach async await masterCredsResponse.data.forEach(async (masterCred) => {\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: Promise.resolve(getSessionID())\n })\n})\n map Promise.all const masterCredPromises = masterCredsResponse.data.map(\n async (masterCred) => ({\n master: masterCred.parent, \n loginCheck: await getSessionId()\n })\n);\nconst masterCredsArray = await Promise.all(masterCredPromises);\n" }, { "answer_id": 74569300, "author": "Rajan Karmaker", "author_id": 10658252, "author_profile": "https://Stackoverflow.com/users/10658252", "pm_score": 1, "selected": false, "text": "masterCredsResponse.data.forEach( async (masterCred) => {\n let loginCheckReponse = await getSessionID()()\n // Check Login status\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: loginCheckReponse\n })\n})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734367/" ]
74,569,148
<p>I'm new to stack overflow and new to dev.. and have been teaching myself to code using react and Express... so, apologies if this question is foundationally in-plausiable.. I have fundamental gaps in my knowledge :)</p> <p>I have a bunch (25 + likely to grow) collections in a mongoDB, and each collection has a mongoose defined schema that is unique to each collection.</p> <p>The Express API end points are below, with the suffix correlating with the colection:</p> <ul> <li>https://localhost:5030/mySchema/...</li> <li>https://localhost:5030/myShema2/... -.... etc</li> </ul> <p>I'm currently refactoring the code to strip out the control and route code. I had the logic appended after the verb in teh route path - which works, but is messy and cumbersome, and limits re-use + is a pain to debug and update, so I'm spliting out the controller logic.</p> <p>For each collection / API endpoint, I have common URLs / API functions applied to each route:</p> <ul> <li>getAll</li> <li>findByName</li> <li>sumamry (filtering out attributes I don't want to display)</li> <li>etc</li> </ul> <p>If we use the following example code:</p> <pre><code>const mySchema = require('../models/mySchema'), const mySchema1 = require('../models/mySchema1'), const mySchema2 = require('../models/mySchema2'), const mySchema3 = require('../models/mySchema3'), const mySchema4 = require('../models/mySchema4'), const mySchema5 = require('../models/mySchema5'), const mySchema6 = require('../models/mySchema6'), const getAll = (req, res) =&gt; { console.log('Request made to Fetch assets data') try { mySchema.find() then((resultsFound) =&gt; res.json(resultsFound)) console.log('Results Found are', resultsFound) } catch (error) { next(err) //In-Built Express error Handling } } </code></pre> <p>Is there a way of variabilising the schema name so this controller code can be applicable across the schema definitions for mySchema, myschema1, mySchema2 etc...</p> <p>I've really only tried manually templating the config.</p> <p>A hack way I thought of to achieve this is to strip out the suffix of the URL from the request, and set that as a variable... but that has a limited use-case it solves only those instances where the schema definition resides in the identical place in the URL.</p> <p>Is there a more extensible way using things I don't know, and probably won't understand taht would achieve this dynamic scheam attribution in a controller?</p>
[ { "answer_id": 74569274, "author": "Jake Fried", "author_id": 4032930, "author_profile": "https://Stackoverflow.com/users/4032930", "pm_score": 2, "selected": false, "text": "Promise.resolve await forEach async await masterCredsResponse.data.forEach(async (masterCred) => {\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: Promise.resolve(getSessionID())\n })\n})\n map Promise.all const masterCredPromises = masterCredsResponse.data.map(\n async (masterCred) => ({\n master: masterCred.parent, \n loginCheck: await getSessionId()\n })\n);\nconst masterCredsArray = await Promise.all(masterCredPromises);\n" }, { "answer_id": 74569300, "author": "Rajan Karmaker", "author_id": 10658252, "author_profile": "https://Stackoverflow.com/users/10658252", "pm_score": 1, "selected": false, "text": "masterCredsResponse.data.forEach( async (masterCred) => {\n let loginCheckReponse = await getSessionID()()\n // Check Login status\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: loginCheckReponse\n })\n})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20596595/" ]
74,569,169
<p>I have one active subscription. Now I want to add new subscription item to that subscription but that on free trial while other items on that subscription are active.</p> <p>How do I achieve this thing.</p> <p>I read the documentation where we can set <code>trail_end</code> for subscription but there is no field for subscription item.</p> <p>Any help must be appreciated.</p> <p>In stripe panel in that plan I have added trial period but than also in invoice it deduct the price.</p>
[ { "answer_id": 74569274, "author": "Jake Fried", "author_id": 4032930, "author_profile": "https://Stackoverflow.com/users/4032930", "pm_score": 2, "selected": false, "text": "Promise.resolve await forEach async await masterCredsResponse.data.forEach(async (masterCred) => {\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: Promise.resolve(getSessionID())\n })\n})\n map Promise.all const masterCredPromises = masterCredsResponse.data.map(\n async (masterCred) => ({\n master: masterCred.parent, \n loginCheck: await getSessionId()\n })\n);\nconst masterCredsArray = await Promise.all(masterCredPromises);\n" }, { "answer_id": 74569300, "author": "Rajan Karmaker", "author_id": 10658252, "author_profile": "https://Stackoverflow.com/users/10658252", "pm_score": 1, "selected": false, "text": "masterCredsResponse.data.forEach( async (masterCred) => {\n let loginCheckReponse = await getSessionID()()\n // Check Login status\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: loginCheckReponse\n })\n})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16685135/" ]
74,569,171
<p>I want to convert this Json to list in c#.</p> <p>Here's my JSON string and class</p> <pre><code>{&quot;Headers&quot;:[{&quot;KeyValue&quot;:&quot;Hello AA&quot;},{&quot;KeyValue&quot;:&quot;Hello BB&quot;}],&quot;Footers&quot;:[{&quot;KeyValue&quot;:&quot;Wifi Password : 11112222&quot;}]} </code></pre> <pre><code>public class Template { public List&lt;HeaderInfo&gt; Headers { get; set; } public List&lt;FooterInfo&gt; Footers { get; set; } } public class HeaderInfo { public string KeyValue { get;set; } } public class FooterInfo { public string KeyValue { get; set; } } </code></pre> <p>Deserialize:</p> <pre><code>lstData = JsonConvert.DeserializeObject&lt;List&lt;Template&gt;&gt;(templateData.ToString()); </code></pre> <p>When I try convert it , it shows this problem:</p> <blockquote> <p>Cannot deserialize the current JSON object (e.g. <code>{&quot;name&quot;:&quot;value&quot;}</code>) into type <code>System.Collections.Generic.List&lt;DXClass.Model.Template&gt;</code> because the type requires a JSON array (e.g. <code>[1,2,3]</code>) to deserialize correctly.</p> </blockquote> <p>To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'Headers', line 1, position 11.'</p>
[ { "answer_id": 74569274, "author": "Jake Fried", "author_id": 4032930, "author_profile": "https://Stackoverflow.com/users/4032930", "pm_score": 2, "selected": false, "text": "Promise.resolve await forEach async await masterCredsResponse.data.forEach(async (masterCred) => {\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: Promise.resolve(getSessionID())\n })\n})\n map Promise.all const masterCredPromises = masterCredsResponse.data.map(\n async (masterCred) => ({\n master: masterCred.parent, \n loginCheck: await getSessionId()\n })\n);\nconst masterCredsArray = await Promise.all(masterCredPromises);\n" }, { "answer_id": 74569300, "author": "Rajan Karmaker", "author_id": 10658252, "author_profile": "https://Stackoverflow.com/users/10658252", "pm_score": 1, "selected": false, "text": "masterCredsResponse.data.forEach( async (masterCred) => {\n let loginCheckReponse = await getSessionID()()\n // Check Login status\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: loginCheckReponse\n })\n})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18177344/" ]
74,569,207
<p>I have checked the official doc and realised we cannot directly use Hooks inside the class-based component. So, I have tried the HOC method to use react-hook-form with a class-based component.</p> <p>But this case is also not working in my case.</p> <p>My HOC Component::</p> <pre><code>import React from &quot;react&quot;; import { useForm } from &quot;react-hook-form&quot; export const ClassHookFormWrap = (Component) =&gt; { const form = useForm(); console.log(&quot;form&quot;, form, Component) return (props) =&gt; { return &lt;Component form={form} {...props} /&gt;; }; }; </code></pre> <p>My class-based component::</p> <pre><code>import React from &quot;react&quot;; import { ClassHookFormWrap } from &quot;./ClassHookFormWrap&quot;; class ClassHookForm extends React.Component { onSubmit = (data) =&gt; { console.log(data); } render(){ console.log(&quot;this.props&quot;, this.props) return( &lt;div&gt;Form&lt;/div&gt; ) } } export default ClassHookFormWrap(ClassHookForm); </code></pre> <p>The error I got inside console::</p> <p><a href="https://i.stack.imgur.com/n180k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n180k.jpg" alt="enter image description here" /></a></p> <p>This is a sandbox link I have added a code sample here:: <a href="https://codesandbox.io/s/old-monad-7mkxg8?file=/src/App.js:224-237" rel="nofollow noreferrer">https://codesandbox.io/s/old-monad-7mkxg8?file=/src/App.js:224-237</a></p> <p>Is there any way to use this form inside a class-based component?</p>
[ { "answer_id": 74569274, "author": "Jake Fried", "author_id": 4032930, "author_profile": "https://Stackoverflow.com/users/4032930", "pm_score": 2, "selected": false, "text": "Promise.resolve await forEach async await masterCredsResponse.data.forEach(async (masterCred) => {\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: Promise.resolve(getSessionID())\n })\n})\n map Promise.all const masterCredPromises = masterCredsResponse.data.map(\n async (masterCred) => ({\n master: masterCred.parent, \n loginCheck: await getSessionId()\n })\n);\nconst masterCredsArray = await Promise.all(masterCredPromises);\n" }, { "answer_id": 74569300, "author": "Rajan Karmaker", "author_id": 10658252, "author_profile": "https://Stackoverflow.com/users/10658252", "pm_score": 1, "selected": false, "text": "masterCredsResponse.data.forEach( async (masterCred) => {\n let loginCheckReponse = await getSessionID()()\n // Check Login status\n masterCredsArray.push({\n master: masterCred.parent,\n loginCheck: loginCheckReponse\n })\n})\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6487762/" ]
74,569,226
<p>I am using groovy to execute a set of groovy scripts, which works fine when the runtime jar is deployed with the webapp and the runtime executes the groovy scripts present under C:\jboss-eap-7.4\bin (java working directory). Due to portability and other constraints now we need to move these groovy scripts as part of the runtime jar and then load and execute these scripts from the class path.</p> <p>Can anyone help in running the groovy scripts present inside the runtime jar file (within the webapp)?</p> <p><a href="https://i.stack.imgur.com/ybsas.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybsas.png" alt="enter image description here" /></a></p> <p>The current implementation that executes the groovy scripts from C:\jboss-eap-7.4\bin (java working directory)</p> <p>** Updated after aswer given by GPT-3**</p> <pre><code>final String PLUGIN_DESCRIPTOR = &quot;Plugins.groovy&quot; final class PluginBootStrapper { private GroovyScriptEngine scriptEngine = null; private GroovyShell shell; private GroovyClassLoader classLoader = null; private final boolean loadFromClasspath; private final List&lt;Plugin&gt; allPlugins = null; private static final Logger logger = LogManager.getLogger(PluginBootStrapper.class); public PluginBootStrapper() { System.out.println(&quot;Inside PluginBootStrapper&quot;) logger.info(&quot;Inside PluginBootStrapper&quot;) String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir)//&quot;.\\plugins&quot;//System.getProperty(CSMProperties.endorsed_plugins_dir) loadFromClasspath = true shell = new GroovyShell(); //scriptEngine = new GroovyScriptEngine(CommonUtils.getAllDirectories(pluginsDir)) logger.info &quot;Plugins Directory:&quot;+pluginsDir println &quot;Plugins Directory:&quot;+pluginsDir allPlugins = loadDescriptor().invokeMethod(&quot;getAllPlugins&quot;, null) } private Object loadDescriptor() { Object pluginDescriptor = bootStrapScript(CSMProperties.get(CSMProperties.PLUGIN_DESCRIPTOR)) pluginDescriptor } Object bootStrapScript(String script) { String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir) if (pluginsDir != null) { script = pluginsDir + script } printClassPath(this.class.getClassLoader()) Object pluginScript = null //logger.info &quot;script: &quot;+ script //String path = this.getClass().getClassLoader().getResource(script).toExternalForm() //logger.info &quot;bootStrapScript script &quot;+ script logger.info &quot;bootStrapScript script: &quot;+ script + &quot;, path: &quot;+ new File(script).absolutePath println &quot;bootStrapScript script: &quot;+ script + &quot;, path: &quot;+ new File(script).absolutePath if (this.loadFromClasspath) { pluginScript = new GroovyShell(this.class.getClassLoader()).evaluate(new File(script)); //&lt;-- Line no:60 /* classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); pluginScript = classLoader.parseClass(new File(script)); */ return pluginScript } else { pluginScript = scriptEngine.loadScriptByName(script).newInstance() return pluginScript } return pluginScript } public List&lt;Plugin&gt; getAllPlugins() { return allPlugins } def printClassPath(classLoader) { println &quot;$classLoader&quot; classLoader.getURLs().each {url-&gt; println &quot;- ${url.toString()}&quot; } if (classLoader.parent) { printClassPath(classLoader.parent) } } } </code></pre> <p>CommonUtils.getAllDirectories method</p> <pre><code>public static String[] getAllDirectories(String directory) { logger.info(&quot;Inside CommonUtils&quot;+directory) def dir = new File(directory) def dirListing = [] if (dir.exists()) { logger.info &quot;Looking for plugins in &quot;+dir.absolutePath+&quot; directory.&quot; dir.eachFileRecurse {file-&gt; if(file.isDirectory()) { dirListing &lt;&lt; file.getPath() logger.info &quot;Using &quot;+file.getPath()+&quot; plugin folder.&quot; } else { logger.info &quot;Using &quot;+file.getPath()+&quot; plugin file.&quot; } } } else { logger.error directory+&quot; folder does not exist. Please provide the plugin files.&quot; } dirListing.toArray() as String [] } </code></pre> <p>Test Run Command: <code>java -cp runtime-2.0-jar-with-dependencies.jar;.runtime-2.0-jar-with-dependencies.jar; -Dendorsed_plugins_dir=runtime-2.0-jar-with-dependencies.jar\ com.Main %*</code></p> <p>Output <a href="https://i.stack.imgur.com/eW2nw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eW2nw.png" alt="enter image description here" /></a></p> <p>** Old Update**</p> <p>At present with the above code, if I place the plugins folder (groovy script) inside the jar, it says it cannot find Plugins.groovy under <code>C:\jboss-eap-7.4\bin</code> folder</p> <p>Screenshot of jar inside war file <code>C:\Users\ricky\Desktop\siperian-mrm.ear\mysupport.war\WEB-INF\lib\runtime.jar\</code> <a href="https://i.stack.imgur.com/8nggu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8nggu.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74606781, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "GroovyClassLoader classLoader = new GroovyClassLoader();\nClass scriptClass = classLoader.parseClass(new File(\"path/to/script.groovy\"));\nObject scriptInstance = scriptClass.newInstance();\n GroovyShell shell = new GroovyShell();\nObject scriptResult = shell.evaluate(new File(\"path/to/script.groovy\"));\n" }, { "answer_id": 74659750, "author": "daggett", "author_id": 1276664, "author_profile": "https://Stackoverflow.com/users/1276664", "pm_score": 1, "selected": false, "text": "plugins.jar /a/b/C.groovy def f(x){\n println \"${this.getClass()} :: ${x}\"\n}\n //in this case you don't need plugins.jar to be in classpath\n//you should detect somehow where the plugins.jar is located for current runtime\nURL jar = new URL('jar:file:./plugins.jar!/') //jar url must end with !/\ndef groovyScriptEngine = new GroovyScriptEngine(jar)\ndef C = groovyScriptEngine.loadScriptByName('a/b/C.groovy')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\n//C.groovy must have a `package` header if it's located in /a/b folder: package a.b\ndef C = this.getClass().getClassLoader().loadClass('a.b.C')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\ndef url = this.getClass().getClassLoader().getResource('a/b/C.groovy')\ndef gshell = new GroovyShell()\ndef c = gshell.parse(url.toURI())\nc.f('hello world')\n a/b/C.groovy URL jar = c.getClass().protectionDomain.codeSource.location //you don't need this for option #1\n\nJarURLConnection jarConnection = (JarURLConnection)url.openConnection()\njarConnection.getJarFile().with{jarFile->\n jarFile.entries().each{java.util.jar.JarEntry e->\n println e.getName()\n if(!e.isDirectory()){\n //you can load/run script here instead of printing it\n println '------------------------'\n println jarFile.getInputStream(e).getText()\n println '------------------------'\n }\n }\n}\n" }, { "answer_id": 74671451, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 0, "selected": false, "text": "GroovyClassLoader // Get the classloader for the current thread\nClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n// Create a new GroovyClassLoader using the classloader\nGroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);\n\n// Load the Groovy script from the classpath\nClass groovyClass = groovyClassLoader.parseClass(new File(\"path/in/jar/to/script.groovy\"));\n\n// Create a new instance of the script\nObject groovyObject = groovyClass.newInstance();\n\n// Execute the script\ngroovyObject.run();\n script.groovy" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10966421/" ]
74,569,229
<p>I'm trying to create a combination of concentrations of two chemicals for an experiment. Since I want to see which combination of both is the best I want to create an overview how much I need to add of each at a given concentration. So far I managed to create two pivot_tables/dataframes of each but Im somehow don't get them to merge into one.</p> <p>So I've tried this approach so far:</p> <pre><code>import numpy as np import pandas as pd array_CinA = np.array([0,125,250,500,1000]) array_Aceto = np.array([0,100,200,400,800]) vol_cina = [0, 5, 10, 20, 40] vol_as = [0, 2, 4,8,16] array = np.array(np.meshgrid(array_CinA,array_Aceto)).T.reshape(-1,2) df = pd.DataFrame({&quot;CinnamonicAcid&quot;:array_CinA, &quot;Acetosyringone&quot;:array_Aceto, &quot;VolCinA&quot;: vol_cina, &quot;VolAS&quot;: vol_as}) pivtab = df.pivot_table(index=&quot;CinnamonicAcid&quot;, columns=&quot;Acetosyringone&quot;, values=[&quot;VolCinA&quot;, &quot;VolAS&quot;]) #pivtab.to_excel print(pivtab) </code></pre> <p>Which gives me the following output:</p> <pre class="lang-none prettyprint-override"><code> VolAS VolCinA Acetosyringone 0 100 200 400 800 0 100 200 400 800 CinnamonicAcid 0 0.0 NaN NaN NaN NaN 0.0 NaN NaN NaN NaN 125 NaN 2.0 NaN NaN NaN NaN 5.0 NaN NaN NaN 250 NaN NaN 4.0 NaN NaN NaN NaN 10.0 NaN NaN 500 NaN NaN NaN 8.0 NaN NaN NaN NaN 20.0 NaN 1000 NaN NaN NaN NaN 16.0 NaN NaN NaN NaN 40.0 </code></pre> <p>My desired output would be something like this:</p> <p><img src="https://i.stack.imgur.com/kyvf7.png" alt="Output from Code" /></p>
[ { "answer_id": 74606781, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "GroovyClassLoader classLoader = new GroovyClassLoader();\nClass scriptClass = classLoader.parseClass(new File(\"path/to/script.groovy\"));\nObject scriptInstance = scriptClass.newInstance();\n GroovyShell shell = new GroovyShell();\nObject scriptResult = shell.evaluate(new File(\"path/to/script.groovy\"));\n" }, { "answer_id": 74659750, "author": "daggett", "author_id": 1276664, "author_profile": "https://Stackoverflow.com/users/1276664", "pm_score": 1, "selected": false, "text": "plugins.jar /a/b/C.groovy def f(x){\n println \"${this.getClass()} :: ${x}\"\n}\n //in this case you don't need plugins.jar to be in classpath\n//you should detect somehow where the plugins.jar is located for current runtime\nURL jar = new URL('jar:file:./plugins.jar!/') //jar url must end with !/\ndef groovyScriptEngine = new GroovyScriptEngine(jar)\ndef C = groovyScriptEngine.loadScriptByName('a/b/C.groovy')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\n//C.groovy must have a `package` header if it's located in /a/b folder: package a.b\ndef C = this.getClass().getClassLoader().loadClass('a.b.C')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\ndef url = this.getClass().getClassLoader().getResource('a/b/C.groovy')\ndef gshell = new GroovyShell()\ndef c = gshell.parse(url.toURI())\nc.f('hello world')\n a/b/C.groovy URL jar = c.getClass().protectionDomain.codeSource.location //you don't need this for option #1\n\nJarURLConnection jarConnection = (JarURLConnection)url.openConnection()\njarConnection.getJarFile().with{jarFile->\n jarFile.entries().each{java.util.jar.JarEntry e->\n println e.getName()\n if(!e.isDirectory()){\n //you can load/run script here instead of printing it\n println '------------------------'\n println jarFile.getInputStream(e).getText()\n println '------------------------'\n }\n }\n}\n" }, { "answer_id": 74671451, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 0, "selected": false, "text": "GroovyClassLoader // Get the classloader for the current thread\nClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n// Create a new GroovyClassLoader using the classloader\nGroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);\n\n// Load the Groovy script from the classpath\nClass groovyClass = groovyClassLoader.parseClass(new File(\"path/in/jar/to/script.groovy\"));\n\n// Create a new instance of the script\nObject groovyObject = groovyClass.newInstance();\n\n// Execute the script\ngroovyObject.run();\n script.groovy" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18484775/" ]
74,569,233
<p>I'm trying to set image files to the variable with applescript, like this:</p> <p><code>set targetImg to choose file with prompt &quot;select image&quot; of type {&quot;public.image&quot;} with multiple selections allowed</code></p> <p>With this command, I can set the files with pop-up finder.</p> <p>But I want to set the files automatically and just tell applescript the directory path of the files.</p> <p>How can I do this?</p>
[ { "answer_id": 74606781, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "GroovyClassLoader classLoader = new GroovyClassLoader();\nClass scriptClass = classLoader.parseClass(new File(\"path/to/script.groovy\"));\nObject scriptInstance = scriptClass.newInstance();\n GroovyShell shell = new GroovyShell();\nObject scriptResult = shell.evaluate(new File(\"path/to/script.groovy\"));\n" }, { "answer_id": 74659750, "author": "daggett", "author_id": 1276664, "author_profile": "https://Stackoverflow.com/users/1276664", "pm_score": 1, "selected": false, "text": "plugins.jar /a/b/C.groovy def f(x){\n println \"${this.getClass()} :: ${x}\"\n}\n //in this case you don't need plugins.jar to be in classpath\n//you should detect somehow where the plugins.jar is located for current runtime\nURL jar = new URL('jar:file:./plugins.jar!/') //jar url must end with !/\ndef groovyScriptEngine = new GroovyScriptEngine(jar)\ndef C = groovyScriptEngine.loadScriptByName('a/b/C.groovy')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\n//C.groovy must have a `package` header if it's located in /a/b folder: package a.b\ndef C = this.getClass().getClassLoader().loadClass('a.b.C')\ndef c = C.newInstance()\nc.f('hello world')\n //plugins.jar must be in current classpath\ndef url = this.getClass().getClassLoader().getResource('a/b/C.groovy')\ndef gshell = new GroovyShell()\ndef c = gshell.parse(url.toURI())\nc.f('hello world')\n a/b/C.groovy URL jar = c.getClass().protectionDomain.codeSource.location //you don't need this for option #1\n\nJarURLConnection jarConnection = (JarURLConnection)url.openConnection()\njarConnection.getJarFile().with{jarFile->\n jarFile.entries().each{java.util.jar.JarEntry e->\n println e.getName()\n if(!e.isDirectory()){\n //you can load/run script here instead of printing it\n println '------------------------'\n println jarFile.getInputStream(e).getText()\n println '------------------------'\n }\n }\n}\n" }, { "answer_id": 74671451, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 0, "selected": false, "text": "GroovyClassLoader // Get the classloader for the current thread\nClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n// Create a new GroovyClassLoader using the classloader\nGroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);\n\n// Load the Groovy script from the classpath\nClass groovyClass = groovyClassLoader.parseClass(new File(\"path/in/jar/to/script.groovy\"));\n\n// Create a new instance of the script\nObject groovyObject = groovyClass.newInstance();\n\n// Execute the script\ngroovyObject.run();\n script.groovy" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20594773/" ]
74,569,240
<p>I would like to checkout to <code>dev</code> branch in a merge request pipeline that is opened for merging to <code>dev</code> with some other branch. I am going to check somethings in this job and then continue with some other jobs depending on the success of this one. Is it possible to do such thing or do I always have to work with the branch the pipeline triggered at?</p> <p>I add the related part of the gitlab configuration</p> <pre><code> variables: GIT_STRATEGY: clone checksomething: rules: - if: $CI_PIPELINE_SOURCE == &quot;merge_request_event&quot; &amp;&amp; $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == &quot;dev&quot; - if: $CI_COMMIT_BRANCH &amp;&amp; $CI_OPEN_MERGE_REQUESTS when: never - if: $CI_COMMIT_BRANCH environment: name: development before_script: - git checkout dev script: - !reference [.check-something-on-dev] </code></pre> <p>But I have this error:</p> <pre><code>$ git checkout dev error: pathspec 'dev' did not match any file(s) known to git``` </code></pre>
[ { "answer_id": 74569315, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "git branch -avv origin/dev git checkout git switch checkout" }, { "answer_id": 74602956, "author": "iRestMyCaseYourHonor", "author_id": 2980481, "author_profile": "https://Stackoverflow.com/users/2980481", "pm_score": 2, "selected": true, "text": " before_script:\n - git fetch origin dev\n - git checkout dev\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2980481/" ]
74,569,246
<p>I want to replace a space to underscore, if the space is in between double quotes. Example:</p> <pre><code>given = 'hello &quot;welcome to&quot; python &quot;blog&quot;' expected = 'hello &quot;welcome_to&quot; python &quot;blog&quot;' </code></pre> <p>My actual string is in SQL code and I need to transform it to use underscore for migration purpose.</p> <h3>What I tried</h3> <pre class="lang-py prettyprint-override"><code>import re s = 'hello &quot;welcome to&quot; java 2 &quot;blog&quot;' a = re.sub('(\&quot;[\w\s]+\&quot;)', '_', s) print (a) </code></pre> <p>Also been trying and trying to google but can't find yet.</p> <p>How to do in Python?</p>
[ { "answer_id": 74569335, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 4, "selected": true, "text": "inp = 'hello \"welcome to\" python \"blog\"'\ndata = inp.split('\"')\nfor i, part in enumerate(data[:-1]):\n if i % 2 == 1:\n data[i] = part.replace(' ', '_')\nout = '\"'.join(data)\nprint(out)\n 'hello \"welcome_to\" python \"blog\"'\n '\"'.join(s if i % 2 == 0 else s.replace(' ', '_') for i, s in enumerate(inp.split('\"')))\n '\"'.join(\n s if i % 2 == 0\n else s.replace(' ', '_')\n for i, s in enumerate(inp.split('\"')[:-1])\n)\n" }, { "answer_id": 74577732, "author": "tunsmm", "author_id": 20600716, "author_profile": "https://Stackoverflow.com/users/20600716", "pm_score": 0, "selected": false, "text": "given = 'hello \"welcome to\" python \"blog\"'\ndouble_quote = False\nexpected = ''\nfor c in given:\n if double_quote:\n if c == ' ':\n c = '_'\n elif c == '\"':\n double_quote = False\n elif c == '\"':\n double_quote = True\n expected += c\nprint(expected)\n given = 'hello \"welcome to\" python \"blog\"'\ndouble_quote = False\nexpected = []\nfor c in given:\n if double_quote:\n if c == ' ':\n c = '_'\n elif c == '\"':\n double_quote = False\n elif c == '\"':\n double_quote = True\n expected.append(c)\nexpected = ''.join(expected)\n" }, { "answer_id": 74578370, "author": "kimbo", "author_id": 9638991, "author_profile": "https://Stackoverflow.com/users/9638991", "pm_score": 0, "selected": false, "text": "re.sub() import re\n\npat = re.compile(r'\\\"[^\\\"]+\\\"')\n\ndef repl(m):\n return m[0].replace(' ', '_')\n\ninp = 'hello \"welcome to\" python \"blog\"'\nout = re.sub(pat, repl, inp)\nprint(out)\n \\\" [^\\\"]+ \\\" repl()" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619729/" ]
74,569,250
<p>The api changed some of it´s security configurations tonight, but i have been doing server side calls for a few months so i discard this being a problem in the server.</p> <p>This is my configuration in postman</p> <p><a href="https://i.stack.imgur.com/R9z7g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R9z7g.png" alt="API Call works fine" /></a></p> <p>Hello, this is my API Call in JAVA</p> <pre><code>{Authorization=Bearer XXXXXXXXXXXXXXXX, headers={Content-Type=application/json}, params={limit=50, state=published, page=1}, url=https://app.tuotempo.com/api/v3/tt_portal_fiatc_test/catalog} </code></pre> <p>The exception i get in the HTTPRequest from JAVA is</p> <pre><code>{&quot;result&quot;:&quot;ERROR&quot;,&quot;return&quot;:[],&quot;msg&quot;:&quot;ACCESS RIGHT DENIED&quot;,&quot;exception&quot;:&quot;TUOTEMPO_SERVICE_NOT_ALLOWED&quot;,&quot;execution_time&quot;:&quot;&quot;,&quot;debug&quot;:&quot;You need a valid access right for the instance tt_portal_fiatc_test&quot;} </code></pre> <p>What i am missing?</p> <p>EDIT: Additional INFO: the GET call in JAVA</p> <p><a href="https://i.stack.imgur.com/xHRqR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xHRqR.png" alt="Generic GET Method in my Code" /></a></p> <p>EDIT2: Already tried without the &quot;bearer&quot; just with Auth: XXXXX.</p> <pre><code>{Authorization=XXXXXXXXXXXXXXXX, headers={Content-Type=application/json}, params={limit=50, state=published, page=1}, url=https://app.tuotempo.com/api/v3/tt_portal_fiatc_test/catalog} RESPUESTA{headers={content-type=application/json, transfer-encoding=chunked, vary=Accept-Encoding, expires=Thu, 19 Nov 1981 08:52:00 GMT, cache-control=no-cache, pragma=no-cache, set-cookie=lang=es; expires=Sun, 25-Dec-2022 05:31:28 GMT; Max-Age=2592000; path=/; secure; HttpOnly, x-status-code=403, date=Fri, 25 Nov 2022 05:31:28 GMT, connection=close}, status_code=403, reason_phrase=Forbidden, content=[B@241dde53} CONTENT: {&quot;result&quot;:&quot;ERROR&quot;,&quot;return&quot;:[],&quot;msg&quot;:&quot;ACCESS RIGHT DENIED&quot;,&quot;exception&quot;:&quot;TUOTEMPO_SERVICE_NOT_ALLOWED&quot;,&quot;execution_time&quot;:&quot;&quot;,&quot;debug&quot;:&quot;You need a valid access right for the instance tt_portal_fiatc_test&quot;} </code></pre>
[ { "answer_id": 74569834, "author": "Alex Karamfilov", "author_id": 7031148, "author_profile": "https://Stackoverflow.com/users/7031148", "pm_score": 1, "selected": false, "text": "User-Agent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631570/" ]
74,569,252
<p>Please assist me to stop this from removing the &quot;.php&quot; extension in sub directories eg: <code>https://www.example.com/enquire/contactmail</code> instead of: <code>https://www.example.com/enquire/contactmail.php</code></p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d \#####exclude /cp folder#### RewriteCond %{REQUEST_URI} !^/enquire RewriteCond %{REQUEST_FILENAME}\\.php -f RewriteRule ^(.\*)$ $1.php RewriteCond %{THE_REQUEST} ^\[A-Z\]{3,9}\\ /((?!cp)\[^.\]+)\\.php RewriteRule ^/?(.\*)\\.php$ /$1 \[NC,L,QSA,R=301\] RewriteRule ^enquire/(.\*)$ contactmail.php?s=$1 \[NC,L,QSA\] RewriteRule ^enquire/(\[0-9\]+)$ contactmail.php?a=$1 \[NC,L,QSA\] </code></pre>
[ { "answer_id": 74569327, "author": "Saud Ahmad", "author_id": 12752265, "author_profile": "https://Stackoverflow.com/users/12752265", "pm_score": 0, "selected": false, "text": "IndexIgnore * # prevent directory listing\nOrder deny,allow\nAllow from *\n\n# ------------------------------------------\n# Rewrite so that php extentions are not shown\nRewriteEngine on\n\n#.php URL Rewrite\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME}\\.php -f\nRewriteRule ^(.*)$ $1.php\n" }, { "answer_id": 74569940, "author": "arkascha", "author_id": 1248114, "author_profile": "https://Stackoverflow.com/users/1248114", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteBase /\n\nRewriteCond %{REQUEST_FILENAME} !-d\n\n# exception for the /enquire request path\nRewriteRule ^enquire/(\\d+)$ contactmail.php?a=$1 [NC,END,QSA]\nRewriteRule ^enquire/(.*)$ contactmail.php?s=$1 [NC,END,QSA]\n\n# redirect requests that specify a \".php\" extension\nRewriteRule ^(.*)\\.php$ $1 [NC,L,QSA,R=301]\n\n# rewrite requests if a corresponding php file exists\nRewriteCond %{REQUEST_FILENAME}.php -f\nRewriteRule ^ %{REQUEST_URI}.php\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6870075/" ]
74,569,262
<p>Here is a simplified Typescript function:</p> <pre class="lang-js prettyprint-override"><code>function x(y: 1 | 2 | 3) : string { if (y === 1) return &quot;a&quot;; if (y === 2) return &quot;b&quot;; if (y === 3) return &quot;c&quot;; } </code></pre> <p>Typescript checker returns this error:</p> <blockquote> <p>Function lacks ending return statement and return type does not include 'undefined'</p> </blockquote> <p>Still, all cases are covered. I could have written <code>else</code> or just <code>return &quot;c&quot;</code> in the last line, but it could be considered less explicit (in this example it's OK, but consider it could be a more complex function that needs to be more explicit about its particular conditions.</p> <p>Is there a way to tell to typescript I covered all the cases without using <code>else</code> or <code>return &quot;c&quot;</code>?</p>
[ { "answer_id": 74569570, "author": "lpizzinidev", "author_id": 13211263, "author_profile": "https://Stackoverflow.com/users/13211263", "pm_score": 0, "selected": false, "text": "switch function x(y: 1 | 2 | 3) : string {\n switch (y) {\n case 1:\n return \"a\";\n case 2:\n return \"b\";\n case 3: \n return \"c\";\n }\n}\n" }, { "answer_id": 74605768, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 2, "selected": true, "text": "if else switch switch assertNever() never throw assertNever() function assertNever(x: never): never {\n throw new Error(\"Unexpected Value: \" + x);\n}\n function x(y: 1 | 2 | 3): string {\n if (y === 1) return \"a\";\n if (y === 2) return \"b\";\n if (y === 3) return \"c\";\n assertNever(y); // okay\n}\n function x(y: 1 | 2 | 3): string {\n if (y === 1) return \"a\";\n // if (y === 2) return \"b\";\n if (y === 3) return \"c\";\n assertNever(y); // error! Argument of type 'number' is not assignable to parameter of type 'never'\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978690/" ]
74,569,350
<p>I add my codes below. What is my fault, can anyone help me? I want to when SpawnRandomBall function run two times, spawnInternal turn into spawnInternal2. So I create a new variable, called 'check'. The variable increase when SpawnRandomBall function run. I set the variable as a public. In this way I can see that 'check' variable increase or doesn't increase. 'Check' variable is increasing without problem. When the veriable value equal to 3, it must be 'else if' run. But unfortunately it doesn't work.</p> <p>I guess problem is I run my codes in Start() function. But I don't know how can I do properly.</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnManagerX : MonoBehaviour { public GameObject[] ballPrefabs; private float spawnLimitXLeft = 14.5f; private float spawnLimitXRight = 24; private float spawnPosY = 10; private float startDelay = 1.0f; private float spawnInterval = 4.0f; private float spawnInterval2 = 2.0f; public int check; // Start is called before the first frame update void Start() { if (check &lt;= 2) { InvokeRepeating(&quot;SpawnRandomBall&quot;, startDelay, spawnInterval); } else if (check &gt; 2) { InvokeRepeating(&quot;SpawnRandomBall&quot;, startDelay, spawnInterval2); } } // Spawn random ball at random x position at top of play area void SpawnRandomBall () { // Generate random ball index and random spawn position Vector3 spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight)); int ballIndex = Random.Range(0, 3); // instantiate ball at random spawn location Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation); check += 1; } } </code></pre> <p>I want to change SpawnInternal variable into SpawnInternal2</p>
[ { "answer_id": 74569490, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 0, "selected": false, "text": "Start else if else if check SpawnRandomBall // Start is called before the first frame update\nvoid Start()\n{\n InvokeRepeating(\"SpawnRandomBall\", startDelay, spawnInterval2);\n}\n// Spawn random ball at random x position at top of play area\nvoid SpawnRandomBall()\n{\n check++;\n if (check == 1 || check == 3)\n return;\n \n // Generate random ball index and random spawn position\n Vector3 spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));\n int ballIndex = Random.Range(0, 3);\n\n // instantiate ball at random spawn location\n Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);\n}\n" }, { "answer_id": 74570125, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 1, "selected": false, "text": "public class SpawnManagerX : MonoBehaviour\n{\n public GameObject[] ballPrefabs;\n\n private float spawnLimitXLeft = 14.5f;\n private float spawnLimitXRight = 24;\n private float spawnPosY = 10;\n\n private float startDelay = 1.0f;\n private float spawnInterval = 4.0f;\n private float spawnInterval2 = 2.0f;\n public int check;\n\n void Start()\n {\n StartCoroutine ( SpawnRandomBall () );\n }\n\n // Spawn random ball at random x position at top of play area\n IEnumerator SpawnRandomBall ()\n {\n while ( true )\n {\n // yielding here will produce an initial delay when the coroutine is run.\n yield return new WaitForSeconds ( \n (check++ < 2) ? spawnInterval : spawnInterval2 );\n\n // Generate random ball index and random spawn position\n var spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));\n var ballIndex = Random.Range(0, 3);\n\n // instantiate ball at random spawn location\n Instantiate( ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation );\n }\n }\n}\n Start while (true) WaitForSeconds" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20596929/" ]
74,569,378
<p>So I have a code, which scraps names+prices of minerals from 14 pages (so far) and saves it to .txt file. I tried with Page1 first only, then I wanted to add more pages for more data. But then code was grabbing something it should not grab - a random name/string. I didn't expect it to grab that one, but it did, and assigned a wrong price to this! It happens just after a mineral with this &quot;unexpected name&quot; and then whole rest of list has wrong prices. See image below: <a href="https://i.stack.imgur.com/CGUCH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CGUCH.jpg" alt="unexpected data" /></a></p> <p>So as this string is different than any other, further code can't split it and gives error:</p> <pre><code>cutted2 = split2.pop(1) ^^^^^^^^^^^^^ IndexError: pop index out of range </code></pre> <p>I tried to ignore these errors and used one of methods used in different Stackoverflow page:</p> <pre><code>try: cutted2 = split2.pop(1) except IndexError: continue </code></pre> <p>It did work, no errors appeared...But then it was assigning wrong prices to wrong minerals (as I noticed)!!! How can I change code to just IGNORE these &quot;strange&quot; names and just go on with list? Below is whole code, it stops on URL5 as I remember and gives this pop index error:</p> <pre><code>import requests from bs4 import BeautifulSoup import re def collecter(URL): headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36&quot;} soup = BeautifulSoup(requests.get(URL, headers=headers).text, &quot;lxml&quot;) names = [n.getText(strip=True) for n in soup.select(&quot;table tr td font a&quot;)] prices = [ p.getText(strip=True).split(&quot;Price:&quot;)[-1] for p in soup.select(&quot;table tr td font font&quot;) ] names[:] = [&quot; &quot;.join(n.split()) for n in names if not n.startswith(&quot;[&quot;)] prices[:] = [p for p in prices if p] with open(&quot;Minerals.txt&quot;, &quot;a+&quot;, encoding='utf-8') as file: for name, price in zip(names, prices): # print(f&quot;{name}\n{price}&quot;) # print(&quot;-&quot; * 50) filename = str(name)+&quot; &quot;+str(price)+&quot;\n&quot; split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(&quot;: &quot;) try: cutted2 = split2.pop(1) except IndexError: continue two_prices = cutted2+&quot; &quot;+split1.pop(0)+&quot;\n&quot; file.write(two_prices) URL1 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=0&quot; URL2 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=25&quot; URL3 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=50&quot; URL4 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=75&quot; URL5 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=100&quot; URL6 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=125&quot; URL7 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=150&quot; URL8 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=175&quot; URL9 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=200&quot; URL10 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=225&quot; URL11 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=250&quot; URL12 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=275&quot; URL13 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=300&quot; URL14 = &quot;https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First=325&quot; collecter(URL1) collecter(URL2) collecter(URL3) collecter(URL4) collecter(URL5) collecter(URL6) collecter(URL7) collecter(URL8) collecter(URL9) collecter(URL10) collecter(URL11) collecter(URL12) collecter(URL13) collecter(URL14) </code></pre> <p>EDIT: THIS IS FULLY WORKING CODE BELOW, THANKS FOR HELP GUYS!</p> <pre><code>import requests from bs4 import BeautifulSoup import re for URL in range(0,2569,25): headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36&quot;} soup = BeautifulSoup(requests.get(f'https://www.fabreminerals.com/search_results.php?LANG=EN&amp;SearchTerms=&amp;submit=Buscar&amp;MineralSpeciment=&amp;Country=&amp;Locality=&amp;PriceRange=&amp;checkbox=enventa&amp;First={URL}', headers=headers).text, &quot;lxml&quot;) names = [n.getText(strip=True) for n in soup.select(&quot;table tr td font&gt;a&quot;)] prices = [p.getText(strip=True).split(&quot;Price:&quot;)[-1] for p in soup.select(&quot;table tr td font&gt;font&quot;)] names[:] = [&quot; &quot;.join(n.split()) for n in names if not n.startswith(&quot;[&quot;) ] prices[:] = [p for p in prices if p] with open(&quot;MineralsList.txt&quot;, &quot;a+&quot;, encoding='utf-8') as file: for name, price in zip(names, prices): # print(f&quot;{name}\n{price}&quot;) # print(&quot;-&quot; * 50) filename = str(name)+&quot; &quot;+str(price)+&quot;\n&quot; split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(&quot;: &quot;) cutted2 = split2.pop(1) try: two_prices = cutted2+&quot; &quot;+split1.pop(0)+&quot;\n&quot; except IndexError: two_prices = cutted2+&quot;\n&quot; file.write(two_prices) </code></pre> <p>But after some changes it stops on new error - it can't find a string by given properties, so error &quot;IndexError: pop from empty list&quot; appears... Not even <code>soup.select(&quot;table tr td font&gt;font&quot;)</code> helped, like it did in 'names'</p> <p><a href="https://i.stack.imgur.com/NCDma.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NCDma.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74569490, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 0, "selected": false, "text": "Start else if else if check SpawnRandomBall // Start is called before the first frame update\nvoid Start()\n{\n InvokeRepeating(\"SpawnRandomBall\", startDelay, spawnInterval2);\n}\n// Spawn random ball at random x position at top of play area\nvoid SpawnRandomBall()\n{\n check++;\n if (check == 1 || check == 3)\n return;\n \n // Generate random ball index and random spawn position\n Vector3 spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));\n int ballIndex = Random.Range(0, 3);\n\n // instantiate ball at random spawn location\n Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);\n}\n" }, { "answer_id": 74570125, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 1, "selected": false, "text": "public class SpawnManagerX : MonoBehaviour\n{\n public GameObject[] ballPrefabs;\n\n private float spawnLimitXLeft = 14.5f;\n private float spawnLimitXRight = 24;\n private float spawnPosY = 10;\n\n private float startDelay = 1.0f;\n private float spawnInterval = 4.0f;\n private float spawnInterval2 = 2.0f;\n public int check;\n\n void Start()\n {\n StartCoroutine ( SpawnRandomBall () );\n }\n\n // Spawn random ball at random x position at top of play area\n IEnumerator SpawnRandomBall ()\n {\n while ( true )\n {\n // yielding here will produce an initial delay when the coroutine is run.\n yield return new WaitForSeconds ( \n (check++ < 2) ? spawnInterval : spawnInterval2 );\n\n // Generate random ball index and random spawn position\n var spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));\n var ballIndex = Random.Range(0, 3);\n\n // instantiate ball at random spawn location\n Instantiate( ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation );\n }\n }\n}\n Start while (true) WaitForSeconds" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396568/" ]
74,569,385
<p>Say, there are multiple elements and their and multiple child elements. I have selected the parent elements and from the code the I want to select the child elements.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; This is div 1 &lt;p&gt; This is paragraph 1 under div 1. &lt;/p&gt; &lt;/div&gt; &lt;div&gt; This is div 2 &lt;p&gt; This is paragraph 2 under div 2. &lt;/p&gt; &lt;/div&gt; &lt;div&gt; This is div 3 &lt;p&gt; This is paragraph 3 under div 3. &lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here lets say I have the xpaths for the divs. Something like @FindBy(xpath=&quot;(//div)[1]&quot;) Webelement div_1;</p> <p>But I do not define the child element using the Findby tag. I would like to find the child element using the div_1 element in my actual test code itself. How can I do this?</p>
[ { "answer_id": 74569605, "author": "ggeorge", "author_id": 5276946, "author_profile": "https://Stackoverflow.com/users/5276946", "pm_score": 2, "selected": false, "text": "@FindBy(xpath=\"(//div)[1]\")\nWebElement parent;\n\nWebElement child = parent.findElement(By.xpath(\"./p\"));\n" }, { "answer_id": 74569623, "author": "Alex Karamfilov", "author_id": 7031148, "author_profile": "https://Stackoverflow.com/users/7031148", "pm_score": 1, "selected": true, "text": "WebElement div = driver.findElement(By.xpath(\"//div[@class='something']\");\n div.findElement(By.xpath(\"//div\"));\n List<WebElement> subDivs = div.findElements(By.tagName(\"div\"));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12396842/" ]
74,569,391
<p>I am trying to run a simple program that spawns a vim process.</p> <p>The user should be able (when the <code>exec.Command</code> starts) to switch to <code>vim</code> window and the process execution should halt there.</p> <p>When user closes <code>vim</code> (<code>wq!</code>) the program execution should resume from that point.</p> <p>The following simple attempt fails but I cannot figure out why</p> <pre><code>package main import ( &quot;log&quot; &quot;os/exec&quot; ) func main() { cmd := exec.Command(&quot;vim&quot;, &quot;lala&quot;) err := cmd.Run() if err != nil { log.Fatal(err) } } </code></pre> <pre><code>▶ go run main.go 2022/11/25 09:16:44 exit status 1 exit status 1 </code></pre> <p>Why the <code>exit status 1</code>?</p>
[ { "answer_id": 74570060, "author": "jabr", "author_id": 19972197, "author_profile": "https://Stackoverflow.com/users/19972197", "pm_score": 0, "selected": false, "text": "Stdin Stdout cmd package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n\n cmd := exec.Command(\"vim\", \"lala\")\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n err := cmd.Run()\n\n if err != nil {\n log.Fatal(err)\n }\n}\n" }, { "answer_id": 74570069, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 3, "selected": true, "text": "cmd.Stdin = os.Stdin\ncmd.Stdout = os.Stdout\n :wq package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n cmd := exec.Command(\"vim\", \"lala\")\n\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n\n err := cmd.Run()\n if err != nil {\n log.Fatal(err)\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2409793/" ]
74,569,409
<p>I'm working on a fullstack app having spring boot v2.7.5 as backend and Angular v15 as frontend. I use IntelliJ IDEA IDE for development. Locally, springboot runs on http://localhost:8080 and angular runs on http://localhost:4200. I use gradle to build the project a single war file and which would be deployed on external tomcat server.</p> <p>Following is the project structure:</p> <p><a href="https://i.stack.imgur.com/B3aAA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B3aAA.png" alt="enter image description here" /></a></p> <p>I have 3 build.gradle files, 1 for frontend , 1 for backend, and 1 for global. When I run the global build.gradle file, it would call call build.gradle from fronend folder which builds angular project and copies all the build files and put them into <strong>backend/src/main/resources/static</strong> folder. Next, build.gradle from backend gets called which would build final war file to be deployed on external tomcat server.</p> <p>The reason I'm putting frontend build files (index.html, some .js files) into <strong>backend/src/main/resources/static</strong> is the fact that Spring Boot Serves static content from that location. <a href="https://www.baeldung.com/spring-mvc-static-resources#spring-boot" rel="nofollow noreferrer">more details</a> .</p> <p>So the static directory looks like this after adding frontend build files:</p> <p><a href="https://i.stack.imgur.com/yjeKg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yjeKg.png" alt="enter image description here" /></a></p> <p>When I try to access http://localhost:8080, it loads index.html from static folder. <a href="https://i.stack.imgur.com/Ybskt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ybskt.png" alt="enter image description here" /></a></p> <p>So far it is good. When I click login button, internally it calls backend api and move to next page (home page i.e., http://localhost:8080/fe/appInstances).</p> <p><a href="https://i.stack.imgur.com/mVSwY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mVSwY.png" alt="enter image description here" /></a></p> <p>Now if I refresh the page, it gives me the following 404 Whitelabel Error Page. <a href="https://i.stack.imgur.com/I2Tqa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I2Tqa.png" alt="enter image description here" /></a></p> <p>I understand that since this is springboot as it is looking for definition of http://localhost:8080/fe/appInstances api end point in the java code.</p> <p>To fix this, I have created the following IndexController.java class which should redirect all the frontend rest end points to index.html which is present at <strong>main/resources/static</strong> folder.</p> <p><strong>IndexController.java</strong></p> <pre><code>@Controller public class IndexController { @GetMapping(&quot;/&quot;) public String index() { return &quot;redirect:/index&quot;; } @GetMapping(&quot;/fe/*&quot;) public String anyFrontEndApi() { return &quot;index&quot;; } } </code></pre> <p>But now, I get the following Whilelabel error page about <strong>Circular view path [index]: would dispatch back to the current handler URL [/fe/index] again.</strong></p> <p><a href="https://i.stack.imgur.com/Ik71t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ik71t.png" alt="enter image description here" /></a></p> <p>I have tried Changing @Controller to @RestController and changing the return type to ModelandView something like this. But irrespective of all, it is still giving me the Whitelable Error Page about Cicular view path...</p> <pre><code>@RestController public class IndexController { @GetMapping(&quot;/&quot;) public String index() { return &quot;redirect:/index&quot;; } @GetMapping(&quot;/fe/*&quot;) public ModelAndView anyFrontEndApi() { ModelAndView mv = new ModelAndView(); mv.setViewName(&quot;index&quot;); return mv; } } </code></pre> <p>Am I missing something here? Can someone please suggest me a fix for this?</p> <p>PS: @justthink addressed this situation <a href="https://stackoverflow.com/a/67249018/9145082">here</a>. But I don't know how to do reserve proxy way.</p>
[ { "answer_id": 74570060, "author": "jabr", "author_id": 19972197, "author_profile": "https://Stackoverflow.com/users/19972197", "pm_score": 0, "selected": false, "text": "Stdin Stdout cmd package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n\n cmd := exec.Command(\"vim\", \"lala\")\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n err := cmd.Run()\n\n if err != nil {\n log.Fatal(err)\n }\n}\n" }, { "answer_id": 74570069, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 3, "selected": true, "text": "cmd.Stdin = os.Stdin\ncmd.Stdout = os.Stdout\n :wq package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n cmd := exec.Command(\"vim\", \"lala\")\n\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n\n err := cmd.Run()\n if err != nil {\n log.Fatal(err)\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9145082/" ]
74,569,424
<p>I have the following data frame:</p> <pre><code>df &lt;- structure(list( peptide = structure(c( 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L ), levels = c( &quot;P1&quot;, &quot;P2&quot;, &quot;P3&quot;, &quot;P4&quot;, &quot;P5&quot; ), class = &quot;factor&quot;), reaction_time = c( 0, 3, 5, 10, 0, 3, 5, 10, 0, 3, 5, 10, 0, 3, 5, 10, 0, 3, 5, 10 ), mean_residual_quantity = c( 100, 110, 114, 110.5, 100, 91, 84.5, 69.5, 100, 75, 70, 59, 100, 63.5, 58, 43, 100, 44, 28, 12 ) ), class = c(&quot;grouped_df&quot;, &quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -20L), groups = structure(list(peptide = structure(1:5, levels = c( &quot;P1&quot;, &quot;P2&quot;, &quot;P3&quot;, &quot;P4&quot;, &quot;P5&quot; ), class = &quot;factor&quot;), .rows = structure(list( 1:4, 5:8, 9:12, 13:16, 17:20 ), ptype = integer(0), class = c( &quot;vctrs_list_of&quot;, &quot;vctrs_vctr&quot;, &quot;list&quot; ))), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;), row.names = c(NA, -5L), .drop = TRUE)) </code></pre> <p>With this code:</p> <pre><code>ggpubr::ggline(df, x = &quot;reaction_time&quot;, y = &quot;mean_residual_quantity&quot;, color = &quot;peptide&quot;, xlab = &quot;Reaction Time&quot;, palette = &quot;jco&quot;, size = 1, ylab = &quot;Residual Quantity (%)&quot; ) + scale_y_continuous(breaks = get_breaks(n = 10)) + grids() + rremove(&quot;legend.title&quot;) </code></pre> <p>I can create this plot:</p> <p><a href="https://i.stack.imgur.com/9XT8u.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9XT8u.jpg" alt="enter image description here" /></a></p> <p>Visually, we can see that the <em>slope</em> of the graph keeps decreasing from P1 to P5. Is there a single measure I can use to quantify this decreasing trend, for each P1 to P5?</p> <p>So in the end, if we rank that value, the order should be the P1, P2, P3, P4, P5.</p> <p>And how can I implement it with R?</p>
[ { "answer_id": 74570060, "author": "jabr", "author_id": 19972197, "author_profile": "https://Stackoverflow.com/users/19972197", "pm_score": 0, "selected": false, "text": "Stdin Stdout cmd package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n\n cmd := exec.Command(\"vim\", \"lala\")\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n err := cmd.Run()\n\n if err != nil {\n log.Fatal(err)\n }\n}\n" }, { "answer_id": 74570069, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 3, "selected": true, "text": "cmd.Stdin = os.Stdin\ncmd.Stdout = os.Stdout\n :wq package main\n\nimport (\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n cmd := exec.Command(\"vim\", \"lala\")\n\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n\n err := cmd.Run()\n if err != nil {\n log.Fatal(err)\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391698/" ]
74,569,440
<p>I have a two-dimensional <code>char</code> array (an array of strings). When I try to assign a string to an element, an error occurs saying &quot;array type 'char *[8]' is not assignable&quot;.</p> <p>This is my code:</p> <pre><code>int main() { char array[4][8]; array[0] = &quot;test&quot;; } </code></pre> <p>How would I properly assign an element of a 2-D array?</p>
[ { "answer_id": 74569498, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "array[0] char *[8] array[0][0] char * strdup() #include <string.h>\n// ...\nchar *array[4][8];\narray[0][0] = strdup(\"test\");\nfree(array[0][0]);\n const const char *array2[4][8];\narray2[0][0] = \"test\";\n #include <string.h>\n//...\nchar array3[4][8];\nstrcpy(array3[0], \"test\");\n" }, { "answer_id": 74569499, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 0, "selected": false, "text": "array[0][0] = \"test;\" const char *array[4][8];" }, { "answer_id": 74569508, "author": "striker", "author_id": 20596655, "author_profile": "https://Stackoverflow.com/users/20596655", "pm_score": -1, "selected": false, "text": "int main() {\n char *array[4][8];\n array[0][0] = \"test\";\n}\n" }, { "answer_id": 74569586, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 1, "selected": true, "text": "char *array[4][8]; char array[4][8]; // i.e. without *\n = strcpy strcpy(array[0], \"test\");\n = char array[4][8] ={\"test\", \"hello\", \"world\", \"done\"};\n for (int i=0; i < 4; ++i) puts(array[i]);\n test\nhello\nworld\ndone\n printf(\"%c\", array[1][4]);\n o hello" }, { "answer_id": 74569595, "author": "Nicholas", "author_id": 10663879, "author_profile": "https://Stackoverflow.com/users/10663879", "pm_score": 0, "selected": false, "text": "int main() { \n char *array[4][8];\n array[0] = \"test\";\n}\n char* array[0] array[0] char* char* array[0][0] = \"test\";\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17607692/" ]
74,569,449
<p>I was given a macro by a predecessor.</p> <p>I would like to add automatic colouring of the font (white on dark colours, black on light colours).</p> <p>I have no experience with visual basic.</p> <pre class="lang-vb prettyprint-override"><code>Sub colourProgress() Dim c As Word.Cell If Selection.Information(wdWithInTable) Then For Each c In Selection.Tables(1).Range.Cells If IsNumeric(Left(c.Range.Text, Len(c.Range.Text) - 1)) Then If Val(c.Range.Text) = 3 Then c.Shading.BackgroundPatternColor = wdColorYellow ElseIf Val(c.Range.Text) = 4 Then c.Shading.BackgroundPatternColor = wdColorOrange End If ElseIf InStr(LCase(c.Range.Text), &quot;good&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(0, 176, 80) ElseIf InStr(LCase(c.Range.Text), &quot;exceptional&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(148, 55, 257) ElseIf InStr(LCase(c.Range.Text), &quot;satisfactory&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = wdColorYellow ElseIf InStr(LCase(c.Range.Text), &quot;serious&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = wdColorRed ElseIf InStr(LCase(c.Range.Text), &quot;concern&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(255, 192, 0) ElseIf InStr(LCase(c.Range.Text), &quot;three or more sub-levels above target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(148, 55, 257) ElseIf InStr(LCase(c.Range.Text), &quot;two sub-levels above target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = wdColorBrightGreen ElseIf InStr(LCase(c.Range.Text), &quot;one sub-level above target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(0, 176, 80) ElseIf InStr(LCase(c.Range.Text), &quot;on target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = wdColorYellow ElseIf InStr(LCase(c.Range.Text), &quot;one sub-level below target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = RGB(255, 192, 0) ElseIf InStr(LCase(c.Range.Text), &quot;two or more sub-levels below target&quot;) &gt; 0 Then c.Shading.BackgroundPatternColor = wdColorRed ElseIf c.RowIndex &gt; 1 Then ' set non-numeric in row 2 and down to White c.Shading.BackgroundPatternColor = wdColorWhite End If Next c End If End Sub </code></pre> <p>I tried adding</p> <pre><code>c.Font.Color = white </code></pre>
[ { "answer_id": 74569498, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "array[0] char *[8] array[0][0] char * strdup() #include <string.h>\n// ...\nchar *array[4][8];\narray[0][0] = strdup(\"test\");\nfree(array[0][0]);\n const const char *array2[4][8];\narray2[0][0] = \"test\";\n #include <string.h>\n//...\nchar array3[4][8];\nstrcpy(array3[0], \"test\");\n" }, { "answer_id": 74569499, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 0, "selected": false, "text": "array[0][0] = \"test;\" const char *array[4][8];" }, { "answer_id": 74569508, "author": "striker", "author_id": 20596655, "author_profile": "https://Stackoverflow.com/users/20596655", "pm_score": -1, "selected": false, "text": "int main() {\n char *array[4][8];\n array[0][0] = \"test\";\n}\n" }, { "answer_id": 74569586, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 1, "selected": true, "text": "char *array[4][8]; char array[4][8]; // i.e. without *\n = strcpy strcpy(array[0], \"test\");\n = char array[4][8] ={\"test\", \"hello\", \"world\", \"done\"};\n for (int i=0; i < 4; ++i) puts(array[i]);\n test\nhello\nworld\ndone\n printf(\"%c\", array[1][4]);\n o hello" }, { "answer_id": 74569595, "author": "Nicholas", "author_id": 10663879, "author_profile": "https://Stackoverflow.com/users/10663879", "pm_score": 0, "selected": false, "text": "int main() { \n char *array[4][8];\n array[0] = \"test\";\n}\n char* array[0] array[0] char* char* array[0][0] = \"test\";\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20596997/" ]
74,569,452
<p>I am restoring a postgres database via .backup file from one postgres-14 instance to another:</p> <p><code>pg_restore -h localhost -p 5432 -U postgres -d mydatabase -v &quot;mybackupfile.backup&quot;</code></p> <p>The backup fails, complaining about</p> <p><code>pg_restore: error: could not execute query: ERROR: function public.uuid_generate_v1() does not exist </code></p> <p>However, the extension <code>uuid-ossp</code> that contains the respective function is installed on the target system.</p> <p>What can I do about that?</p> <hr /> <p>The statment causing the error:</p> <pre><code>pg_restore: creating TABLE &quot;data.mytable&quot; pg_restore: from TOC entry 215; 1259 155973 TABLE mytable superuser pg_restore: error: could not execute query: ERROR: function public.uuid_generate_v1() does not exist LINE 53: uuid uuid DEFAULT public.uuid_generate_v1(), ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Command was: CREATE TABLE data.mytable ( my_id integer DEFAULT nextval('data.my_id_seq'::regclass) NOT NULL, [...] uuid uuid DEFAULT public.uuid_generate_v1() ); </code></pre>
[ { "answer_id": 74569498, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "array[0] char *[8] array[0][0] char * strdup() #include <string.h>\n// ...\nchar *array[4][8];\narray[0][0] = strdup(\"test\");\nfree(array[0][0]);\n const const char *array2[4][8];\narray2[0][0] = \"test\";\n #include <string.h>\n//...\nchar array3[4][8];\nstrcpy(array3[0], \"test\");\n" }, { "answer_id": 74569499, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 0, "selected": false, "text": "array[0][0] = \"test;\" const char *array[4][8];" }, { "answer_id": 74569508, "author": "striker", "author_id": 20596655, "author_profile": "https://Stackoverflow.com/users/20596655", "pm_score": -1, "selected": false, "text": "int main() {\n char *array[4][8];\n array[0][0] = \"test\";\n}\n" }, { "answer_id": 74569586, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 1, "selected": true, "text": "char *array[4][8]; char array[4][8]; // i.e. without *\n = strcpy strcpy(array[0], \"test\");\n = char array[4][8] ={\"test\", \"hello\", \"world\", \"done\"};\n for (int i=0; i < 4; ++i) puts(array[i]);\n test\nhello\nworld\ndone\n printf(\"%c\", array[1][4]);\n o hello" }, { "answer_id": 74569595, "author": "Nicholas", "author_id": 10663879, "author_profile": "https://Stackoverflow.com/users/10663879", "pm_score": 0, "selected": false, "text": "int main() { \n char *array[4][8];\n array[0] = \"test\";\n}\n char* array[0] array[0] char* char* array[0][0] = \"test\";\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297780/" ]
74,569,456
<p>I have some reports that need to be modified by deleting some specific cells such as blank cells or highlights in the background</p> <p>I have tried to record Macro to delete the special cells. however, the position will be changed regarding the difference of the row numbers. I could not specify the certain position of each cell.</p> <p>Here is my data</p> <p><a href="https://i.stack.imgur.com/bfa8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bfa8A.png" alt="enter image description here" /></a></p> <p>here is what I expect to get</p> <p><a href="https://i.stack.imgur.com/eFmw0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eFmw0.png" alt="enter image description here" /></a></p> <p>Here is my recorded Macro</p> <pre><code>Sub Macro1() 'Macro1 Macro Range(&quot;B4&quot;).Select Selection.Delete Shift:=xlToLeft Range(&quot;B16&quot;).Select Selection.Delete Shift:=xlUp Range(&quot;B24&quot;).Select Selection.Delete Shift:=xlToLeft ActiveWindow.SmallScroll Down:=12 Range(&quot;B30&quot;).Select Selection.Delete Shift:=xlToLeft End Sub </code></pre>
[ { "answer_id": 74569498, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "array[0] char *[8] array[0][0] char * strdup() #include <string.h>\n// ...\nchar *array[4][8];\narray[0][0] = strdup(\"test\");\nfree(array[0][0]);\n const const char *array2[4][8];\narray2[0][0] = \"test\";\n #include <string.h>\n//...\nchar array3[4][8];\nstrcpy(array3[0], \"test\");\n" }, { "answer_id": 74569499, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 0, "selected": false, "text": "array[0][0] = \"test;\" const char *array[4][8];" }, { "answer_id": 74569508, "author": "striker", "author_id": 20596655, "author_profile": "https://Stackoverflow.com/users/20596655", "pm_score": -1, "selected": false, "text": "int main() {\n char *array[4][8];\n array[0][0] = \"test\";\n}\n" }, { "answer_id": 74569586, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 1, "selected": true, "text": "char *array[4][8]; char array[4][8]; // i.e. without *\n = strcpy strcpy(array[0], \"test\");\n = char array[4][8] ={\"test\", \"hello\", \"world\", \"done\"};\n for (int i=0; i < 4; ++i) puts(array[i]);\n test\nhello\nworld\ndone\n printf(\"%c\", array[1][4]);\n o hello" }, { "answer_id": 74569595, "author": "Nicholas", "author_id": 10663879, "author_profile": "https://Stackoverflow.com/users/10663879", "pm_score": 0, "selected": false, "text": "int main() { \n char *array[4][8];\n array[0] = \"test\";\n}\n char* array[0] array[0] char* char* array[0][0] = \"test\";\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74569456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20579718/" ]