qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,600,439
<p>The goal is to write a function that returns the total quantity of all storage units put together (Madrid, Barcelona and Seville), I do think its better to use a recursion for this problem however i cant seem to work it out! I have this dictionary:</p> <pre><code>Storage = { &quot;Madrid&quot;: [ {&quot;name&quot;: &quot;pencil&quot;, &quot;quantity&quot;: 5}, {&quot;name&quot;: &quot;cam&quot;, &quot;quantity&quot;: 11}, {&quot;name&quot;: &quot;powder&quot;, &quot;quantity&quot;: 51} ], &quot;Barcelona&quot;: { &quot;Branch 1&quot;: [ {&quot;name&quot;: &quot;pencil&quot;, &quot;quantity&quot;: 11}, {&quot;name&quot;: &quot;cam&quot;, &quot;quantity&quot;: 25} ], &quot;Branch 2&quot;: [ {&quot;name&quot;: &quot;pencil&quot;, &quot;quantity&quot;: 17}, {&quot;name&quot;: &quot;cam&quot;, &quot;quantity&quot;: 9} ] }, &quot;Seville&quot;: { &quot;Branch 1&quot;: { &quot;Sub Branch 1&quot;: { &quot;Sub sub Branch 1&quot;: [ {&quot;name&quot;: &quot;powder&quot;, &quot;quantity&quot;: 11} ] } }, &quot;Branch 2&quot;: [ {&quot;name&quot;: &quot;pencil&quot;, &quot;quantity&quot;: 4} ] } } </code></pre> <p>I searched and wrote a lot of codes and this is the one that made the most sense</p> <pre><code>def recursive_sum(n): current_sum = 0 for key in n: if not isinstance(n[key], dict): if not isinstance(n[key], str): current_sum = current_sum + n[key] else: current_sum = current_sum + recursive_sum(n[key]) return current_sum print(recursive_sum(Storage)) </code></pre> <p>but it returns this:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/user/Desktop/pythonProject/main.py&quot;, line 85, in &lt;module&gt; print(recursive_sum(Storage)) File &quot;/Users/user/Desktop/pythonProject/main.py&quot;, line 79, in recursive_sum current_sum = current_sum + n[key] TypeError: unsupported operand type(s) for +: 'int' and 'list' </code></pre> <p>i searched a lot but i cant seem to understand how am i going to take the values of the list inside the dictionary, am i thinking wrong? Thank you in advance!</p>
[ { "answer_id": 74600538, "author": "Yip", "author_id": 15047837, "author_profile": "https://Stackoverflow.com/users/15047837", "pm_score": 0, "selected": false, "text": "if not isinstance(n[key], str):\n current_sum = current_sum + n[key]\n [{'name': 'pencil', 'quantity': 5}, {'name': 'cam', 'quantity': 11}, {'name': 'powder', 'quantity': 51}]\n def recursive_sum(n):\ncurrent_sum = 0\nfor key in n:\n if not isinstance(n[key], dict):\n if not isinstance(n[key], str):\n for i in n[key]:\n current_sum = current_sum + i[\"quantity\"]\n \n else:\n current_sum = current_sum + recursive_sum(n[key])\nreturn current_sum\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450290/" ]
74,600,456
<p>I have response coming from the api like attached image. I want to convert this response to the image. I have tried to convert this into base64 string but i am not able to do it as well.</p> <p>Image of the response</p> <p><a href="https://i.stack.imgur.com/4bamb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4bamb.png" alt="enter image description here" /></a></p> <p>api is like this:</p> <pre><code> axios.get(`https://api.bamboohr.com/api/gateway.php/tadigital/v1/employees/2223/photo/large`, { auth: { username: 'xxxxxxxxxxxxxxxxx', password: 'xxxxxxxxxxxxxxxxx' } } ).then(resp =&gt; { console.log(resp.data) }); </code></pre> <p>I want the solution without using responseType in the get request because api is not accepting the response type. I am not getting a way to convert this to image</p>
[ { "answer_id": 74600538, "author": "Yip", "author_id": 15047837, "author_profile": "https://Stackoverflow.com/users/15047837", "pm_score": 0, "selected": false, "text": "if not isinstance(n[key], str):\n current_sum = current_sum + n[key]\n [{'name': 'pencil', 'quantity': 5}, {'name': 'cam', 'quantity': 11}, {'name': 'powder', 'quantity': 51}]\n def recursive_sum(n):\ncurrent_sum = 0\nfor key in n:\n if not isinstance(n[key], dict):\n if not isinstance(n[key], str):\n for i in n[key]:\n current_sum = current_sum + i[\"quantity\"]\n \n else:\n current_sum = current_sum + recursive_sum(n[key])\nreturn current_sum\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17320926/" ]
74,600,529
<p>I'm planning to use my WordPress installation as a headless and only consume data via WP API (<a href="https://developer.wordpress.org/rest-api/reference/" rel="nofollow noreferrer">https://developer.wordpress.org/rest-api/reference/</a>) in the front-end.</p> <p>But by default, the UI of the client-facing website is visible to all the users and I want to make sure that if a customer opens a website it gets redirected to my front end.</p> <p>To make it clear, here's examples:</p> <ul> <li>open: wordpress-example.com -&gt; redirect to my-api-example.com</li> <li>open: wordpress-example.com/any-route -&gt; redirect to my-api-example.com etc.</li> <li>open: wordpress-example.com/wp-json/wp/v2/posts -&gt; return API response</li> <li>open: wordpress-example.com/wp-json/wp/v2/categories -&gt; return API response etc.</li> <li>open: wordpress-example.com/wp-admin.php -&gt; opens WP Admin</li> </ul> <p>Solution 1: Maybe there is a global setting in WordPress or a separate plug-in that disables the UI. I could not find it.</p> <p>Solution 2: Adjust the .thaccess file to exclude <code>/wp-admin.php</code> and <code>/wp-json/</code> routes <a href="https://fedingo.com/how-to-exclude-folder-from-rewrite-rule-in-htaccess/" rel="nofollow noreferrer">https://fedingo.com/how-to-exclude-folder-from-rewrite-rule-in-htaccess/</a></p>
[ { "answer_id": 74600538, "author": "Yip", "author_id": 15047837, "author_profile": "https://Stackoverflow.com/users/15047837", "pm_score": 0, "selected": false, "text": "if not isinstance(n[key], str):\n current_sum = current_sum + n[key]\n [{'name': 'pencil', 'quantity': 5}, {'name': 'cam', 'quantity': 11}, {'name': 'powder', 'quantity': 51}]\n def recursive_sum(n):\ncurrent_sum = 0\nfor key in n:\n if not isinstance(n[key], dict):\n if not isinstance(n[key], str):\n for i in n[key]:\n current_sum = current_sum + i[\"quantity\"]\n \n else:\n current_sum = current_sum + recursive_sum(n[key])\nreturn current_sum\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/405623/" ]
74,600,539
<p>i'm new to Java, so i have a little problem here...</p> <p>i need to write a function that extracts the server name from the URL It means the following: For a row of the form http://SomeServerName/abcd/dfdf.htm?dfdf=dfdf i need to isolate &quot;SomeServerName&quot;</p> <ul> <li>The string may not necessarily start with http, but also with https or something else. But :// there is always</li> <li>Consider the case when there is no more slash after :// (for example http://SomeServerName)</li> <li>I need to use only indexOf and substring</li> </ul> <pre><code>// This is what i got so far public static String getURL(String string) { int startIndex = string.indexOf('/') + 2; int endIndex = string.indexOf(&quot;/&quot;, startIndex); return string.substring(startIndex, endIndex); } public static void main(String[] args) { String string = &quot;https://SomeServerName/abcd/dfdf.htm?dfdf=dfdf&quot;; System.out.println(getURL(string)); } </code></pre>
[ { "answer_id": 74600658, "author": "user2959556", "author_id": 2959556, "author_profile": "https://Stackoverflow.com/users/2959556", "pm_score": -1, "selected": true, "text": " // Sample String s.\n String s = \"http://SomeServerName/abcd/dfdf.htm?dfdf=dfdf\";\n /*\n get a substring(startIndex, endIndex)\n startIndex : search for index of string \"//\" and add its length to get to end of it.\n endIndex: input string length.\n */\n String s1 = s.substring(s.indexOf(\"//\")+2,s.length());\n /*\n get a substring(startIndex, endIndex)\n startIndex : 0\n endIndex : starting index of \"/\" if present or length of string s1\n */\n String output = s1.substring(0, s1.indexOf(\"/\") > 0 ? s1.indexOf(\"/\") : s1.length());\n System.out.println(output); // output : SomeServerName\n" }, { "answer_id": 74600894, "author": "vinith vasudevan", "author_id": 14183807, "author_profile": "https://Stackoverflow.com/users/14183807", "pm_score": 0, "selected": false, "text": "String s=\"http://SomeServerName\";\n String s1=s.substring(s.indexOf(\"://\")+3);\n if(s1.indexOf(\"/\")==-1) {\n System.out.println(s1);\n }else {\n System.out.println(s1.substring(0,s1.indexOf(\"/\")));\n }\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623335/" ]
74,600,545
<p>I encountered some code at work today where an exception is thrown from a destructor.</p> <ul> <li>You should never throw an exception from a destructor. I point this out because I'm sure if I don't, someone else will.</li> </ul> <p>I am informed that this was a concious design decision and is needed to clean up some data in the case where another failure is encountered. The process of stack-unwinding is being exploited to do the clean up. Under normal circumstances the clean-up process is successful and no exception is thrown. However today I encountered a case where the clean-up failed and an exception is thrown, hence I began to investigate.</p> <p><em>The above aside, since this is not a question about code-reviewing code the organization I work for uses, my question is as follows.</em></p> <h5>What happens if the code path followed as the result of throwing an exception throws another exception?</h5> <p>Since this is an unsual situation I only know of 2 ways this can happen.</p> <ol> <li><p>The first is the trivial case where an exception is thrown, it is caught by a catch block, and that then throws. This is the same as just throwing an exception which is not caught. There are already some questions about this, for example <a href="https://stackoverflow.com/questions/981400/what-happens-if-a-throw-statement-is-executed-outside-of-catch-block">here</a>. In short, <code>terminate()</code> is called.</p> </li> <li><p>When an exception is thrown, the <a href="https://stackoverflow.com/questions/8311457/are-destructors-called-after-a-throw-in-c">Stack Unwinding process</a> begins. This process calls destructors of stack allocated objects. Therefore the only other way I know of to cause the throwing of nested exceptions is to throw inside a destructor, in the same manner as I encountered today.</p> </li> </ol> <p>I cannot think of any further possibilities. If there are any I would be interested to hear of them.</p> <p>Regarding point 2. What happens in this case?</p>
[ { "answer_id": 74600546, "author": "FreelanceConsultant", "author_id": 893254, "author_profile": "https://Stackoverflow.com/users/893254", "pm_score": 0, "selected": false, "text": "terminate() terminate() abort() abort() SIGABRT terminate() abort() Aborted echo $? 134" }, { "answer_id": 74601078, "author": "Quimby", "author_id": 7691729, "author_profile": "https://Stackoverflow.com/users/7691729", "pm_score": 2, "selected": false, "text": "catch terminate throw; std::terminate catch throw E catch std::terminate catch E catch throw std​::​uncaught_­exceptions std::terminate if (std::uncaught_exceptions()==0)// Safe throw from dtor.\n throw 42;\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893254/" ]
74,600,568
<p>I am looking for the best way to do pandas' <code>df.groupby([&quot;group_a&quot;, &quot;group_b&quot;]).ngroup()</code>in polars and assign that specific ngroup counter value back to the respective group.</p> <pre><code>df = pl.DataFrame( {&quot;group_a&quot;: [&quot;a&quot;, &quot;aa&quot;, &quot;a&quot;], &quot;group_b&quot;: [&quot;b&quot;, &quot;bb&quot;, &quot;b&quot;], &quot;val&quot;: [1, 2, 3]} ) ┌─────────┬─────────┬─────┐ │ group_a ┆ group_b ┆ val │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞═════════╪═════════╪═════╡ │ a ┆ b ┆ 1 │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ aa ┆ bb ┆ 2 │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ a ┆ b ┆ 3 │ └─────────┴─────────┴─────┘ </code></pre> <p>should become</p> <pre><code>┌─────────┬─────────┬─────┬───────────┐ │ group_a ┆ group_b ┆ val ┆ new_group │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 ┆ i64 │ ╞═════════╪═════════╪═════╪═══════════╡ │ a ┆ b ┆ 1 ┆ 0 │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤ │ aa ┆ bb ┆ 2 ┆ 1 │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤ │ a ┆ b ┆ 3 ┆ 0 │ └─────────┴─────────┴─────┴───────────┘ </code></pre> <p>In pandas, I would use ngroups to do this with a join, but don't know in polars.</p> <p>Edit: I have found one possible workaround but I feel like there should be a better, more efficient way, since it also gets killed for my actual dataset of millions of rows.</p> <pre><code>group_ids = [&quot;group_a&quot;, &quot;group_b&quot;] df = df.join( pl.concat([ df.unique(subset=group_ids), (pl.arange(0, len(df.unique(subset=group_ids)), eager=True, dtype=pl.Int64) .alias(&quot;new_id&quot;) .to_frame())], how=&quot;horizontal&quot;) .select(group_ids + [&quot;new_id&quot;]), left_on=group_ids, right_on=group_ids ) </code></pre>
[ { "answer_id": 74603070, "author": "jqurious", "author_id": 19355181, "author_profile": "https://Stackoverflow.com/users/19355181", "pm_score": 3, "selected": true, "text": ".rank(method=\"dense\") >>> df = pl.DataFrame({\n... \"group_a\": [\"a\", \"aa\", \"a\", \"aaa\"], \n... \"group_b\": [\"b\", \"bb\", \"b\", \"bbb\"], \n... \"val\": [1, 2, 3, 4] \n... })\n...\n... group_ids = [\"group_a\", \"group_b\"]\n...\n... (\n... df\n... .with_row_count(name=\"new_id\")\n... .with_column(\n... pl.col(\"new_id\")\n... .first()\n... .over(group_ids)\n... .rank(method=\"dense\") - 1\n... )\n... )\nshape: (4, 4)\n┌────────┬─────────┬─────────┬─────┐\n│ new_id | group_a | group_b | val │\n│ --- | --- | --- | --- │\n│ u32 | str | str | i64 │\n╞════════╪═════════╪═════════╪═════╡\n│ 0 | a | b | 1 │\n├────────┼─────────┼─────────┼─────┤\n│ 1 | aa | bb | 2 │\n├────────┼─────────┼─────────┼─────┤\n│ 0 | a | b | 3 │\n├────────┼─────────┼─────────┼─────┤\n│ 2 | aaa | bbb | 4 │\n└─//─────┴─//──────┴─//──────┴─//──┘\n >>> (\n... df\n... .with_row_count(name=\"new_id\")\n... .with_column(pl.col(\"new_id\").first().over(group_ids))\n... )\nshape: (4, 4)\n┌────────┬─────────┬─────────┬─────┐\n│ new_id | group_a | group_b | val │\n│ --- | --- | --- | --- │\n│ u32 | str | str | i64 │\n╞════════╪═════════╪═════════╪═════╡\n│ 0 | a | b | 1 │\n├────────┼─────────┼─────────┼─────┤\n│ 1 | aa | bb | 2 │\n├────────┼─────────┼─────────┼─────┤\n│ 0 | a | b | 3 │\n├────────┼─────────┼─────────┼─────┤\n│ 3 | aaa | bbb | 4 │\n└─//─────┴─//──────┴─//──────┴─//──┘\n .rank(method=\"dense\") 1" }, { "answer_id": 74606478, "author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ", "author_id": 20557510, "author_profile": "https://Stackoverflow.com/users/20557510", "pm_score": 2, "selected": false, "text": "groupby_vars = \"group_a\", \"group_b\"\n(\n df.join(\n df.select(groupby_vars).unique().with_row_count(name=\"group_id\"),\n on=groupby_vars,\n )\n)\n shape: (4, 4)\n┌─────────┬─────────┬─────┬──────────┐\n│ group_a ┆ group_b ┆ val ┆ group_id │\n│ --- ┆ --- ┆ --- ┆ --- │\n│ str ┆ str ┆ i64 ┆ u32 │\n╞═════════╪═════════╪═════╪══════════╡\n│ a ┆ b ┆ 1 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤\n│ aa ┆ bb ┆ 2 ┆ 1 │\n├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤\n│ a ┆ b ┆ 3 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤\n│ aaa ┆ bbb ┆ 4 ┆ 2 │\n└─────────┴─────────┴─────┴──────────┘\n" }, { "answer_id": 74615533, "author": "ritchie46", "author_id": 6717054, "author_profile": "https://Stackoverflow.com/users/6717054", "pm_score": -1, "selected": false, "text": "DataFrame df = pl.DataFrame({\n \"group_a\": [\"a\", \"aa\", \"a\"], \n \"group_b\": [\"b\", \"bb\", \"b\"], \"val\": [1, 2, 3]\n})\n\n(df\n .with_column(pl.arange(0, pl.count()).alias(\"new_group\"))\n .with_column(\n pl.first(\"new_group\").over([\"group_a\", \"group_b\"])\n))\n shape: (3, 4)\n┌─────────┬─────────┬─────┬───────────┐\n│ group_a ┆ group_b ┆ val ┆ new_group │\n│ --- ┆ --- ┆ --- ┆ --- │\n│ str ┆ str ┆ i64 ┆ i64 │\n╞═════════╪═════════╪═════╪═══════════╡\n│ a ┆ b ┆ 1 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ aa ┆ bb ┆ 2 ┆ 1 │\n├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ a ┆ b ┆ 3 ┆ 0 │\n└─────────┴─────────┴─────┴───────────┘\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386797/" ]
74,600,602
<p><strong>Hi, please, how to get an ordered list in c#</strong></p> <pre><code>string[] names = {&quot;name1&quot;, &quot;name2&quot;, &quot;name3&quot;}; </code></pre> <p>I would like a result like this:</p> <pre><code>001 name1 002 name2 003 name3 etc ... </code></pre> <p>but not like this</p> <pre><code>1 name1 2 name2 3 name3 etc ... </code></pre> <p>I tried a while loop like:</p> <pre><code>string[] cars = {&quot;name1&quot;, &quot;name2&quot;, &quot;name3&quot;}; foreach (string i in cars) { Console.WriteLine(i); } </code></pre> <p>but I want a result like</p> <pre><code>001 name1 002 name2 003 name3 etc ... </code></pre> <p>not only the names</p>
[ { "answer_id": 74600679, "author": "Ralf", "author_id": 777522, "author_profile": "https://Stackoverflow.com/users/777522", "pm_score": -1, "selected": false, "text": "string[] cars = new[] { \"name1\", \"name2\", \"name3\" };\n\nfor (int i = 0; i < cars.Length; i++)\n Console.WriteLine($\"{i:D3} {cars[i]}\");\n" }, { "answer_id": 74600696, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < cars.Length; i++) {\n Console.WriteLine($\"{i + 1:000} {cars[i]}\");\n}\n string i i s string car $\"{i + 1:000} {cars[i]}\" $ { } : 000 Car public class Car\n{\n public string Name { get; set; }\n \n public int Index { get; set; }\n\n public override string ToString()\n {\n return $\"{Index:000} {Name}\"\n }\n}\n Car[] cars = {\n new Car { Name = \"name\", Index = 1 },\n new Car { Name = \"other name\", Index = 2 },\n new Car { Name = \"yet another name\", Index = 3 },\n};\n\nforeach (Car car in cars) \n{\n Console.WriteLine(car);\n}\n" }, { "answer_id": 74600871, "author": "Maahi", "author_id": 10786431, "author_profile": "https://Stackoverflow.com/users/10786431", "pm_score": -1, "selected": false, "text": "string[] cars = {\"name3\", \"name2\", \"name1\"};\nArray.Sort(cars);\n\nfor (int i = 0; i < cars.Length; i++)\nConsole.WriteLine($\"{i:D3} {cars[i]}\");\n 001 name1\n 002 name2\n 003 name3\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533121/" ]
74,600,610
<p>I'm a newcomer to django and I'm trying to create a user system where different users can log in and upload and view their documents. The upload and viewing works except users are able to see each others documents as well. How can I make it so that users are only able to see documents uploaded by them?</p> <p>The following question also talk about the same problem but I'm unable to understand how the issue was fixed: <a href="https://stackoverflow.com/questions/63767371/how-to-show-user-posted-blog-in-user-profile-page-as-a-my-post-list-section-in-d/74595059#74595059">How to show user posted blog in user profile page as a my post list section in Django 3?</a></p> <p>I realize I've to use foreign keys in my models but I'm not sure how to implement it. Here's snippets of my code so far:</p> <p>Edit: Removed code due to copyright. For all those who helped, thanks a ton. Your answers were immeasurably helpful.</p>
[ { "answer_id": 74600680, "author": "NixonSparrow", "author_id": 12775662, "author_profile": "https://Stackoverflow.com/users/12775662", "pm_score": -1, "selected": false, "text": "{% for document in documents %}\n {% if document.user == request.user %}\n <li><a href=\"{{ document.docfile.url }}\">{{ document.docfile.name }}</a></li>\n {% endif %}\n{% endfor %}\n User Document ForeignKey user" }, { "answer_id": 74600813, "author": "TrueGopnik", "author_id": 16494437, "author_profile": "https://Stackoverflow.com/users/16494437", "pm_score": 1, "selected": false, "text": "# Load documents for the list page\ndocuments = Document.objects.filter(user=request.user)\n\n# Render list page with the documents and the form\ncontext = {'documents': documents, 'form': form, 'message': message}\nreturn render(request, 'list.html', context)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14395093/" ]
74,600,621
<p>I was trying to follow a tutorial on building an app with typescript and react and I keep getting this error: ,,Cannot read properties of undefined (reading 'map')&quot;. Not sure why, can someone maybe help?</p> <p>Here is the code of the component:</p> <pre><code>import { useState } from 'react'; import { useTypedSelector } from '../hooks/useTypedSelector'; import { useActions } from '../hooks/useActions'; const RepositoriesList: React.FC = () =&gt; { const [term, setTerm] = useState(''); const { searchRepositories } = useActions(); const { data, error, loading } = useTypedSelector( (state) =&gt; state.repositories ); const onSubmit = (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; { event.preventDefault(); searchRepositories(term); }; return ( &lt;div&gt; &lt;form onSubmit={onSubmit}&gt; &lt;input value={term} onChange={(e) =&gt; setTerm(e.target.value)} /&gt; &lt;button&gt;Search&lt;/button&gt; &lt;/form&gt; {error &amp;&amp; &lt;h3&gt;{error}&lt;/h3&gt;} {loading &amp;&amp; &lt;h3&gt;Loading...&lt;/h3&gt;} {!error &amp;&amp; !loading &amp;&amp; data.map((name) =&gt; &lt;div key={name}&gt;{name}&lt;/div&gt;)} &lt;/div&gt; ); }; export default RepositoriesList; </code></pre>
[ { "answer_id": 74600680, "author": "NixonSparrow", "author_id": 12775662, "author_profile": "https://Stackoverflow.com/users/12775662", "pm_score": -1, "selected": false, "text": "{% for document in documents %}\n {% if document.user == request.user %}\n <li><a href=\"{{ document.docfile.url }}\">{{ document.docfile.name }}</a></li>\n {% endif %}\n{% endfor %}\n User Document ForeignKey user" }, { "answer_id": 74600813, "author": "TrueGopnik", "author_id": 16494437, "author_profile": "https://Stackoverflow.com/users/16494437", "pm_score": 1, "selected": false, "text": "# Load documents for the list page\ndocuments = Document.objects.filter(user=request.user)\n\n# Render list page with the documents and the form\ncontext = {'documents': documents, 'form': form, 'message': message}\nreturn render(request, 'list.html', context)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18141122/" ]
74,600,624
<p>I am looking for help with changing some CSS properties of my button in my Ionic app.</p> <p>I want my button to look like this: <a href="https://i.stack.imgur.com/XQDzQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQDzQ.png" alt="enter image description here" /></a></p> <p>This is how it looks like now: <a href="https://i.stack.imgur.com/NF8CK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NF8CK.png" alt="enter image description here" /></a></p> <p>I have figured out that if I want to achieve my desired look I have to change the CSS property <code>justify-content: center;</code> of the DOM generated div with class <code>button-inner</code> to <code>justify-content: space-between;</code>... the problem is I don't know how to properly target this element in my SCSS file... I have tried with bellow examples as seen in the docs but nothing works...</p> <pre><code> .button-native { span { justify-content: space-between; } } ion-button:scope(native) { span { justify-content: space-between; } } ion-button:scope(native) { .button-native { justify-content: space-between; } } ion-button:root(native) { span { justify-content: space-between; } } ion-button:root(native) { .button-native { justify-content: space-between; } } </code></pre> <p>Here is also my HTML markup for the button:</p> <pre><code>&lt;ion-button expand=&quot;block&quot;&gt;Add to cart &lt;span&gt;{{ 123 }} €&lt;/span&gt;&lt;/ion-button&gt; </code></pre> <p>what am I missing? What am I doing wrong?</p>
[ { "answer_id": 74601117, "author": "AmirAli Saghaei", "author_id": 14661202, "author_profile": "https://Stackoverflow.com/users/14661202", "pm_score": 0, "selected": false, "text": "<ion-button expand=\"block\">Add to cart \n<div style=\"flex-grow: 10;\"></div>\n<span>{{ 123 }} €</span></ion-button>\n" }, { "answer_id": 74604406, "author": "StackoverBlows", "author_id": 19979278, "author_profile": "https://Stackoverflow.com/users/19979278", "pm_score": 1, "selected": false, "text": "<div class=\"btn-container ion-activatable ripple-parent rectangle\" (click)=\"doSomething()\">\n <ion-ripple-effect></ion-ripple-effect>\n <div class=\"label\">\n <span>Add to cart</span>\n </div>\n <div class=\"amount\">\n <span>€</span>\n </div>\n</div>\n\n.btn-container {\n background-color: blue;\n border-radius: 8px;\n height: 40px;\n width: 240px;\n\n .label {\n margin: 8px;\n float: left;\n color: white;\n font-weight: 500;\n }\n\n .amount {\n margin: 8px;\n float: right;\n color: white;\n font-weight: 500;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7068325/" ]
74,600,633
<p>I have got a responsive two-column layout page. When the size of the screen is down to tablet, it becomes a single-column layout, where the first column wont be visible anymore. I have got a div inside the second div, and I want this to be vertically centre aligned.</p> <p>I am using tailwind along with flexbox.</p> <p>This is my code so far</p> <pre><code> &lt;div className=&quot;flex min-h-full&quot;&gt; &lt;div className=&quot;flex-none w-1/3 min-h-full hidden lg:block&quot;&gt; 01 &lt;/div&gt; &lt;div className=&quot;grow md:bg-slate-100 h-screen&quot;&gt; &lt;div className=&quot;bg-red-400 h-3/5 mx-16&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I have tried various options but I am struggling to have the inner div to be center alligned. Currently its sticking to top.</p>
[ { "answer_id": 74601117, "author": "AmirAli Saghaei", "author_id": 14661202, "author_profile": "https://Stackoverflow.com/users/14661202", "pm_score": 0, "selected": false, "text": "<ion-button expand=\"block\">Add to cart \n<div style=\"flex-grow: 10;\"></div>\n<span>{{ 123 }} €</span></ion-button>\n" }, { "answer_id": 74604406, "author": "StackoverBlows", "author_id": 19979278, "author_profile": "https://Stackoverflow.com/users/19979278", "pm_score": 1, "selected": false, "text": "<div class=\"btn-container ion-activatable ripple-parent rectangle\" (click)=\"doSomething()\">\n <ion-ripple-effect></ion-ripple-effect>\n <div class=\"label\">\n <span>Add to cart</span>\n </div>\n <div class=\"amount\">\n <span>€</span>\n </div>\n</div>\n\n.btn-container {\n background-color: blue;\n border-radius: 8px;\n height: 40px;\n width: 240px;\n\n .label {\n margin: 8px;\n float: left;\n color: white;\n font-weight: 500;\n }\n\n .amount {\n margin: 8px;\n float: right;\n color: white;\n font-weight: 500;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2556858/" ]
74,600,667
<p>I m developing a Flutter APP in MVC+S Design. Also I use the Providers with Notifylisteners but often I got the Message <code>setState() or markNeedsBuild() called during build.</code></p> <p>What is the Best practice of using Providers and Notfylisteners to avoid this problem ?</p> <p>My Code looks like:</p> <pre><code>Class Test() { String? testA String? testB FunctionA async() { ... testA = 'TestA'; notfifyListeners() }; FunctionB async() { ... testB = 'TestB'; notfifyListeners(); } </code></pre> <pre><code> class Test extends StatefulWidget { . . . class TestState extends State&lt;Test&gt; { @override voide iniState() { locator&lt;TestController&gt;().FunctionA(); locator&lt;TestController&gt;().FunctionB(); super.initState(); } } . . . } </code></pre>
[ { "answer_id": 74600810, "author": "vanosidor", "author_id": 6380755, "author_profile": "https://Stackoverflow.com/users/6380755", "pm_score": 1, "selected": false, "text": "@override\nvoid initState() {\n super.initState();\n\n WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {\n locator<TestController>().FunctionA();\n locator<TestController>().FunctionB();\n });\n}\n" }, { "answer_id": 74601095, "author": "Amirali_Eric_J", "author_id": 8388842, "author_profile": "https://Stackoverflow.com/users/8388842", "pm_score": 1, "selected": false, "text": "addPostFrameCallback class TestState extends State<Test> {\n @override\n voide iniState() {\n WidgetsBinding.instance?.addPostFrameCallback((timeStamp){\n locator<TestController>().FunctionA();\n locator<TestController>().FunctionB();\n });\n super.initState();\n }\n\n}\n addPostFrameCallback dispose notfifyListeners()" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598225/" ]
74,600,678
<p>Looking for JSON SCHEMA I have the above json as request using json schema validation i want to make sure the value of 'ActionCode' should be same as HeaderActionCode for any level of child I can have</p> <pre><code> { &quot;Body&quot;: { &quot;LeadDetails&quot;: { &quot;HeaderActionCode&quot;: &quot;Add&quot;, &quot;ActionCode&quot;: &quot;Add&quot;, &quot;Version&quot;: 1, &quot;LineItems&quot;: [ { &quot;ActionCode&quot;: &quot;Add&quot;, &quot;Version&quot;: 0, &quot;LineItems&quot;: [ { &quot;ActionCode&quot;: &quot;Add&quot;, &quot;Version&quot;: 0, &quot;LineItems&quot;: [ { &quot;ActionCode&quot;: &quot;Add&quot;, &quot;Version&quot;: 0 } ] } ] } ] } } } </code></pre> <p>I have the above json as request using json schema validation i want to make sure the value of 'ActionCode' should be same as HeaderActionCode for any level of child I can have</p>
[ { "answer_id": 74600854, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "const validate = (value) => {\n let data = value.Body.LeadDetails\n let actionCode = data.HeaderActionCode\n let items = data.LineItems\n while(items.length > 0){\n let i = items.shift()\n if(i.ActionCode !== actionCode){\n return false\n }\n if(i.LineItems){\n items.push(...i.LineItems)\n }\n }\n return true\n}\n\nconsole.log(validate(json))\n let json =\n{\n \"Body\": {\n \"LeadDetails\": {\n \"HeaderActionCode\": \"Add\",\n \"ActionCode\": \"Add\",\n \"Version\": 1,\n \"LineItems\": [\n {\n \"ActionCode\": \"Add\",\n \"Version\": 0,\n \"LineItems\": [\n {\n \"ActionCode\": \"Add\",\n \"Version\": 0,\n \"LineItems\": [\n {\n \"ActionCode\": \"Add\",\n \"Version\": 0\n }\n ]\n }\n ]\n }\n ]\n }\n }\n}\n\nconst validate = (value) => {\n let data = value.Body.LeadDetails\n let actionCode = data.HeaderActionCode\n if(actionCode !== data.ActionCode){\n return false \n }\n let items = data.LineItems\n while(items.length > 0){\n let i = items.shift()\n if(i.ActionCode !== actionCode){\n return false\n }\n if(i.LineItems){\n items.push(...i.LineItems)\n }\n }\n return true\n}\n\nconsole.log(validate(json))" }, { "answer_id": 74600877, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 2, "selected": true, "text": "var obj = {Body:{LeadDetails:{HeaderActionCode:\"Add\",ActionCode:\"Add\",Version:1,LineItems:[{ActionCode:\"Add\",Version:0,LineItems:[{ActionCode:\"Add\",Version:0,LineItems:[{ActionCode:\"Add\",Version:0}]}]}]}}};\n\nfunction inspectLineItems(arr, HeaderActionCode) {\n if (!arr) return true;\n arr.forEach(function(item) {\n if (item.ActionCode != HeaderActionCode || !inspectLineItems(item.LineItems, HeaderActionCode)) {\n throw new Error(\"missmatch\")\n }\n })\n return true;\n}\n\nfunction inspectLeadDetails(obj) {\n try {\n var HeaderActionCode = obj.HeaderActionCode;\n return inspectLineItems(obj.LineItems, HeaderActionCode);\n } catch (ex) {\n return false\n }\n}\n\nconsole.log(inspectLeadDetails(obj.Body.LeadDetails))" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10199200/" ]
74,600,681
<p>After migrating a project from Spring Boot v2.7 to v3.0 (and thus from Spring Integration v5.5 to v6.0), the following warnings are printed out:</p> <pre><code>WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassA WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassB WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassC WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassD </code></pre> <p><code>MyClassA</code> extends <code>IntegrationFlowAdapter</code>, and is annotated with <code>@Component</code>:</p> <pre class="lang-java prettyprint-override"><code>package com.foobar; @Component class MyClassA extends IntegrationFlowAdapter { // … } </code></pre> <p><code>MyClassB</code> is annotated with <code>@ConfigurationProperties</code>:</p> <pre class="lang-java prettyprint-override"><code>package com.foobar; @ConfigurationProperties(&quot;my-config&quot;) class MyClassB { // … } </code></pre> <p><code>MyClassC</code> is annotated with <code>@Configuration</code>:</p> <pre class="lang-java prettyprint-override"><code>package com.foobar; @Configuration class MyClassC { // … } </code></pre> <p>And this particular one not even extending anything, nor annotated:</p> <pre class="lang-java prettyprint-override"><code>package com.foobar; class MyClassD { // … } </code></pre> <p>I didn’t see any relevant information in the <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide" rel="nofollow noreferrer">Spring Boot</a> and <a href="https://github.com/spring-projects/spring-integration/wiki/Spring-Integration-5.x-to-6.0-Migration-Guide" rel="nofollow noreferrer">Spring Integration</a> migration guides. There is a <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide#simplified-main-class-name-resolution-with-gradle" rel="nofollow noreferrer">section</a> about <em>name resolution</em> in the Spring Boot migration guide, but it is related to Gradle, and I’m using Maven. I’m not even sure what this name resolution is all about.</p> <p>I’m puzzled with the class <code>LocalVariableTableParameterNameDiscoverer</code>, and I’m not sure what migration task I’m supposed to do.</p>
[ { "answer_id": 74601911, "author": "Morgan Courbet", "author_id": 1059429, "author_profile": "https://Stackoverflow.com/users/1059429", "pm_score": 1, "selected": false, "text": "-parameters javac pom.xml <project>\n \n <!-- … -->\n\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.10.1</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n\n <!-- … -->\n\n</project>\n" }, { "answer_id": 74601919, "author": "Artem Bilan", "author_id": 2756547, "author_profile": "https://Stackoverflow.com/users/2756547", "pm_score": 1, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer MessagePublishingInterceptor @Publisher PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME EvaluationContext @MessagingGateway @Header name MessagingMethodInvokerHelper name @Header LocalVariableTableParameterNameDiscoverer 6.0.1 StandardReflectionParameterNameDiscoverer" }, { "answer_id": 74675937, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer -parameters -debug -parameters compilerArgs maven-compiler-plugin pom.xml <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n -parameters -debug -parameters" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1059429/" ]
74,600,712
<p>I have data that i want to resample use end of month based on original df but when i use df.resample('M').last(). the end of month date that i got is different from original df. see the asterix marks. <em>2005-12-31</em> should be &gt;&gt; <em>2005-12-29</em>. any suggestion ? what parameter should i add into .resample() ?</p> <p>orginal df =</p> <pre><code>DATE 2005-12-27 1161.707 2005-12-28 1164.143 *2005-12-29 1162.635* 2006-01-02 1171.709 2006-01-03 1184.690 2006-01-04 1211.699 </code></pre> <p>test_resample = df.resample('M').last()</p> <pre><code>DATE 2005-11-30 1096.641 *2005-12-31 1162.635* 2006-01-31 1232.321 </code></pre>
[ { "answer_id": 74601911, "author": "Morgan Courbet", "author_id": 1059429, "author_profile": "https://Stackoverflow.com/users/1059429", "pm_score": 1, "selected": false, "text": "-parameters javac pom.xml <project>\n \n <!-- … -->\n\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.10.1</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n\n <!-- … -->\n\n</project>\n" }, { "answer_id": 74601919, "author": "Artem Bilan", "author_id": 2756547, "author_profile": "https://Stackoverflow.com/users/2756547", "pm_score": 1, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer MessagePublishingInterceptor @Publisher PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME EvaluationContext @MessagingGateway @Header name MessagingMethodInvokerHelper name @Header LocalVariableTableParameterNameDiscoverer 6.0.1 StandardReflectionParameterNameDiscoverer" }, { "answer_id": 74675937, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer -parameters -debug -parameters compilerArgs maven-compiler-plugin pom.xml <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n -parameters -debug -parameters" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16697053/" ]
74,600,714
<p>I want to run a script using a venv python~3.9 from a subprocess call of another application that uses python3.6. However the imported libraries are wrong and from the site-packages of 3.6 version. How can I modify the subprocess call to load the correct libraries i.e from the venv(3.9 version)</p> <pre><code>p = Popen([process_name, parameters_l], stdin=PIPE, stdout=PIPE, stderr=PIPE) </code></pre> <p>I have tried using the cwd and also changing the working directory via os.chdir however that doesn't seem to work. Furthermore I tried to run activat.bat from the venv, but the issue persists.</p>
[ { "answer_id": 74601911, "author": "Morgan Courbet", "author_id": 1059429, "author_profile": "https://Stackoverflow.com/users/1059429", "pm_score": 1, "selected": false, "text": "-parameters javac pom.xml <project>\n \n <!-- … -->\n\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.10.1</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n\n <!-- … -->\n\n</project>\n" }, { "answer_id": 74601919, "author": "Artem Bilan", "author_id": 2756547, "author_profile": "https://Stackoverflow.com/users/2756547", "pm_score": 1, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer MessagePublishingInterceptor @Publisher PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME EvaluationContext @MessagingGateway @Header name MessagingMethodInvokerHelper name @Header LocalVariableTableParameterNameDiscoverer 6.0.1 StandardReflectionParameterNameDiscoverer" }, { "answer_id": 74675937, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer -parameters -debug -parameters compilerArgs maven-compiler-plugin pom.xml <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n -parameters -debug -parameters" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245579/" ]
74,600,765
<p>I have a numpy.ndarray in Python has the following elements e.g[[-0.85] [ 0.95]]. How can I reverse it so it can be [ [ 0.95][-0.85]]. Keep in mind that the length always two but for sure the values are changing.</p> <pre><code>&lt;class 'numpy.ndarray'&gt; [[-0.85] [ 0.95]] </code></pre>
[ { "answer_id": 74601911, "author": "Morgan Courbet", "author_id": 1059429, "author_profile": "https://Stackoverflow.com/users/1059429", "pm_score": 1, "selected": false, "text": "-parameters javac pom.xml <project>\n \n <!-- … -->\n\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.10.1</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n\n <!-- … -->\n\n</project>\n" }, { "answer_id": 74601919, "author": "Artem Bilan", "author_id": 2756547, "author_profile": "https://Stackoverflow.com/users/2756547", "pm_score": 1, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer MessagePublishingInterceptor @Publisher PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME EvaluationContext @MessagingGateway @Header name MessagingMethodInvokerHelper name @Header LocalVariableTableParameterNameDiscoverer 6.0.1 StandardReflectionParameterNameDiscoverer" }, { "answer_id": 74675937, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "LocalVariableTableParameterNameDiscoverer -parameters -debug -parameters compilerArgs maven-compiler-plugin pom.xml <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n -parameters -debug -parameters" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20232879/" ]
74,600,771
<p>I'm starting to learn Ansible and for this I copy and paste examples from the documentation. For example this one</p> <pre class="lang-yaml prettyprint-override"><code>- name: Check that a page returns a status 200 and fail if the word AWESOME is not in the page contents ansible.builtin.uri: url: http://www.example.com return_content: yes register: this failed_when: &quot;'AWESOME' not in this.content&quot; </code></pre> <p>which I've found in <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/uri_module.html" rel="nofollow noreferrer"><code>uri</code></a> module documentation.</p> <p>Every single time I do this, whatever the module I get:</p> <pre><code>ERROR! 'ansible.builtin.uri' is not a valid attribute for a Play The error appears to have been in '/home/alfrerra/test2.yml': line 1, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - name: Check that a page returns a status 200 and fail if the word AWESOME is not in the page contents ^ here </code></pre> <p>I have only 2 playbooks that only ping successfully:</p> <pre class="lang-yaml prettyprint-override"><code>- name: ping localhost hosts: localhost tasks: - name: ping test ping </code></pre> <p>and</p> <pre class="lang-yaml prettyprint-override"><code>--- - name: ping localhost hosts: localhost tasks: - name: ping test ping </code></pre> <p>So I adapted the example to match these 2 examples, but to no avail so far.</p> <p>I'm sure it's nothing much but it's driving me crazy.</p>
[ { "answer_id": 74601886, "author": "harouna Rachid", "author_id": 18764062, "author_profile": "https://Stackoverflow.com/users/18764062", "pm_score": -1, "selected": false, "text": "failed_when - name: Check that a page returns AWESOME is not in the page contents \n ansible.builtin.uri: \n url: http://www.example.com \n return_content: yes \n register: this \n failed_when: this.rc == 0;\n" }, { "answer_id": 74610945, "author": "U880D", "author_id": 6771046, "author_profile": "https://Stackoverflow.com/users/6771046", "pm_score": 1, "selected": true, "text": "---\n- hosts: localhost\n become: false\n gather_facts: false\n\n tasks:\n\n - name: Check that a page returns a status 200 and fail if the word 'iana.org' is not in the page contents\n uri:\n url: http://www.example.com\n return_content: yes\n environment:\n http_proxy: \"localhost:3128\"\n https_proxy: \"localhost:3128\"\n register: this\n failed_when: \"'iana.org' not in this.content\"\n\n - name: Show content\n debug:\n msg: \"{{ this.content }}\"\n iana.org ERROR! ... not a valid attribute for a Play" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623449/" ]
74,600,774
<p>Let's say I have a constant enum like this:</p> <pre><code>const enum Fruit { Apple = 1, Banana, Carrot, Dragonfruit } </code></pre> <p>The size of this enum would be 4. When it's not a <code>const</code> enum, one can simply call something like <code>Object.keys</code> and do some math to get the size of it. However, I do not believe that works with a <code>const</code> enum.</p> <p>Another alternative that people recommend is to include <code>SIZE</code> parameter, like so:</p> <pre><code>const enum Fruit { Apple = 1, Banana, Carrot, Dragonfruit, __SIZE } </code></pre> <p>And then query <code>Fruit.__SIZE</code> to get the size. However, this has two problems:</p> <ol> <li><p>This application is networked, so when I eventually add more fruit, another fruit will take the spot of <code>__SIZE</code> as it is bumped up. This could cause issues due to the new fruit having the same integer id as the previous <code>SIZE / NULL</code> slot.</p> </li> <li><p>One has to always remember to keep the <code>__SIZE</code> value last, so it's prone to breakage due to a programmer forgetting to keep it synced.</p> </li> </ol> <p>Is there an alternative? Since it only has to be computed once when the application starts up, I don't even mind if it is very slow.</p>
[ { "answer_id": 74601886, "author": "harouna Rachid", "author_id": 18764062, "author_profile": "https://Stackoverflow.com/users/18764062", "pm_score": -1, "selected": false, "text": "failed_when - name: Check that a page returns AWESOME is not in the page contents \n ansible.builtin.uri: \n url: http://www.example.com \n return_content: yes \n register: this \n failed_when: this.rc == 0;\n" }, { "answer_id": 74610945, "author": "U880D", "author_id": 6771046, "author_profile": "https://Stackoverflow.com/users/6771046", "pm_score": 1, "selected": true, "text": "---\n- hosts: localhost\n become: false\n gather_facts: false\n\n tasks:\n\n - name: Check that a page returns a status 200 and fail if the word 'iana.org' is not in the page contents\n uri:\n url: http://www.example.com\n return_content: yes\n environment:\n http_proxy: \"localhost:3128\"\n https_proxy: \"localhost:3128\"\n register: this\n failed_when: \"'iana.org' not in this.content\"\n\n - name: Show content\n debug:\n msg: \"{{ this.content }}\"\n iana.org ERROR! ... not a valid attribute for a Play" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962155/" ]
74,600,779
<pre><code>dict1 = [{'id': 1.0, 'name': 'aa'}, {'id': 4.0, 'name': 'bb'}, {'id': 2.0, 'name': 'cc'}] </code></pre> <p>and</p> <pre><code>dict2 = [{'name': 'aa', 'dtype': 'StringType'}, {'name': 'bb', 'dtype': 'StringType'}, {'name': 'xx', 'dtype': 'StringType'}, {'name': 'cc', 'dtype': 'StringType'}] </code></pre> <p>I would like to merge this two dictionaries based on their common <code>key</code> which is <code>name</code>.</p> <p>I would like to get the following desired result.</p> <pre><code>merged_dict= [{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'}, {'id': 4.0, 'name': 'bb', 'dtype': 'StringType'}, {'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}] </code></pre> <p>I was trying to get this using the following for loop.</p> <pre><code>for i in dict1: for j in dict2: j.update(i) </code></pre>
[ { "answer_id": 74600814, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "update tmp = {d['name']: d for d in dict2}\n\nfor d in dict1:\n d.update(tmp.get(d['name'], {}))\n\nprint(dict1)\n [{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},\n {'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},\n {'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}]\n tmp {'aa': {'name': 'aa', 'dtype': 'StringType'},\n 'bb': {'name': 'bb', 'dtype': 'StringType'},\n 'xx': {'name': 'xx', 'dtype': 'StringType'},\n 'cc': {'name': 'cc', 'dtype': 'StringType'}}\n dict1 tmp = {d['name']: d for d in dict2}\nmerged_dict = [d|tmp.get(d['name'], {}) for d in dict1]\n" }, { "answer_id": 74600956, "author": "Ersel Er", "author_id": 4681316, "author_profile": "https://Stackoverflow.com/users/4681316", "pm_score": 0, "selected": false, "text": "import pandas as pd\ndf1 = pd.DataFrame(dict1)\ndf2 = pd.DataFrame(dict2)\nres = df1.merge(df2, on=['name'])\n id name dtype\n0 1.0 aa StringType\n1 4.0 bb StringType\n2 2.0 cc StringType\n pd.DataFrame() dict res.to_dict('records')\n [\n {'id': 1.0, 'name': 'aa', 'dtype': 'StringType'}, \n {'id': 4.0, 'name': 'bb', 'dtype': 'StringType'}, \n {'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}\n]\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14882883/" ]
74,600,794
<p>Who will help me with the code?</p> <p>I have a json file that looks like this:</p> <pre><code>{&quot;entries&quot;: [{&quot;attributes&quot;: {&quot;cn&quot;: [&quot;John Doe&quot;], &quot;lastLogon&quot;: [&quot;133137573913265630&quot;], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;4096&quot;]},&quot;dn&quot;: &quot;CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot;}, {&quot;attributes&quot;: {&quot;cn&quot;: [&quot;Jane Doe&quot;], &quot;lastLogon&quot;: [], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;514&quot;]}, &quot;dn&quot;: &quot;CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot;}]} </code></pre> <p>which I create with the json module</p> <pre><code>for dc in dcList: LDAP_HOST = dc['hostName'] def ldap_server(): return Server(LDAP_HOST, use_ssl=True, tls=tls_configuration, get_info=ALL_ATTRIBUTES) conn = ldap_connection() conn.search(LDAP_BASE_DN, LDAP_OBJECT_FILTER, attributes=user_attr_list) ### write data from addc to JSON file jsonFile = rootPath + dataPath + LDAP_HOST +&quot;-&quot;+ jsonUsersData data = json.loads(conn.response_to_json()) with open(jsonFile, 'w') as f: json.dump(data, f) </code></pre> <p>I would like the file to look more readable, for example:</p> <pre><code>{ &quot;entries&quot;: [ { &quot;attributes&quot;: { &quot;cn&quot;: [&quot;John Doe&quot;], &quot;lastLogon&quot;: [&quot;133137573913265630&quot;], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;4096&quot;] }, &quot;dn&quot;: &quot;CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot; }, { &quot;attributes&quot;: { &quot;cn&quot;: [&quot;Jane Doe&quot;], &quot;lastLogon&quot;: [], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;514&quot;] }, &quot;dn&quot;: &quot;CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot; } ] } </code></pre> <p>and ideally, the file should be converted to the following format:</p> <pre><code>&quot;users&quot;: [ { &quot;cn&quot;: [&quot;John Doe&quot;], &quot;lastLogon&quot;: [&quot;133137573913265630&quot;], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;4096&quot;] &quot;dn&quot;: &quot;CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot; }, { &quot;cn&quot;: [&quot;Jane Doe&quot;], &quot;lastLogon&quot;: [], &quot;sn&quot;: [&quot;Doe&quot;], &quot;userAccountControl&quot;: [&quot;514&quot;] &quot;dn&quot;: &quot;CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local&quot; } ] } </code></pre>
[ { "answer_id": 74600949, "author": "Filip Niko", "author_id": 12193952, "author_profile": "https://Stackoverflow.com/users/12193952", "pm_score": 2, "selected": false, "text": "json.dump json.dump(data, indent=2) json.dump json.dump" }, { "answer_id": 74601000, "author": "Shubham Shah", "author_id": 8872644, "author_profile": "https://Stackoverflow.com/users/8872644", "pm_score": 0, "selected": false, "text": "json.dump(data, f,indent=4,sort_keys=True)" }, { "answer_id": 74601083, "author": "arozx", "author_id": 18544796, "author_profile": "https://Stackoverflow.com/users/18544796", "pm_score": 0, "selected": false, "text": "import json\n\njson_string='SOME_JSON_HERE'\n\ntry:\n parsed_json=json.loads(json_string)\n out=(json.dumps(parsed_json, indent=4,sort_keys=False))\n print(out)\nexcept Exception as e:\n print(repr(e))\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20164393/" ]
74,600,797
<p>I am using the CodeMirror plugin with version 5.65.7 for my textarea in a web application based on Vuejs, and everything is working fine without any issues. I would like to add the placeholder to my textarea, so I have added the respective placeholder file to my application and can see the placeholder in my textarea.</p> <p>I would like to change the font color of the placeholder and centre align it, so I tried to make some modifications to the codemirror styles, but for some reason it’s not working at all. Could you please tell me how to change the font colour and centre the placeholder for the CodeMirror-controlled textarea?</p> <p>I looked at a similar question <a href="https://discuss.codemirror.net/t/placeholder-font-color/3453" rel="nofollow noreferrer">here</a>: Placeholder font colour&quot; and tried to do the same, but for some reason it’s not working.</p> <p>I have created a sample project based on my real application to demonstrate the issue in <a href="https://codesandbox.io/s/cocky-matan-kvqnu?file=/pages/index.vue" rel="nofollow noreferrer">CodeSandBox</a>.</p> <p>I tried to look into devtools and tried but it's not working as expected. Can someone please let me know what I'm doing wrong and provide some workaround?</p> <p>Following is the code sample which is also available in CodeSandBox:</p> <pre><code>&lt;template&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-5 offset-md-1 mt-5 mr-2 mb-2 pt-2&quot;&gt; &lt;textarea id=&quot;jsonEvents&quot; ref=&quot;jsonEvents&quot; v-model=&quot;jsonEvents&quot; class=&quot;form-control&quot; placeholder=&quot;Document in JSON format&quot; spellcheck=&quot;false&quot; data-gramm=&quot;false&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-md-5 offset-md-1 mt-5 mr-2 mb-2 pt-2&quot;&gt; &lt;textarea id=&quot;xmlEvents&quot; ref=&quot;xmlEvents&quot; v-model=&quot;xmlEvents&quot; class=&quot;form-control&quot; placeholder=&quot;Document in XML format&quot; spellcheck=&quot;false&quot; data-gramm=&quot;false&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; let CodeMirror = null; if (typeof window !== &quot;undefined&quot; &amp;&amp; typeof window.navigator !== &quot;undefined&quot;) { CodeMirror = require(&quot;codemirror&quot;); require(&quot;codemirror/mode/xml/xml.js&quot;); require(&quot;codemirror/mode/javascript/javascript.js&quot;); require(&quot;codemirror/lib/codemirror.css&quot;); require(&quot;codemirror/addon/lint/lint.js&quot;); require(&quot;codemirror/addon/lint/lint.css&quot;); require(&quot;codemirror/addon/lint/javascript-lint.js&quot;); require(&quot;codemirror/addon/hint/javascript-hint.js&quot;); require(&quot;codemirror/addon/display/placeholder.js&quot;); } export default { name: &quot;Converter&quot;, components: {}, data() { return { xmlEvents: &quot;&quot;, jsonEvents: &quot;&quot;, xmlEditor: null, jsonEditor: null, }; }, mounted() { // Make the XML textarea CodeMirror this.xmlEditor = CodeMirror.fromTextArea(this.$refs.xmlEvents, { mode: &quot;application/xml&quot;, beautify: { initialBeautify: true, autoBeautify: true }, lineNumbers: true, indentWithTabs: true, autofocus: true, tabSize: 2, gutters: [&quot;CodeMirror-lint-markers&quot;], lint: true, autoCloseBrackets: true, autoCloseTags: true, styleActiveLine: true, styleActiveSelected: true, }); // Set the height for the XML CodeMirror this.xmlEditor.setSize(null, &quot;75vh&quot;); // Make the JSON textarea CodeMirror this.jsonEditor = CodeMirror.fromTextArea(this.$refs.jsonEvents, { mode: &quot;applicaton/ld+json&quot;, beautify: { initialBeautify: true, autoBeautify: true }, lineNumbers: true, indentWithTabs: true, autofocus: true, tabSize: 2, gutters: [&quot;CodeMirror-lint-markers&quot;], autoCloseBrackets: true, autoCloseTags: true, styleActiveLine: true, styleActiveSelected: true, }); // Set the height for the JSON CodeMirror this.jsonEditor.setSize(null, &quot;75vh&quot;); // Add the border for all the CodeMirror textarea for (const s of document.getElementsByClassName(&quot;CodeMirror&quot;)) { s.style.border = &quot;1px solid black&quot;; } }, }; &lt;/script&gt; &lt;style&gt; textarea { height: 75vh; white-space: nowrap; resize: both; border: 1px solid black; } .cm-editor .cm-placeholder { color: red !important; text-align: center; line-height: 200px; } .CodeMirror-editor pre.CodeMirror-placeholder { color: red !important; text-align: center; line-height: 200px; } .CodeMirror-editor .CodeMirror-placeholder { color: red !important; text-align: center; line-height: 200px; } &lt;/style&gt; </code></pre>
[ { "answer_id": 74601567, "author": "DrGregoryHouse", "author_id": 9496566, "author_profile": "https://Stackoverflow.com/users/9496566", "pm_score": 0, "selected": false, "text": "textarea::placeholder {\n color: red; \n}\n" }, { "answer_id": 74601736, "author": "Lucas Santos", "author_id": 16496733, "author_profile": "https://Stackoverflow.com/users/16496733", "pm_score": 0, "selected": false, "text": "\"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"#074\" },\n .CodeMirror .cm-s-default .cm-placeholder, ::placeholder{\n color:blue;\n text-align: center;\n line-height: 120px;\n}\n #inp::placeholder{\n color: lime;\n text-align: center;\n} <input id=\"inp\" placeholder=\"placeholder\" />" }, { "answer_id": 74602879, "author": "Neha Soni", "author_id": 11834856, "author_profile": "https://Stackoverflow.com/users/11834856", "pm_score": 2, "selected": true, "text": "let placeholder_el = document.querySelectorAll('pre.CodeMirror-placeholder')[0];\nplaceholder_el.style['color'] = 'red';\nplaceholder_el.style['text-align'] = 'center';\nplaceholder_el.style['line-height'] = '200px';\n" }, { "answer_id": 74610938, "author": "BATMAN_2008", "author_id": 7584240, "author_profile": "https://Stackoverflow.com/users/7584240", "pm_score": 0, "selected": false, "text": ".CodeMirror pre.CodeMirror-placeholder{\n color: #F1948A;\n text-align: center;\n line-height: 200px;\n font-family:arial;\n font-size: 1rem;\n font-weight:400\n}\n scoped" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7584240/" ]
74,600,816
<p>If run this code on <code>iOS16</code> keyboard gets dismissed randomly when character is typed (please see gif), while on <code>iOS15</code> everything is fine.</p> <pre><code>struct ContentView: View { let names = [&quot;Holly&quot;, &quot;Josh&quot;, &quot;Rhonda&quot;, &quot;Ted&quot;] @State var text = &quot;&quot; var body: some View { List { Section { ForEach(searchResults, id: \.self) { name in Text(name) } } header: { TextField(&quot;Search for name&quot;, text: $text) } } } var searchResults: [String] { if text.isEmpty { return names } else { return names.filter { $0.contains(text) } } } } </code></pre> <p>It happens when content is in a section with a header. Is it bug from apple introduced in <code>iOS16</code> or am I doing something wrong? Has anyone had the same issue?</p> <p><a href="https://i.stack.imgur.com/tDD3e.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tDD3e.gif" alt="enter image description here" /></a></p>
[ { "answer_id": 74601567, "author": "DrGregoryHouse", "author_id": 9496566, "author_profile": "https://Stackoverflow.com/users/9496566", "pm_score": 0, "selected": false, "text": "textarea::placeholder {\n color: red; \n}\n" }, { "answer_id": 74601736, "author": "Lucas Santos", "author_id": 16496733, "author_profile": "https://Stackoverflow.com/users/16496733", "pm_score": 0, "selected": false, "text": "\"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"#074\" },\n .CodeMirror .cm-s-default .cm-placeholder, ::placeholder{\n color:blue;\n text-align: center;\n line-height: 120px;\n}\n #inp::placeholder{\n color: lime;\n text-align: center;\n} <input id=\"inp\" placeholder=\"placeholder\" />" }, { "answer_id": 74602879, "author": "Neha Soni", "author_id": 11834856, "author_profile": "https://Stackoverflow.com/users/11834856", "pm_score": 2, "selected": true, "text": "let placeholder_el = document.querySelectorAll('pre.CodeMirror-placeholder')[0];\nplaceholder_el.style['color'] = 'red';\nplaceholder_el.style['text-align'] = 'center';\nplaceholder_el.style['line-height'] = '200px';\n" }, { "answer_id": 74610938, "author": "BATMAN_2008", "author_id": 7584240, "author_profile": "https://Stackoverflow.com/users/7584240", "pm_score": 0, "selected": false, "text": ".CodeMirror pre.CodeMirror-placeholder{\n color: #F1948A;\n text-align: center;\n line-height: 200px;\n font-family:arial;\n font-size: 1rem;\n font-weight:400\n}\n scoped" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730320/" ]
74,600,817
<p>I am currently using a windows machine, and am busy with some Genetic Algorithm stuff that relies on using a PyBullet virtual environment to test out the locomotive capacity of my &quot;robots&quot;. The project I'm working on required me to use multi-threading, so my lecturer recommended that I install WSL to do so because apparently it does not work on Windows.</p> <p>I installed WSL, and created a python virtual environment to work in. Everything was perfectly fine until I tried to connect to a PyBullet server, which produced the following output:</p> <pre><code>pybullet build time: Nov 27 2022 13:20:33 startThreads creating 1 threads. starting thread 0 started thread 0 argc=2 argv[0] = --unused argv[1] = --start_demo_name=Physics Server ExampleBrowserThreadFunc started X11 functions dynamically loaded using dlopen/dlsym OK! cannot connect to X server </code></pre> <p>What can I do to fix this? Please ask if more information on my setup is needed :)</p>
[ { "answer_id": 74601567, "author": "DrGregoryHouse", "author_id": 9496566, "author_profile": "https://Stackoverflow.com/users/9496566", "pm_score": 0, "selected": false, "text": "textarea::placeholder {\n color: red; \n}\n" }, { "answer_id": 74601736, "author": "Lucas Santos", "author_id": 16496733, "author_profile": "https://Stackoverflow.com/users/16496733", "pm_score": 0, "selected": false, "text": "\"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"#074\" },\n .CodeMirror .cm-s-default .cm-placeholder, ::placeholder{\n color:blue;\n text-align: center;\n line-height: 120px;\n}\n #inp::placeholder{\n color: lime;\n text-align: center;\n} <input id=\"inp\" placeholder=\"placeholder\" />" }, { "answer_id": 74602879, "author": "Neha Soni", "author_id": 11834856, "author_profile": "https://Stackoverflow.com/users/11834856", "pm_score": 2, "selected": true, "text": "let placeholder_el = document.querySelectorAll('pre.CodeMirror-placeholder')[0];\nplaceholder_el.style['color'] = 'red';\nplaceholder_el.style['text-align'] = 'center';\nplaceholder_el.style['line-height'] = '200px';\n" }, { "answer_id": 74610938, "author": "BATMAN_2008", "author_id": 7584240, "author_profile": "https://Stackoverflow.com/users/7584240", "pm_score": 0, "selected": false, "text": ".CodeMirror pre.CodeMirror-placeholder{\n color: #F1948A;\n text-align: center;\n line-height: 200px;\n font-family:arial;\n font-size: 1rem;\n font-weight:400\n}\n scoped" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12238077/" ]
74,600,818
<pre class="lang-html prettyprint-override"><code>&lt;div fxFlex=&quot;25&quot; fxFlex.xs=&quot;100&quot; class=&quot;px-8&quot;&gt; &lt;div class=&quot;form-label&quot;&gt;Ticket Status &lt;span class=&quot;reqSgnColor&quot;&gt;*&lt;/span&gt; &lt;/div&gt; &lt;mat-form-field appearance=&quot;outline&quot;&gt; &lt;mat-select matNativeControl required formControlName=&quot;complaint_status&quot; filter=&quot;true&quot; id=&quot;comp_status&quot; name=&quot;comp_status&quot; (valueChange)=&quot;closed_over_by($event)&quot;&gt; &lt;mat-option *ngFor=&quot;let status of complnt_status&quot; [value]=&quot;status.value&quot;&gt;{{status.viewValue}} &lt;/mat-option&gt; &lt;/mat-select&gt; &lt;mat-error&gt; Select Status is Required&lt;/mat-error&gt; &lt;/mat-form-field&gt; &lt;/div&gt; </code></pre> <p><a href="https://i.stack.imgur.com/zK7bq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zK7bq.png" alt="enter image description here" /></a></p> <p>Basically I have 2 pages, in one page i need to hide a value from dropdown, and show the same value in other Page of the the dropdown. actually i have two pages &quot;Open-Complain&quot; and another is &quot;Resolve-Complaints&quot; so in that i have a button called edit button (Present on both pages Identical).When i go on Page &quot;Open-Complants&quot; in Drop down &quot;Close Option&quot; shoulnt appear and in Case of &quot;Resolve-Complaints&quot; in drop down &quot;open option shouldnt be there&quot;.on NOte When Click Edit Button Both Comes On &quot;Edit Complaint Page only&quot;.option are static.</p>
[ { "answer_id": 74601567, "author": "DrGregoryHouse", "author_id": 9496566, "author_profile": "https://Stackoverflow.com/users/9496566", "pm_score": 0, "selected": false, "text": "textarea::placeholder {\n color: red; \n}\n" }, { "answer_id": 74601736, "author": "Lucas Santos", "author_id": 16496733, "author_profile": "https://Stackoverflow.com/users/16496733", "pm_score": 0, "selected": false, "text": "\"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"#074\" },\n .CodeMirror .cm-s-default .cm-placeholder, ::placeholder{\n color:blue;\n text-align: center;\n line-height: 120px;\n}\n #inp::placeholder{\n color: lime;\n text-align: center;\n} <input id=\"inp\" placeholder=\"placeholder\" />" }, { "answer_id": 74602879, "author": "Neha Soni", "author_id": 11834856, "author_profile": "https://Stackoverflow.com/users/11834856", "pm_score": 2, "selected": true, "text": "let placeholder_el = document.querySelectorAll('pre.CodeMirror-placeholder')[0];\nplaceholder_el.style['color'] = 'red';\nplaceholder_el.style['text-align'] = 'center';\nplaceholder_el.style['line-height'] = '200px';\n" }, { "answer_id": 74610938, "author": "BATMAN_2008", "author_id": 7584240, "author_profile": "https://Stackoverflow.com/users/7584240", "pm_score": 0, "selected": false, "text": ".CodeMirror pre.CodeMirror-placeholder{\n color: #F1948A;\n text-align: center;\n line-height: 200px;\n font-family:arial;\n font-size: 1rem;\n font-weight:400\n}\n scoped" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19807996/" ]
74,600,832
<p>I wanted to find similar items in a list with slightly lower or higher values ​​(0.01 or -0.01) but up to 0.1, example:</p> <pre><code>real_list = [1.94, 4.72, 8.99, 5.37, 1.33] list_2 = [1.86, 4.78, 8.91, 5.41, 1.30] </code></pre> <p>you can see that the values ​​of the two lists are similar, but they are not found in an if, example:</p> <pre><code> for i in list_2: if i in real_list: print(&quot;found&quot;) else: print(&quot;not found&quot;) </code></pre> <p>this code returns me this</p> <pre><code>not found not found not found not found not found </code></pre> <p>I tried to make some modifications but I wanted it to do some combinations decreasing and increasing values ​​in different parts until it found the value in the other list, example:</p> <pre><code>list_2 = [1.86, 4.78, 8.91, 5.41, 1.30] 1.85 4.77 8.9 5.4 1.29 1.84 4.76 </code></pre> <p>or increase the values ​​until you find it in the list, remembering that it has to be close to 0.1 and nothing more, in short is to find similar values ​​in a list.</p> <p>Can someone help me?</p>
[ { "answer_id": 74600875, "author": "LeoE", "author_id": 9227188, "author_profile": "https://Stackoverflow.com/users/9227188", "pm_score": 2, "selected": true, "text": "real_list = [1.94, 4.72, 8.99, 5.37, 1.33]\nlist_2 = [1.86, 4.78, 8.91, 5.41, 1.30]\nthreshold = 0.1\nfor i in list_2:\n found = False\n for j in real_list:\n if abs(i-j) <= threshold:\n print(\"found\")\n found = True\n break\n if not found:\n print(\"not found\")\n" }, { "answer_id": 74600914, "author": "João Vítor Rios Fuck", "author_id": 19402498, "author_profile": "https://Stackoverflow.com/users/19402498", "pm_score": -1, "selected": false, "text": "real_list = [1.94, 4.72, 8.99, 5.37, 1.33]\nlist_2 = [1.86, 4.78, 8.91, 5.41, 1.30]\n\nfor x in real_list:\n for y in list_2:\n\n if abs(x-y)<0.1:\n print(\"found\",x, \"is close to\",y)\n else:\n print(\"not found\")\n" }, { "answer_id": 74601621, "author": "Lutz", "author_id": 11988351, "author_profile": "https://Stackoverflow.com/users/11988351", "pm_score": 1, "selected": false, "text": "import numpy as np\nreal_list = np.array([1.94, 4.72, 8.99, 5.37, 1.33])\nlist_2 = [1.86, 4.78, 8.91, 5.41, 1.30]\n[\"found\" if np.any(np.isclose(x,real_list,atol=0.04)) else \"not found\" for x in list_2]\n atol rtol" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20353376/" ]
74,600,833
<p>I have an array that inside it has several other arrays.</p> <p>What I need is to find the array that has an object with <code>name: &quot;tax-payer-identification&quot;</code>. Change the variable's value <code>required: true</code> to <code>false</code>.</p> <p>But the problem is that it's an array of arrays and I don't know how to manipulate it, change the variable value, and return the array to be used.</p> <p>Can you tell me how can I do this? Thank you very much for any help.</p> <p><a href="https://i.stack.imgur.com/mfMU0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mfMU0.png" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react"; import { data } from "./data"; import "./styles.css"; const App = () =&gt; { const getData = () =&gt; { data.map((item) =&gt; item.map((item2) =&gt; console.log(item2))); }; console.log(getData()); return &lt;div&gt;App&lt;/div&gt;; }; export default App;</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>export const data = [ [{ // some data }], [{ // some data }, { // some data } ], [{ // some data }], [{ name: "tax-payer-identification", type: "text", regex: "^.{0,20}$", inputName: "vatNumber", required: true, maxLength: 20, minLength: 0 }], [{ // some data }], [{ // some data }], [{ // some data }, { // some data } ], [{ // some data }, { // some data } ] ];</code></pre> </div> </div> </p>
[ { "answer_id": 74600945, "author": "JSEvgeny", "author_id": 6131368, "author_profile": "https://Stackoverflow.com/users/6131368", "pm_score": 3, "selected": true, "text": "const output = data.map(item => item.map(nested => {\n if (nested.name === \"tax-payer-identification\") {\n nested.required = true\n }\n return nested\n}))\n" }, { "answer_id": 74605638, "author": "Jay F.", "author_id": 20504019, "author_profile": "https://Stackoverflow.com/users/20504019", "pm_score": 0, "selected": false, "text": "array const updateArray = (dataArray, updates = {}) => {\n let result = [];\n\n const updateApply = (objData) => {\n if (updates && Object.keys(updates).length > 0) {\n Object.keys(updates).map((key) => {\n if (objData.hasOwnProperty(key)) {\n objData[key] = updates[key];\n }\n });\n }\n\n return objData;\n };\n\n for (const index in dataArray) {\n if (Array.isArray(dataArray[index])) {\n result[index] = dataArray[index].map((e) => {\n return Array.isArray(e)\n ? updateArray([...e], updates)\n : updateApply(e);\n });\n } else {\n result[index] = updateApply(dataArray[index]);\n }\n }\n\n return result;\n};\n updateArray(data, { require: false });\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19105436/" ]
74,600,862
<p>I'm just trying to update the website application designed with <strong>Angular</strong> and got this error. I think there's something I'm missing but I couldn't find. <a href="https://i.stack.imgur.com/nRCim.png" rel="nofollow noreferrer">code-simples</a></p> <pre><code>&quot;C:\Program Files\nodejs\npm.cmd&quot; install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @agm/core@3.0.0-beta.0 npm ERR! Found: @angular/common@15.0.1 npm ERR! node_modules/@angular/common npm ERR! @angular/common@&quot;15.0.1&quot; from the root project npm ERR! peer @angular/common@&quot;^14.0.0 || ^15.0.0&quot; from @angular/cdk@14.2.1 npm ERR! node_modules/@angular/cdk npm ERR! @angular/cdk@&quot;14.2.1&quot; from the root project npm ERR! peer @angular/cdk@&quot;14.2.1&quot; from @angular/material@14.2.1 npm ERR! node_modules/@angular/material npm ERR! @angular/material@&quot;14.2.1&quot; from the root project npm ERR! 2 more (@angular/material-moment-adapter, mat-table-exporter) npm ERR! 3 more (@swimlane/ngx-charts, mat-table-exporter, cdk-table-exporter) npm ERR! 17 more (@angular/flex-layout, @angular/forms, ...) npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/common@&quot;^9.1.0 || ^10.0.0&quot; from @agm/core@3.0.0-beta.0 npm ERR! node_modules/@agm/core npm ERR! @agm/core@&quot;3.0.0-beta.0&quot; from the root project npm ERR! npm ERR! Conflicting peer dependency: @angular/common@10.2.5 npm ERR! node_modules/@angular/common npm ERR! peer @angular/common@&quot;^9.1.0 || ^10.0.0&quot; from @agm/core@3.0.0-beta.0 npm ERR! node_modules/@agm/core npm ERR! @agm/core@&quot;3.0.0-beta.0&quot; from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See C:\Users\ardac\AppData\Local\npm-cache\eresolve-report.txt for a full report. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\ardac\AppData\Local\npm-cache\_logs\2022-11-28T12_42_43_429Z-debug-0.log Process finished with exit code 1 </code></pre> <p>I'm trying to do Angular documentation rules one by one</p>
[ { "answer_id": 74600945, "author": "JSEvgeny", "author_id": 6131368, "author_profile": "https://Stackoverflow.com/users/6131368", "pm_score": 3, "selected": true, "text": "const output = data.map(item => item.map(nested => {\n if (nested.name === \"tax-payer-identification\") {\n nested.required = true\n }\n return nested\n}))\n" }, { "answer_id": 74605638, "author": "Jay F.", "author_id": 20504019, "author_profile": "https://Stackoverflow.com/users/20504019", "pm_score": 0, "selected": false, "text": "array const updateArray = (dataArray, updates = {}) => {\n let result = [];\n\n const updateApply = (objData) => {\n if (updates && Object.keys(updates).length > 0) {\n Object.keys(updates).map((key) => {\n if (objData.hasOwnProperty(key)) {\n objData[key] = updates[key];\n }\n });\n }\n\n return objData;\n };\n\n for (const index in dataArray) {\n if (Array.isArray(dataArray[index])) {\n result[index] = dataArray[index].map((e) => {\n return Array.isArray(e)\n ? updateArray([...e], updates)\n : updateApply(e);\n });\n } else {\n result[index] = updateApply(dataArray[index]);\n }\n }\n\n return result;\n};\n updateArray(data, { require: false });\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20520132/" ]
74,600,888
<pre><code>li=[22 , True , 22/7 , {&quot;Staat&quot;:&quot;Deutschland&quot; , &quot;Stadt&quot; : &quot;Berlin&quot;} , 69 , [&quot;Python&quot; , &quot;C++&quot; , &quot;C#&quot;] , (&quot;Kairo&quot; , &quot;Berlin&quot; , &quot;Amsterdam&quot;) , False , &quot;Apfel&quot; , 55 ] </code></pre> <p>How can I sort this list in multiple lists , one list for each data type (int , str , dict, etc..)</p> <pre><code>for x in li: if type(x) == float: double = x print(&quot;double&quot; ,double ) elif type(x) == str: strings = x print(&quot;strings&quot; ,strings) </code></pre> <pre><code>it is too long , and its does not combine similar data in one list </code></pre>
[ { "answer_id": 74601018, "author": "Lutz", "author_id": 11988351, "author_profile": "https://Stackoverflow.com/users/11988351", "pm_score": 1, "selected": false, "text": "lists_by_type={};\nfor x in li:\n print (x)\n if type(x) in lists_by_type.keys():\n lists_by_type[type(x)].append(x)\n else:\n lists_by_type[type(x)]=[x]\n {int: [22, 69, 55],\n bool: [True, False],\n float: [3.142857142857143],\n dict: [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}],\n list: [['Python', 'C++', 'C#']],\n tuple: [('Kairo', 'Berlin', 'Amsterdam')],\n str: ['Apfel']}\n" }, { "answer_id": 74601132, "author": "burak", "author_id": 18519656, "author_profile": "https://Stackoverflow.com/users/18519656", "pm_score": 1, "selected": true, "text": "li=[22 , True , 22/7 , {\"Staat\":\"Deutschland\" , \"Stadt\" : \"Berlin\"} , 69 \n , [\"Python\" , \"C++\" , \"C#\"] ,\n (\"Kairo\" , \"Berlin\" , \"Amsterdam\") , False , \"Apfel\" , 55 ]\n\n\n# this function groups elements by type\ndef group(lists):\n groups = dict()\n for i in lists:\n a = str(type(i)).split(\" \")\n typ = a[1][1:-2]\n if typ in groups.keys():\n groups[typ].append(i)\n else:\n groups[typ] = [i]\n return groups\n\n\nprint(group(li))\n {'int': [22, 69, 55], 'bool': [True, False], 'float': [3.142857142857143], 'dict': [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}], 'list': [['Python', 'C++', 'C#']], 'tuple': [('Kairo', 'Berlin', 'Amsterdam')], 'str': ['Apfel']}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623543/" ]
74,600,902
<p>I recently created a unit test project(.net framework) in my project(.net framework 4.8). I run my tests with visual studio <a href="https://i.stack.imgur.com/21hdq.png" rel="nofollow noreferrer">enter image description here</a>. now wanna add a stage to my ci/cd on gitlab to run my tests. I know how to do that in .net (dotnet test) but I don't know how to run my tests for .net framework with command line</p> <p>I'll be happy to know your solutions. Tnx</p>
[ { "answer_id": 74601018, "author": "Lutz", "author_id": 11988351, "author_profile": "https://Stackoverflow.com/users/11988351", "pm_score": 1, "selected": false, "text": "lists_by_type={};\nfor x in li:\n print (x)\n if type(x) in lists_by_type.keys():\n lists_by_type[type(x)].append(x)\n else:\n lists_by_type[type(x)]=[x]\n {int: [22, 69, 55],\n bool: [True, False],\n float: [3.142857142857143],\n dict: [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}],\n list: [['Python', 'C++', 'C#']],\n tuple: [('Kairo', 'Berlin', 'Amsterdam')],\n str: ['Apfel']}\n" }, { "answer_id": 74601132, "author": "burak", "author_id": 18519656, "author_profile": "https://Stackoverflow.com/users/18519656", "pm_score": 1, "selected": true, "text": "li=[22 , True , 22/7 , {\"Staat\":\"Deutschland\" , \"Stadt\" : \"Berlin\"} , 69 \n , [\"Python\" , \"C++\" , \"C#\"] ,\n (\"Kairo\" , \"Berlin\" , \"Amsterdam\") , False , \"Apfel\" , 55 ]\n\n\n# this function groups elements by type\ndef group(lists):\n groups = dict()\n for i in lists:\n a = str(type(i)).split(\" \")\n typ = a[1][1:-2]\n if typ in groups.keys():\n groups[typ].append(i)\n else:\n groups[typ] = [i]\n return groups\n\n\nprint(group(li))\n {'int': [22, 69, 55], 'bool': [True, False], 'float': [3.142857142857143], 'dict': [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}], 'list': [['Python', 'C++', 'C#']], 'tuple': [('Kairo', 'Berlin', 'Amsterdam')], 'str': ['Apfel']}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623556/" ]
74,600,909
<p>I'm developing online clothing store on Django. Now I faced the issue: I have a form which helps user to add to his cart some clothes. I need to show which sizes of this clothes are avaliable. To do this, I need to refer to the database. But how to do it from the form?</p> <p>models.py:</p> <pre><code>from django.db import models from django.urls import reverse from multiselectfield import MultiSelectField class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.FileField(blank=True, upload_to=get_upload_path) SIZE_CHOICES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('XL', 'XL'), ('XXL', 'XXL')) sizes = MultiSelectField(choices=SIZE_CHOICES, max_choices=6, max_length=17) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) </code></pre> <p>my form:</p> <p>forms.py</p> <pre><code>from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) # size = ?? </code></pre> <p>the view which uses this form:</p> <p>views.py</p> <pre><code>def product_detail(request: WSGIRequest, product_id: int, product_slug: str) -&gt; HttpResponse: product = get_object_or_404(Product, id=product_id, slug=product_slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'shop/product/detail.html', {'product': product, 'cart_product_form': cart_product_form}) </code></pre> <p>shop/product/detail.html:</p> <pre><code>{% extends &quot;shop/base.html&quot; %} &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Detail&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {% block content %} &lt;br&gt; &lt;b&gt;{{ product.name }} &lt;/b&gt; &lt;br&gt; &lt;i&gt;{{ product.description }} &lt;/i&gt; &lt;br&gt; {{ product.price }} &lt;br&gt; &lt;img src=&quot;{{ product.image.url }}&quot; width=&quot;300&quot; height=&quot;500&quot;&gt; &lt;br&gt; Available sizes: &lt;br&gt; {{ product.sizes }}&lt;br&gt; &lt;form action=&quot;{% url &quot;cart:add_to_cart&quot; product.id %}&quot; method=&quot;post&quot;&gt; {{ cart_product_form }} {% csrf_token %} &lt;input type=&quot;submit&quot; value=&quot;Add to cart&quot;&gt; &lt;/form&gt; {% endblock %} &lt;/body&gt; </code></pre> <p>I tried to create a function which gets avaliable sizes and send to the form:</p> <p>forms.py</p> <pre><code>def get_sizes(product: Product): return product.sizes </code></pre> <p>But to do this I need to refer to the Product from the form, I don't know how to do it.</p>
[ { "answer_id": 74601018, "author": "Lutz", "author_id": 11988351, "author_profile": "https://Stackoverflow.com/users/11988351", "pm_score": 1, "selected": false, "text": "lists_by_type={};\nfor x in li:\n print (x)\n if type(x) in lists_by_type.keys():\n lists_by_type[type(x)].append(x)\n else:\n lists_by_type[type(x)]=[x]\n {int: [22, 69, 55],\n bool: [True, False],\n float: [3.142857142857143],\n dict: [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}],\n list: [['Python', 'C++', 'C#']],\n tuple: [('Kairo', 'Berlin', 'Amsterdam')],\n str: ['Apfel']}\n" }, { "answer_id": 74601132, "author": "burak", "author_id": 18519656, "author_profile": "https://Stackoverflow.com/users/18519656", "pm_score": 1, "selected": true, "text": "li=[22 , True , 22/7 , {\"Staat\":\"Deutschland\" , \"Stadt\" : \"Berlin\"} , 69 \n , [\"Python\" , \"C++\" , \"C#\"] ,\n (\"Kairo\" , \"Berlin\" , \"Amsterdam\") , False , \"Apfel\" , 55 ]\n\n\n# this function groups elements by type\ndef group(lists):\n groups = dict()\n for i in lists:\n a = str(type(i)).split(\" \")\n typ = a[1][1:-2]\n if typ in groups.keys():\n groups[typ].append(i)\n else:\n groups[typ] = [i]\n return groups\n\n\nprint(group(li))\n {'int': [22, 69, 55], 'bool': [True, False], 'float': [3.142857142857143], 'dict': [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}], 'list': [['Python', 'C++', 'C#']], 'tuple': [('Kairo', 'Berlin', 'Amsterdam')], 'str': ['Apfel']}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11115592/" ]
74,600,916
<p><a href="https://i.stack.imgur.com/rcBqS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rcBqS.png" alt="enter image description here" /></a></p> <p>The column consist of minutes that is in the decimal format. This is to be converted to Time format.</p> <p><strong>Example:</strong> The 5th record is 61 minutes and 6 seconds.</p> <p>This is to be displayed as 1 hour, 1 minute and 6 seconds - (01:01:06).</p> <p>How to solve this problem in power query editor/ power BI?</p>
[ { "answer_id": 74601018, "author": "Lutz", "author_id": 11988351, "author_profile": "https://Stackoverflow.com/users/11988351", "pm_score": 1, "selected": false, "text": "lists_by_type={};\nfor x in li:\n print (x)\n if type(x) in lists_by_type.keys():\n lists_by_type[type(x)].append(x)\n else:\n lists_by_type[type(x)]=[x]\n {int: [22, 69, 55],\n bool: [True, False],\n float: [3.142857142857143],\n dict: [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}],\n list: [['Python', 'C++', 'C#']],\n tuple: [('Kairo', 'Berlin', 'Amsterdam')],\n str: ['Apfel']}\n" }, { "answer_id": 74601132, "author": "burak", "author_id": 18519656, "author_profile": "https://Stackoverflow.com/users/18519656", "pm_score": 1, "selected": true, "text": "li=[22 , True , 22/7 , {\"Staat\":\"Deutschland\" , \"Stadt\" : \"Berlin\"} , 69 \n , [\"Python\" , \"C++\" , \"C#\"] ,\n (\"Kairo\" , \"Berlin\" , \"Amsterdam\") , False , \"Apfel\" , 55 ]\n\n\n# this function groups elements by type\ndef group(lists):\n groups = dict()\n for i in lists:\n a = str(type(i)).split(\" \")\n typ = a[1][1:-2]\n if typ in groups.keys():\n groups[typ].append(i)\n else:\n groups[typ] = [i]\n return groups\n\n\nprint(group(li))\n {'int': [22, 69, 55], 'bool': [True, False], 'float': [3.142857142857143], 'dict': [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}], 'list': [['Python', 'C++', 'C#']], 'tuple': [('Kairo', 'Berlin', 'Amsterdam')], 'str': ['Apfel']}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20061934/" ]
74,600,965
<h1>What is the best way to replace a specific portion of a vector with a new vector?</h1> <p>As of now, I am using hardcoded code to replace the vector. What is the most effective way to achieve this?</p> <pre class="lang-rust prettyprint-override"><code>fn main() { let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let u = vec![0,0,0,0]; v[2] = u[0]; v[3] = u[1]; v[4] = u[2]; v[5] = u[3]; println!(&quot;v = {:?}&quot;, v); } </code></pre> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=aa12319863bf39fe0241a73a2fabe0ce" rel="nofollow noreferrer">Permalink to the playground</a></p> <p>Is there any function to replace the vector with given indices?</p>
[ { "answer_id": 74601143, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 4, "selected": true, "text": "Copy v[2..][..u.len()].copy_from_slice(&u);\n Copy v.splice(2..2 + u.len(), u);\n" }, { "answer_id": 74601223, "author": "RIJIK", "author_id": 5044463, "author_profile": "https://Stackoverflow.com/users/5044463", "pm_score": 1, "selected": false, "text": "let offset : usize = 2;\nu.iter().enumerate().for_each(|(index, &val)| {\n v[index + offset] = val;\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8326080/" ]
74,600,972
<p>I have <code>MY_OBJ_TABLE</code> type and would like to dump variable content of such either into text or xml format.</p> <p>The thing is, function processing such request should be able to receive any type of <code>table of objects</code>, not just the <code>MY_OBJ_TABLE</code>.</p> <p>I have looked into <a href="https://github.com/ReneNyffenegger/Oracle-patterns/blob/master/Installed/types/any/passAnyObject/passAnyObject.sql" rel="nofollow noreferrer">passAnyObject.sql</a> which looks like a step in the right direction. Advices and solutions are greatly appreciated.</p> <pre><code>CREATE OR REPLACE TYPE &quot;MY_OBJ&quot; FORCE AS OBJECT ( key VARCHAR2(20), value VARCHAR2(1000), CONSTRUCTOR FUNCTION MY_OBJ RETURN SELF AS RESULT, MEMBER PROCEDURE init_my_obj ); CREATE OR REPLACE TYPE BODY &quot;MY_OBJ&quot; AS CONSTRUCTOR FUNCTION MY_OBJ RETURN SELF AS RESULT AS BEGIN init_my_obj (); return; END MY_OBJ; MEMBER PROCEDURE init_my_obj AS BEGIN key := NULL; value := NULL; END init_my_obj; END; CREATE OR REPLACE TYPE MY_OBJ_TABLE IS TABLE OF MY_OBJ; </code></pre>
[ { "answer_id": 74601143, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 4, "selected": true, "text": "Copy v[2..][..u.len()].copy_from_slice(&u);\n Copy v.splice(2..2 + u.len(), u);\n" }, { "answer_id": 74601223, "author": "RIJIK", "author_id": 5044463, "author_profile": "https://Stackoverflow.com/users/5044463", "pm_score": 1, "selected": false, "text": "let offset : usize = 2;\nu.iter().enumerate().for_each(|(index, &val)| {\n v[index + offset] = val;\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74600972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223226/" ]
74,601,010
<p>Using <strong>Bootstrap 5</strong>. I have a card to display brand info and button on right to navigate.</p> <p><a href="https://i.stack.imgur.com/25QVr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/25QVr.png" alt="enter image description here" /></a></p> <p>When the description content is short, the button looks good, in one line. But as the description length is increased, the button is broken in multiple lines</p> <p><a href="https://i.stack.imgur.com/uxdMQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uxdMQ.png" alt="enter image description here" /></a></p> <p>I want to have the button width in one-line only and width adjusted according to the inside content and the description content to be adjusted in the left over space.</p> <p>Is it possible to achieve it using <code>flex</code>?</p> <p>Codepen link <a href="https://codepen.io/anuj9196/pen/mdKjeEq" rel="nofollow noreferrer">https://codepen.io/anuj9196/pen/mdKjeEq</a></p> <p>I tried setting fixed with to the button, but then the button size does not adjust according to it's inner content. Also tried putting <code>&lt;br&gt;</code> tab in the description content, but then on large screen, too much space is left blank.</p>
[ { "answer_id": 74601143, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 4, "selected": true, "text": "Copy v[2..][..u.len()].copy_from_slice(&u);\n Copy v.splice(2..2 + u.len(), u);\n" }, { "answer_id": 74601223, "author": "RIJIK", "author_id": 5044463, "author_profile": "https://Stackoverflow.com/users/5044463", "pm_score": 1, "selected": false, "text": "let offset : usize = 2;\nu.iter().enumerate().for_each(|(index, &val)| {\n v[index + offset] = val;\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719167/" ]
74,601,011
<p>I have created a ResourceDictionary file that comes with a .cs file. So afer creating the ResourceDictionary file I'm getting an error The name 'InitializeComponent' does not exist in the current context.</p> <p><a href="https://i.stack.imgur.com/B71zw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B71zw.png" alt="Error Screenshot" /></a></p> <p>Below is the xaml file associated with the above file.</p> <p><a href="https://i.stack.imgur.com/ivsWV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ivsWV.png" alt="enter image description here" /></a></p> <p>I'm using VS2022 17.5.0 Preview 1.0</p> <ol> <li>I have set the build action for the c# file to C# Compiler</li> <li>I have cleaned and rebuilt my project several times and tried deleting the bin and obj folders nothing seems to work</li> </ol>
[ { "answer_id": 74609080, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 3, "selected": true, "text": "Project / rt-click / Add / NewItem / .Net Maui ResourceDictionary (XAML) <MauiXaml Update=\"Dictionary1.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n Compile MauiXaml Dictionary1.xaml Dictionary1.xaml.cs MauiXaml <ItemGroup>\n <None Include=\"Themes\\Light.xaml\" />\n</ItemGroup>\n <ItemGroup>\n <MauiXaml Update=\"Themes\\Light.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n</ItemGroup>\n <ItemGroup>\n <Folder Include=\"Themes\\\" />\n</ItemGroup>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5402232/" ]
74,601,031
<p>So I need to have the name as a column and then also street but it doesn't work.</p> <p>I tried this</p> <pre><code>SELECT naam, straat FROM activiteit GROUP BY naam HAVING COUNT(*)&gt;1; </code></pre> <p>expected to have this</p> <pre><code>naam | straat | --------+--------+ tennis | Gent | basket | Antwerpen | </code></pre> <p>but got this</p> <pre><code>column &quot;activiteit.straat&quot; must appear in the GROUP BY clause or be used in an aggregate function </code></pre>
[ { "answer_id": 74609080, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 3, "selected": true, "text": "Project / rt-click / Add / NewItem / .Net Maui ResourceDictionary (XAML) <MauiXaml Update=\"Dictionary1.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n Compile MauiXaml Dictionary1.xaml Dictionary1.xaml.cs MauiXaml <ItemGroup>\n <None Include=\"Themes\\Light.xaml\" />\n</ItemGroup>\n <ItemGroup>\n <MauiXaml Update=\"Themes\\Light.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n</ItemGroup>\n <ItemGroup>\n <Folder Include=\"Themes\\\" />\n</ItemGroup>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20349656/" ]
74,601,050
<p>I have a project where I have two GitHub actions yml file where the first file is called build.yml and it contains instructions to compile, build and test the project. It is as simple as this:</p> <pre><code>name: build my-project on: push: paths-ignore: - 'images/**' - README.md branches: - master pull_request: branches: - master release: types: [ created ] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: cache ivy2 uses: actions/cache@v1 with: path: ~/.ivy2/cache key: ${{ runner.os }}-sbt-ivy-cache-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }} - name: sbt Test run: sbt clean test </code></pre> <p>I now have another yml file that contains the instructions to do a release based on annotated tags. It is like this:</p> <pre><code>name: release my-project on: push: # Sequence of patterns matched against refs/tags tags: - 'v[0-9]+.[0-9]+.[0-9]+-[a-zA-Z]*' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jobs: build: uses: ./.github/workflows/build.yml publish: runs-on: ubuntu-latest needs: test # See build.yml file where the test job is defined # If there is a tag and if that tag comes from master branch if: startsWith(github.ref, 'refs/tags/v') steps: - name: checkout uses: actions/checkout@v3 - name: capture changelog id: changelog uses: metcalfc/changelog-generator@v4.0.1 with: myToken: ${{ secrets.GITHUB_TOKEN }} - name: sbt ci-publish-github run: sbt publish - name: ci-release-github id: create-release uses: actions/create-release@latest with: allowUpdates: true tag_name: ${{ github.ref }} release_name: Release ${{ github.ref }} body: | ## What's Changed ${{ steps.changelog.outputs.changelog }} draft: false prerelease: false </code></pre> <p>I just created an annotated tag which then resulted in an error like this:</p> <pre><code>Invalid workflow file: .github/workflows/publish.yml#L14 error parsing called workflow &quot;./.github/workflows/build.yml&quot;: workflow is not reusable as it is missing a `on.workflow_call` trigger </code></pre> <p>So basically what I want is, when I push an annotated tag, I want to first run the test job from build.yml and then once that succeeds, I would like to run the publish job. Any suggestions on how to get this straight?</p>
[ { "answer_id": 74609080, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 3, "selected": true, "text": "Project / rt-click / Add / NewItem / .Net Maui ResourceDictionary (XAML) <MauiXaml Update=\"Dictionary1.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n Compile MauiXaml Dictionary1.xaml Dictionary1.xaml.cs MauiXaml <ItemGroup>\n <None Include=\"Themes\\Light.xaml\" />\n</ItemGroup>\n <ItemGroup>\n <MauiXaml Update=\"Themes\\Light.xaml\">\n <Generator>MSBuild:Compile</Generator>\n </MauiXaml>\n</ItemGroup>\n <ItemGroup>\n <Folder Include=\"Themes\\\" />\n</ItemGroup>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102968/" ]
74,601,073
<p>I have the following dataframe called df (<code>dput</code> below):</p> <pre><code> group value 1 A 4 2 A 2 3 A 4 4 A 3 5 A 1 6 A 5 7 B 3 8 B 2 9 B 1 10 B 2 11 B 2 12 B 2 </code></pre> <p>I would like to calculate the percentage of values on the mode value per group. Here is the code to calculate the mode per group:</p> <pre class="lang-r prettyprint-override"><code># Mode function mode &lt;- function(codes){ which.max(tabulate(codes)) } library(dplyr) # Calculate mode per group df %&gt;% group_by(group) %&gt;% mutate(mode_value = mode(value)) #&gt; # A tibble: 12 × 3 #&gt; # Groups: group [2] #&gt; group value mode_value #&gt; &lt;chr&gt; &lt;dbl&gt; &lt;int&gt; #&gt; 1 A 4 4 #&gt; 2 A 2 4 #&gt; 3 A 4 4 #&gt; 4 A 3 4 #&gt; 5 A 1 4 #&gt; 6 A 5 4 #&gt; 7 B 3 2 #&gt; 8 B 2 2 #&gt; 9 B 1 2 #&gt; 10 B 2 2 #&gt; 11 B 2 2 #&gt; 12 B 2 2 </code></pre> <p><sup>Created on 2022-11-28 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> <p>But I am not sure how to calculate the percentage of values on the mode per group which should look like this:</p> <pre><code> group value mode_value perc_on_mode 1 A 4 4 0.33 2 A 2 4 0.33 3 A 4 4 0.33 4 A 3 4 0.33 5 A 1 4 0.33 6 A 5 4 0.33 7 B 3 2 0.67 8 B 2 2 0.67 9 B 1 2 0.67 10 B 2 2 0.67 11 B 2 2 0.67 12 B 2 2 0.67 </code></pre> <p>So I was wondering if anyone knows how to calculate the percentage of values on the mode value per group?</p> <hr /> <p><code>dput</code> of df:</p> <pre><code>df &lt;- structure(list(group = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;), value = c(4, 2, 4, 3, 1, 5, 3, 2, 1, 2, 2, 2)), class = &quot;data.frame&quot;, row.names = c(NA, -12L)) </code></pre>
[ { "answer_id": 74601106, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 2, "selected": false, "text": "df %>%\n group_by(group) %>%\n mutate(mode_value = mode(value),\n perc_on_mode = mean(value == mode_value))\n # A tibble: 12 x 4\n# Groups: group [2]\n group value mode_value perc_on_mode\n <chr> <dbl> <int> <dbl>\n 1 A 4 4 0.333\n 2 A 2 4 0.333\n 3 A 4 4 0.333\n 4 A 3 4 0.333\n 5 A 1 4 0.333\n 6 A 5 4 0.333\n 7 B 3 2 0.667\n 8 B 2 2 0.667\n 9 B 1 2 0.667\n10 B 2 2 0.667\n11 B 2 2 0.667\n12 B 2 2 0.667\n" }, { "answer_id": 74601301, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 2, "selected": true, "text": "mode mode <- function(codes){\n tab <- tabulate(codes)\n mode_value <- which.max(tab)\n data.frame(value = codes, mode_value, perc_on_mode = tab[mode_value]/length(codes))\n}\n\n# Calculate mode per group\ndf %>%\n group_by(group) %>%\n do(mode(.$value))\n#> # A tibble: 12 x 4\n#> # Groups: group [2]\n#> group value mode_value perc_on_mode\n#> <chr> <dbl> <int> <dbl>\n#> 1 A 4 4 0.333\n#> 2 A 2 4 0.333\n#> 3 A 4 4 0.333\n#> 4 A 3 4 0.333\n#> 5 A 1 4 0.333\n#> 6 A 5 4 0.333\n#> 7 B 3 2 0.667\n#> 8 B 2 2 0.667\n#> 9 B 1 2 0.667\n#> 10 B 2 2 0.667\n#> 11 B 2 2 0.667\n#> 12 B 2 2 0.667\n data.table library(data.table)\n\nmode <- function(codes){\n tab <- tabulate(codes)\n mode_value <- which.max(tab)\n list(mode_value, tab[mode_value]/length(codes))\n}\n\nsetDT(df)[, c(\"mode_value\", \"perc_on_mode\") := mode(value), group][]\n#> group value mode_value perc_on_mode\n#> 1: A 4 4 0.3333333\n#> 2: A 2 4 0.3333333\n#> 3: A 4 4 0.3333333\n#> 4: A 3 4 0.3333333\n#> 5: A 1 4 0.3333333\n#> 6: A 5 4 0.3333333\n#> 7: B 3 2 0.6666667\n#> 8: B 2 2 0.6666667\n#> 9: B 1 2 0.6666667\n#> 10: B 2 2 0.6666667\n#> 11: B 2 2 0.6666667\n#> 12: B 2 2 0.6666667\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14282714/" ]
74,601,172
<p>Trying to get an an onclick function to delete an item (that's been clicked) from an array.</p> <p>However, it doesnt delete anything. setListOfDocs is supposed to set the listOfDocs array with the clicked item gone (onClick function is a filter)</p> <p>It does not work. There's no error in the console. I don't know why it's not updating the state so that the listOfDocs is the new filtered array (with the clicked item removed from the array).</p> <p>Im using material ui.</p> <pre class="lang-js prettyprint-override"><code> function NewMatterDocuments() { const [listOfDocs, setListOfDocs] = useState(['item1', 'item2', 'item3', 'item4']); const [disableButton, toggleDisableButton] = useState(false); const [displayTextField, toggleDisplayTextField] = useState('none'); const [textInputValue, setTextInputValue] = useState(); const buttonClick = () =&gt; { toggleDisableButton(true); toggleDisplayTextField('box'); }; //this function works const handleEnter = ({ target }) =&gt; { setTextInputValue(target.value); const newItem = target.value; setListOfDocs((prev) =&gt; { return [...prev, newItem]; }); setTextInputValue(null); }; // //this function does not work....which is weird because it pretty much // does the same thing as the previous function except it deletes an item // instead of adding it to the array. Why does the previous function work // but this one doesnt? const deleteItem = ({ currentTarget }) =&gt; { const deletedId = currentTarget.id; const result = listOfDocs.filter((item, index) =&gt; index !== deletedId); setListOfDocs(result) }; return ( &lt;div&gt; &lt;Typography variant=&quot;body2&quot;&gt; &lt;FormGroup&gt; &lt;Grid container spacing={3}&gt; &lt;Grid item xs={6}&gt; &lt;Grid item xs={6}&gt; Document Type &lt;/Grid&gt; {listOfDocs.map((item, index) =&gt; { return ( &lt;ListItem id={index} secondaryAction={&lt;Checkbox /&gt;}&gt; &lt;ListItemAvatar&gt; &lt;Avatar&gt; &lt;DeleteIcon id={index} onClick={deleteItem} /&gt; &lt;/Avatar&gt; &lt;/ListItemAvatar&gt; &lt;ListItemButton&gt; &lt;ListItemText id={index} primary={item} /&gt; &lt;/ListItemButton&gt; &lt;/ListItem&gt; ); })} &lt;List sx={{ width: '100%', bgcolor: 'background.paper' }}&gt; &lt;Button disabled={!disableButton ? false : true} color=&quot;inherit&quot; onClick={buttonClick}&gt; Add &lt;/Button&gt; &lt;ListItem sx={{ display: `${displayTextField}` }} id={uuid()} key={uuid()}&gt; &lt;TextField id=&quot;standard-basic&quot; label=&quot;Additional Document&quot; variant=&quot;standard&quot; value={textInputValue} onKeyDown={(e) =&gt; { e.key === 'Enter' &amp;&amp; handleEnter(e); }} &gt;&lt;/TextField&gt; &lt;/ListItem&gt; &lt;/List&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/FormGroup&gt; &lt;/Typography&gt; &lt;/div&gt; ); } export default NewMatterDocuments; </code></pre> <p>I tried to change the function that wasnt working into the following:</p> <pre class="lang-js prettyprint-override"><code>const deleteItem = ({ currentTarget }) =&gt; { setListOfDocs((prev) =&gt; { prev.filter((item, index) =&gt; index != currentTarget.id); }); }; </code></pre> <p>It gives the error &quot;Uncaught TypeError: Cannot read properties of undefined (reading 'map')&quot; The next map function inside the jsx doesnt work...</p>
[ { "answer_id": 74601463, "author": "Jérémy Rippert", "author_id": 20293448, "author_profile": "https://Stackoverflow.com/users/20293448", "pm_score": 0, "selected": false, "text": "const deleteItem = ({ currentTarget }) => {\n const deletedId = currentTarget.id;\n const result = listOfDocs.filter((item, index) => item !== deletedId); \n setListOfDocs(result)\n };\n" }, { "answer_id": 74616110, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const deleteItem = ({ currentTarget }) => {\n setListOfDocs((prev) => {\n return prev.filter((item, index) => index != currentTarget.id);\n });\n};\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8132903/" ]
74,601,213
<p>So imagine you want to access the multiple dbContexts that are on different environments or servers (Dev, Test, Pre-prod etc), and use the data from all those different databases to calculate something. How would I register multiple dbContexts of the same type (<code>MonitoringDbContext</code>) and differentiate between them?</p> <p>This is where I got stuck</p> <pre><code>var envDbContextDetails = configuration.GetSection(&quot;EnvironmentConnectionStrings&quot;).Get&lt;EnvironmentConnectionStringsModel&gt;(); var nonRegisteredDbContexts = envDbContextDetails.DbConnectionStrings.Where(x =&gt; x.Environment != envDbContextDetails.CurrentDbEnvironment).ToList(); nonRegisteredDbContexts.ForEach(x =&gt; services.AddDbContext&lt;MonitoringDbContext&gt;(options =&gt; options.UseSqlServer(x.ConnectionString))); </code></pre> <p>So I'm registering multiple <code>MonitoringDbContext</code> contexts, and now what? My idea was to resolve, pull them and add them in a <code>Dictionary&lt;string, MonitoringDbContext&gt;</code> where the key is the environment name (Dev, Test etc) and use them from a <code>DbContextFactory</code> where I would select the one I need, or use all of them in a loop, depending on what I need to calculate. But I have no idea how to get the dbContexts after registering them, and how to differentiate between them.</p>
[ { "answer_id": 74601463, "author": "Jérémy Rippert", "author_id": 20293448, "author_profile": "https://Stackoverflow.com/users/20293448", "pm_score": 0, "selected": false, "text": "const deleteItem = ({ currentTarget }) => {\n const deletedId = currentTarget.id;\n const result = listOfDocs.filter((item, index) => item !== deletedId); \n setListOfDocs(result)\n };\n" }, { "answer_id": 74616110, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 3, "selected": true, "text": "const deleteItem = ({ currentTarget }) => {\n setListOfDocs((prev) => {\n return prev.filter((item, index) => index != currentTarget.id);\n });\n};\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9485849/" ]
74,601,248
<p>So the official bash manual states that &quot;For example, the regular expression ‘[0123456789]’ matches any single digit, whereas ‘[^()]’ matches any single character that is not an opening or closing parenthesis,&quot;, copied a link at the bottom of this question, for context.</p> <p>So I tested it every which way I could think of, to try and do the &quot;negate&quot; part of this, but I could not get it to work:</p> <pre><code>$ cat test a line b line c line d line $ grep [^abc] test a line b line c line d line $ grep '[^abc]' test a line b line c line d line $ grep '[^(abc)]' test a line b line c line d line [$ grep [^(abc)] test bash: syntax error near unexpected token `(' </code></pre> <p><a href="https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html" rel="nofollow noreferrer">https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html</a></p> <p>I was expecting just line D to be shown</p>
[ { "answer_id": 74601338, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "[^abc] a b c a line l i n e grep '^[^abc]*$' test" }, { "answer_id": 74602688, "author": "Andrej Podzimek", "author_id": 8584929, "author_profile": "https://Stackoverflow.com/users/8584929", "pm_score": 1, "selected": false, "text": "bash extglob while IFS= read -r line; do\n [[ \"$line\" = *([^abc]) ]] && printf '%s\\n' \"$line\"\ndone < test\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5841499/" ]
74,601,276
<p><code>Build completed with a result of 'Failed' in 28 seconds (28474 ms) #0 GetStacktrace(int) #1 DebugStringToFile(DebugStringToFileData const&amp;) #2 DebugLogHandler_CUSTOM_Internal_Log(LogType, LogOption, ScriptingBackendNativeStringPtrOpaque*, ScriptingBackendNativeObjectPtrOpaque*) #3 (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,UnityEngine.LogOption,string,UnityEngine.Object) #4 (Mono JIT Code) [BuildPlayerWindowBuildMethods.cs:95] UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions) #5 (Mono JIT Code) [BuildPlayerWindow.cs:1172] UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform,UnityEditor.Modules.IBuildPostprocessor) </code></p> <pre><code>It says FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':launcher:checkDebugDuplicateClasses'. &gt; 1 exception was raised by workers: java.lang.RuntimeException: java.lang.RuntimeException: Duplicate class com.unity3d.ads.BuildConfig found in modules UnityAds-runtime.jar (:UnityAds:) and com.unity3d.ads.unity-ads-4.4.1-runtime.jar (:com.unity3d.ads.unity-ads-4.4.1:) Duplicate class com.unity3d.ads.IUnityAdsInitializationListener found in modules UnityAds-runtime.jar (:UnityAds:) and com.unity3d.ads.unity-ads-4.4.1-runtime.jar (:com.unity3d.ads.unity-ads-4.4.1:) </code></pre> <p>I searched up the problem, and I figured it out that it was because my Unity Ads package was duplicated. But I can't figure out how to remove only one of the duplicates.</p> <p>BTW, it worked perfectly before adding a keystroke.</p>
[ { "answer_id": 74601338, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "[^abc] a b c a line l i n e grep '^[^abc]*$' test" }, { "answer_id": 74602688, "author": "Andrej Podzimek", "author_id": 8584929, "author_profile": "https://Stackoverflow.com/users/8584929", "pm_score": 1, "selected": false, "text": "bash extglob while IFS= read -r line; do\n [[ \"$line\" = *([^abc]) ]] && printf '%s\\n' \"$line\"\ndone < test\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19167140/" ]
74,601,281
<p>When using hiredis, use redisAppendCommand to put multiple hincrby commands, the reply-&gt;type result of redisGetReply is REDIS_REPLY_INTEGER, and only one of the results is returned.<br /> But when I use hmget, the result of reply-&gt;type is REDIS_REPLY_ARRAY.</p>
[ { "answer_id": 74601338, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "[^abc] a b c a line l i n e grep '^[^abc]*$' test" }, { "answer_id": 74602688, "author": "Andrej Podzimek", "author_id": 8584929, "author_profile": "https://Stackoverflow.com/users/8584929", "pm_score": 1, "selected": false, "text": "bash extglob while IFS= read -r line; do\n [[ \"$line\" = *([^abc]) ]] && printf '%s\\n' \"$line\"\ndone < test\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15128586/" ]
74,601,283
<p>I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels as [9, 8 ... -9, -10]. This worked as intended in seaborn (matplotlib), however doing so in plotly just reverses the image vertically. Here's the code:</p> <pre><code>import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(range(-10, 10)), ) fig.show() </code></pre> <p><a href="https://i.stack.imgur.com/wFdRP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wFdRP.png" alt="enter image description here" /></a></p> <pre><code>import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(reversed(range(-10, 10))), ) fig.show() </code></pre> <p><a href="https://i.stack.imgur.com/uCjWL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uCjWL.png" alt="enter image description here" /></a></p> <p>Why is this happening and how can I fix it?</p> <p>EDIT: Adding seaborn code to see the difference. As you can see, reversing the range for labels only changes the labels and has no effect on the image whatsoever, this is the effect I want in plotly.</p> <pre><code>import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(range(-10, 10)) ) </code></pre> <p><a href="https://i.stack.imgur.com/hx0RA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hx0RA.png" alt="enter image description here" /></a></p> <pre><code>import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(reversed(range(-10, 10))) ) </code></pre> <p><a href="https://i.stack.imgur.com/zUqVp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zUqVp.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74630904, "author": "devp", "author_id": 8234870, "author_profile": "https://Stackoverflow.com/users/8234870", "pm_score": -1, "selected": false, "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n" }, { "answer_id": 74662593, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": false, "text": "x = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n" }, { "answer_id": 74663390, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 2, "selected": false, "text": "import plotly.graph_objects as go\n\nimg = np.arange(20**2).reshape((20, 20))\n\nfig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1]))\n\nfig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_layout(autosize=False, height=500, width=500)\nfig.show()\n" }, { "answer_id": 74679491, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\n\ny_values = list(range(-10, 10))\n\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n yaxis_title=\"y-axis\",\n tickvals=y_values,\n ticktext=reversed(y_values),\n )\nfig.show()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14121531/" ]
74,601,287
<p>I am trying to emit same state with different set of data using equatable. But, somehow the state doesn't get emitted the second time when next 5 records are added in the list.</p> <p>It would be great if someone could help.</p> <p>This is how I am emitting post:</p> <pre><code>loadedState = LoadedPosts( now: DateTime.now(), post: List.from(postDetailsFilteredPostResponse, growable: false), newCount: 0, friends: List.from(postFriendsResponse, growable: false), likes: List.from(postLikesResponse, growable: false), comments:List.from(postCommentsResponse, growable: false), photos: List.from(postPhotosResponse, growable: false), userDetail: userDetail); emit(loadedState); </code></pre> <p>This is the state class:</p> <pre><code> abstract class PostState extends Equatable{ @override List&lt;Object?&gt; get props =&gt; []; } class LoadedPosts extends PostState{ List&lt;Post&gt; post = List&lt;Post&gt;.filled(5, Post(postId: '')); final List&lt;User&gt;? friends; final List&lt;Images&gt; photos; final List&lt;UserLikes&gt; likes; final List&lt;UserComments&gt; comments; final User? userDetail; final int newCount; final DateTime now; LoadedPosts({ required this.post, required this.friends, required this.photos, required this. likes, required this.comments, required this.newCount, required this.now, this.userDetail }); @override List&lt;Object?&gt; get props =&gt; [now, post]; } </code></pre>
[ { "answer_id": 74630904, "author": "devp", "author_id": 8234870, "author_profile": "https://Stackoverflow.com/users/8234870", "pm_score": -1, "selected": false, "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n" }, { "answer_id": 74662593, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": false, "text": "x = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n" }, { "answer_id": 74663390, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 2, "selected": false, "text": "import plotly.graph_objects as go\n\nimg = np.arange(20**2).reshape((20, 20))\n\nfig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1]))\n\nfig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_layout(autosize=False, height=500, width=500)\nfig.show()\n" }, { "answer_id": 74679491, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\n\ny_values = list(range(-10, 10))\n\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n yaxis_title=\"y-axis\",\n tickvals=y_values,\n ticktext=reversed(y_values),\n )\nfig.show()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19033905/" ]
74,601,315
<p>I have a little problem with filtering my array.</p> <p>I want display a product filtered by input value with a name or platform or something other value. With name is no problem, but i don't know how to do it with platforms.</p> <p>Bottom is my logic and file with products, txh very much for help</p> <p>live: <a href="https://gacmen45.github.io/game-shop/" rel="nofollow noreferrer">live</a></p> <p>repo: <a href="https://github.com/gacmen45/game-shop" rel="nofollow noreferrer">repo</a></p> <pre><code>const [inputText, setInputText] = useState('') const inputHandler = e =&gt; { const text = e.target.value.toLowerCase() setInputText(text) } const filteredData = PRODUCT_LIST.filter(el =&gt; { if (inputText === '') { return } else { return el.name.toLowerCase().includes(inputText) } }) </code></pre> <pre><code>const PRODUCT_LIST = [ { id: 'gow', name: 'God of War', developer: 'Santa Monica Studio', category: 'games', platform: 'PlayStation 4', version: 'PL', price: 39, },] </code></pre>
[ { "answer_id": 74630904, "author": "devp", "author_id": 8234870, "author_profile": "https://Stackoverflow.com/users/8234870", "pm_score": -1, "selected": false, "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n" }, { "answer_id": 74662593, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": false, "text": "x = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n" }, { "answer_id": 74663390, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 2, "selected": false, "text": "import plotly.graph_objects as go\n\nimg = np.arange(20**2).reshape((20, 20))\n\nfig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1]))\n\nfig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_layout(autosize=False, height=500, width=500)\nfig.show()\n" }, { "answer_id": 74679491, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\n\ny_values = list(range(-10, 10))\n\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n yaxis_title=\"y-axis\",\n tickvals=y_values,\n ticktext=reversed(y_values),\n )\nfig.show()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906130/" ]
74,601,317
<p>I have a vector of strings either starting with <code>\n1.</code> or <code>\ntext</code> and I wish to filter all those starting with <code>\n1.</code> Sample:</p> <pre><code>[1] &quot;\n1. Morgenhanen matter&quot; [2] &quot;\n1. Morgenstund har guld&quot; [3] &quot;\nMorgensange for børn be&quot; </code></pre> <p>but I can't seem to grap those sentences starting with \n1. Here's where I'm at:</p> <pre><code>grepl(&quot;^['\\\\']n1&quot;, df$text) </code></pre> <p>but it returns false for all sentences...</p> <p>In the end I want to end up with something like</p> <pre><code>library(tidyverse) df %&gt;% filter(those sentences starting with \n1) </code></pre> <p>I'm sorry, I'm just not the best at regex in r...</p>
[ { "answer_id": 74630904, "author": "devp", "author_id": 8234870, "author_profile": "https://Stackoverflow.com/users/8234870", "pm_score": -1, "selected": false, "text": "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n" }, { "answer_id": 74662593, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": false, "text": "x = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n" }, { "answer_id": 74663390, "author": "r-beginners", "author_id": 13107804, "author_profile": "https://Stackoverflow.com/users/13107804", "pm_score": 2, "selected": false, "text": "import plotly.graph_objects as go\n\nimg = np.arange(20**2).reshape((20, 20))\n\nfig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1]))\n\nfig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_layout(autosize=False, height=500, width=500)\nfig.show()\n" }, { "answer_id": 74679491, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\n\ny_values = list(range(-10, 10))\n\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n yaxis_title=\"y-axis\",\n tickvals=y_values,\n ticktext=reversed(y_values),\n )\nfig.show()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4438203/" ]
74,601,353
<p>I am trying to acheive a styling as shown in the image attached below <a href="https://i.stack.imgur.com/Ka9yM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ka9yM.png" alt="enter image description here" /></a></p> <p>See how here the fingerprint icon happens to be inside the border of the Textinput field but instead I am getting the output as shown below</p> <p><a href="https://i.stack.imgur.com/V2C8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V2C8A.png" alt="enter image description here" /></a></p> <p>PS:- ignore the left and right side black color borders it happens to be the simulator body just focus on the UI.</p> <p>Here's my code :-</p> <pre><code>import { View, Text, TextInput, StyleSheet } from 'react-native' import React from 'react' import Icon from 'react-native-vector-icons/MaterialCommunityIcons' const TestAtom = () =&gt; { return ( &lt;View style={styles.searchSection}&gt; &lt;TextInput style={styles.input} placeholder='User' onChangeText={(searchString) =&gt; {this.setState({searchString})}} underlineColorAndroid=&quot;transparent&quot;/&gt; &lt;Icon style={styles.searchIcon} name='fingerprint' size={20} color= '#000' /&gt; &lt;/View&gt; ) } const styles = StyleSheet.create({ searchSection: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, searchIcon: { // padding: 10 paddingRight: 10 }, input: { flex: 1, paddingTop: 10, paddingRight: 10, paddingBottom: 10, paddingLeft: 0, backgroundColor: '#fff', color: '#424242', borderBottomColor: '#000', borderBottomWidth: 1 } }); export default TestAtom </code></pre> <p>Can anyone help me with it.</p>
[ { "answer_id": 74601652, "author": "Vin Xi", "author_id": 19450576, "author_profile": "https://Stackoverflow.com/users/19450576", "pm_score": 1, "selected": false, "text": "<View style={{\n borderWidth:1,\n flex:1,\n flexDirection:'row',\n alignItems:'center'\n}}>\n <TextInput/>\n <FingerIcon/>\n</View>\n" }, { "answer_id": 74603393, "author": "SKR123", "author_id": 15781662, "author_profile": "https://Stackoverflow.com/users/15781662", "pm_score": 0, "selected": false, "text": "import { View, StyleSheet,SafeAreaView,TextInput } from 'react-native'\n\nimport MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';\n\nfunction UIComponent(){\n\n<View style={styles.container}>\n\n<View style={styles.componentWrapper}>\n \n <View style={styles.passwordFieldWrapper}>\n <TextInput style={styles.textInput} placeholder='umana Password'>\n </TextInput>\n <MaterialCommunityIcons name=\"fingerprint\" color='green' size={24} />\n </View>\n\n <View style={styles.bottomPart}>\n\n </View>\n</View> \n\n</View>\n}\n\nexport default UIComponent\n\nconst styles = StyleSheet.create({\n\ncontainer:{\n backgroundColor:'#ffffff',\n flex:1\n},\ncomponentWrapper:{\n alignItems:'center',\n justifyContent:'center'\n},\npasswordFieldWrapper:{\n flexDirection:'row'\n},\ntextInput:{\n width:'50%'\n},\nbottomPart:{\n marginTop:3,\n borderBottomColor:'gray',\n borderBottomWidth:1,\n width:'60%'\n}\n\n\n})\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20117908/" ]
74,601,373
<p>While waiting on a condition variable, the thread changing the state of the predicate must own the lock, so the update isn't missed during the wakeup. According to the documentation, this is necessary, even while using atomic variables. However I'm not certain if <code>request_stop()</code> already handles it correctly.</p> <p>So the question is, which of the two options is the correct and standard conforming one?</p> <p><code>~jthread()</code> naturally doesn't take a lock to <code>request_stop()</code>, but then I don't understand where the difference between a <code>stop_token</code> and an atomic shared variable is. And thereby, how one of them requires the lock, while the other doesn't.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;thread&gt; #include &lt;condition_variable&gt; #include &lt;iostream&gt; #include &lt;chrono&gt; std::mutex m; std::condition_variable_any cv; void waitingThread(std::stop_token st){ std::unique_lock&lt;std::mutex&gt; lk(m); std::cout&lt;&lt;&quot;Waiting&quot;&lt;&lt;std::endl; cv.wait(lk, st, [](){return false;}); std::cout&lt;&lt;&quot;Awake&quot;&lt;&lt;std::endl; } void withoutLock(){ std::jthread jt{waitingThread}; std::this_thread::sleep_for(std::chrono::seconds(1)); jt.request_stop(); } void withLock(){ std::jthread jt{waitingThread}; std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard&lt;std::mutex&gt; lk(m); jt.request_stop(); } } int main(){ withoutLock(); withLock(); } </code></pre> <p><a href="https://en.cppreference.com/w/cpp/thread/condition_variable" rel="nofollow noreferrer">std::condition_variable</a> specifies:</p> <blockquote> <p>Even if the shared variable is atomic, it must be modified while owning the mutex to correctly publish the modification to the waiting thread.</p> </blockquote> <p><a href="https://en.cppreference.com/w/cpp/thread/condition_variable_any/wait" rel="nofollow noreferrer">std::condition_variable_any::wait</a>, <a href="https://en.cppreference.com/w/cpp/thread/stop_token" rel="nofollow noreferrer">std::stop_token</a> and <a href="https://en.cppreference.com/w/cpp/thread/stop_source" rel="nofollow noreferrer">std::stop_source</a> do not specify, if the interrupt of the wait is guaranteed register the change in the stop state.</p>
[ { "answer_id": 74603447, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 2, "selected": true, "text": "notify request_stop() request_­stop stop_­requested stop_­possible request_­stop true stop_­requested stop_­token stop_­source while (!stoken.stop_requested()) {\n if (pred())\n return true;\n wait(lock);\n}\nreturn pred();\n request_stop wait(lock) stop_requested() true request_stop wait stop_requested() std::condition_variable_any request_stop" }, { "answer_id": 74604118, "author": "CGlas", "author_id": 17770286, "author_profile": "https://Stackoverflow.com/users/17770286", "pm_score": 0, "selected": false, "text": "stop_token condition_variable_any::wait stop_callback request_stop()" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17770286/" ]
74,601,451
<p>I am prototyping a smart link service in Go using Google Cloud Run. I need to know <strong>which domain/hostname has been used to call my Cloud Run service</strong> (e.g., the default .run.app, or one of many custom mapped domains).</p> <p>I created a check endpoint (<code>/__hitcheck</code>) that returns the current HTTP request's referer, headers, and URL, as JSON.</p> <p>I've checked fields I'd expect to show the current domain called, in vain:</p> <ul> <li><code>r.URL.String() = &quot;/__hitcheck&quot;</code> (my test endpoint)</li> <li><code>r.URL.Host = &quot;&quot;</code></li> </ul> <p>And nothing's in the request headers either.</p> <p><strong>So, how can I know if somebody called <code>/__hitcheck</code> from the Cloud Run service URL directly or one of many custom domains?</strong></p> <p>The redacted JSON payload:</p> <pre><code>{ &quot;r.Header&quot;: { &quot;Accept&quot;: [ &quot;text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9&quot; ], &quot;Accept-Encoding&quot;: [ &quot;gzip, deflate, br&quot; ], &quot;Accept-Language&quot;: [ &quot;en-US,en;q=0.9&quot; ], &quot;Cookie&quot;: [ &quot;...some stuff...&quot; ], &quot;Early-Data&quot;: [ &quot;1&quot; ], &quot;Forwarded&quot;: [ &quot;for=\&quot;MY IP\&quot;;proto=https&quot; ], &quot;Referer&quot;: [ &quot;https://example.com/some-blog-post/&quot; ], &quot;Sec-Ch-Ua&quot;: [ &quot;\&quot;Google Chrome\&quot;;v=\&quot;107\&quot;, \&quot;Chromium\&quot;;v=\&quot;107\&quot;, \&quot;Not=A?Brand\&quot;;v=\&quot;24\&quot;&quot; ], &quot;Sec-Ch-Ua-Mobile&quot;: [ &quot;?0&quot; ], &quot;Sec-Ch-Ua-Platform&quot;: [ &quot;\&quot;macOS\&quot;&quot; ], &quot;Sec-Fetch-Dest&quot;: [ &quot;document&quot; ], &quot;Sec-Fetch-Mode&quot;: [ &quot;navigate&quot; ], &quot;Sec-Fetch-Site&quot;: [ &quot;cross-site&quot; ], &quot;Sec-Fetch-User&quot;: [ &quot;?1&quot; ], &quot;Traceparent&quot;: [ &quot;some request ID&quot; ], &quot;Upgrade-Insecure-Requests&quot;: [ &quot;1&quot; ], &quot;User-Agent&quot;: [ &quot;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&quot; ], &quot;X-Cloud-Trace-Context&quot;: [ &quot;some request ID&quot; ], &quot;X-Forwarded-For&quot;: [ &quot;MY IP&quot; ], &quot;X-Forwarded-Proto&quot;: [ &quot;https&quot; ] }, &quot;r.Referer()&quot;: &quot;https://example.com/some-blog-post/&quot;, &quot;r.RequestURI&quot;: &quot;/__hitcheck&quot;, &quot;r.URL&quot;: { &quot;Scheme&quot;: &quot;&quot;, &quot;Opaque&quot;: &quot;&quot;, &quot;User&quot;: null, &quot;Host&quot;: &quot;&quot;, &quot;Path&quot;: &quot;/__hitcheck&quot;, &quot;RawPath&quot;: &quot;&quot;, &quot;OmitHost&quot;: false, &quot;ForceQuery&quot;: false, &quot;RawQuery&quot;: &quot;&quot;, &quot;Fragment&quot;: &quot;&quot;, &quot;RawFragment&quot;: &quot;&quot; }, &quot;r.URL.String()&quot;: &quot;/__hitcheck&quot; } </code></pre>
[ { "answer_id": 74607565, "author": "John Hanley", "author_id": 8016720, "author_profile": "https://Stackoverflow.com/users/8016720", "pm_score": 2, "selected": false, "text": "Host host" }, { "answer_id": 74613724, "author": "Lazhar", "author_id": 4916475, "author_profile": "https://Stackoverflow.com/users/4916475", "pm_score": 0, "selected": false, "text": "http.Request.Host http.Request.URL.Host" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916475/" ]
74,601,459
<p>Disclaimer: I'm a newbie. I was trying out conditional chains in C with a simple quiz.</p> <p>I entered this:</p> <pre><code>int age = get_int(&quot;Age in whole numbers: &quot;); int r; if(age&lt;12) { printf(&quot;Go back kid\n&quot;); r = 0; } else if(12&lt;= age &lt;16) { printf(&quot;Teenagers not allowed\n&quot;); r = 0; } </code></pre> <p>(im using cs50 codespace in visualstudio which has aforementioned get_int function)</p> <p>age&lt;12 worked but problem showed with this line</p> <pre><code> else if(12&lt;= age &lt;16) </code></pre> <p>The error mentioned in title: <a href="https://i.stack.imgur.com/kb7zm.jpg" rel="nofollow noreferrer">Error</a></p> <p>My main question is the &quot;why&quot; and not just the &quot;how&quot; - as in how does this result in a &quot;Boolean expression&quot; in this case?? I just want to check if age is greater than or equal to 12, and less than 16. The age variable is declared int and will store an int and not Boolean as per my current understanding. How else do I compare the variable input?</p>
[ { "answer_id": 74601504, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "else if ((12 <= age) < 16)\n <= else if (age >= 12 && age < 16)\n" }, { "answer_id": 74601521, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 1, "selected": false, "text": "12 <= age && age < 16\n age >= 12 && age < 16\n 12 <= age < 16\n ( 12 <= age ) < 16\n 12 <= age 0 1 age 0 < 16\n 1 < 16\n" }, { "answer_id": 74601631, "author": "RIJIK", "author_id": 5044463, "author_profile": "https://Stackoverflow.com/users/5044463", "pm_score": 0, "selected": false, "text": "12 <= age 12 <= age true false false = 0 true = 1 (12 <= age < 16) (true < 16) (false < 16) (1 < 16) (0 < 16) true true (12<= age <16) (12 <= age && age < 16)" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623725/" ]
74,601,482
<p>I'm trying to merge two files that contain some numbers into a third file but I'm not getting the right result.</p> <p>This is my code:</p> <pre><code>void merge(string input_file1, string input_file2, string output_file){ fstream fs1; fstream fs2; fstream fs3; int n1, n2; fs1.open(input_file1); fs2.open(input_file2); fs3.open(output_file); while(fs1 &gt;&gt; n1 &amp;&amp; fs2 &gt;&gt; n2){ if(n1 &lt; n2){ fs3 &lt;&lt; n1 &lt;&lt; &quot; &quot;; fs1 &gt;&gt; n1; } else{ fs3 &lt;&lt; n2 &lt;&lt; &quot; &quot;; fs2 &gt;&gt; n2; } } while(fs1 &gt;&gt; n1) fs3 &lt;&lt; n1 &lt;&lt; &quot; &quot;; while(fs2 &gt;&gt; n2) fs3 &lt;&lt; n2 &lt;&lt; &quot; &quot;; } </code></pre> <p>input:</p> <p>input file1: 1 2 3 4 5 6 7</p> <p>input file2: 34 56 77 78 88 90 100</p> <p>output file: 1 3 5 7 88 90 100</p>
[ { "answer_id": 74601821, "author": "molbdnilo", "author_id": 404970, "author_profile": "https://Stackoverflow.com/users/404970", "pm_score": 3, "selected": true, "text": "n1 < n2 fs1 >> n1 n2 n1 >= n2 fs2 >> n2 n1 // Potentially read the first two numbers.\nfs1 >> n1;\nfs2 >> n2;\n// This loop is entered only if there were two numbers. \n// Note that the last successfully read number is written only for the shorter input (if any).\nwhile (fs1 && fs2)\n{\n if (n1 < n2)\n {\n fs3 << n1 << ' ';\n fs1 >> n1;\n }\n else\n {\n fs3 << n2 << ' ';\n fs2 >> n2;\n }\n}\n// Write-then-read because the last value read has not been written yet.\nwhile (fs1)\n{\n fs3 << n1;\n fs1 >> n1;\n}\nwhile (fs2)\n{\n fs3 << n2;\n fs2 >> n2;\n}\n" }, { "answer_id": 74602262, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\nusing namespace std::string_literals;\n\nvoid merge(const std::string& in1, const std::string& in2, const std::string& out) {\n if (std::ifstream ifs1{ in1 }, ifs2(in2); ifs1 and ifs2)\n if (std::ofstream ofs{ out }; ofs) {\n \n std::vector data{ std::istream_iterator<int>(ifs1), {} };\n data.insert(data.end(), std::istream_iterator<int>(ifs2), {});\n std::sort(data.begin(), data.end());\n std::copy(data.begin(), data.end(), std::ostream_iterator<int>(ofs, \" \"));\n }\n else std::cerr << \"\\nError: Could not open input files\\n\\n\";\n else std::cerr << \"\\nError: Could not open output files\\n\\n\";\n}\nint main() {\n merge(\"in1.txt\"s, \"in2.txt\"s, \"out.txt\"s);\n}\n" }, { "answer_id": 74604788, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 0, "selected": false, "text": "views::istream #include <algorithm>\n#include <fstream>\n#include <filesystem>\n#include <ranges>\n\nvoid merge(const std::filesystem::path& in1, const std::filesystem::path& in2, const std::filesystem::path& out)\n{\n auto in1_stream = std::ifstream(in1), in2_stream = std::ifstream(in2);\n auto out_stream = std::ofstream(out);\n std::ranges::merge(\n std::views::istream<int>(in1_stream), std::views::istream<int>(in2_stream),\n std::ostream_iterator<int>(out_stream, \" \")\n );\n}\n\nint main()\n{\n merge(\"input1.txt\", \"input2.txt\", \"output.txt\");\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16978335/" ]
74,601,483
<p>I am trying to find the difference between the times people wake up and go to sleep from survey data. When I convert the data to a time so that I can use difftime, R doesn't recognise that values after 00:00 are from the next day.</p> <p>Here is a sample of the data.</p> <pre><code>df &lt;- data.frame( b = c('07:00', '10:00', '11:00', '13:00', '05:00'), d = c('00:00', '00:30', '23:00', '22:00','04:20') ) </code></pre> <p>I have converted the characters to date times like so</p> <pre><code> df$b &lt;- strptime(df$b, format = &quot;%H:%M&quot;) df$d &lt;- strptime(df$d, format = &quot;%H:%M&quot;) </code></pre> <p>but then I get stuck</p> <p>Everything I have tried hasn't worked at all</p>
[ { "answer_id": 74601821, "author": "molbdnilo", "author_id": 404970, "author_profile": "https://Stackoverflow.com/users/404970", "pm_score": 3, "selected": true, "text": "n1 < n2 fs1 >> n1 n2 n1 >= n2 fs2 >> n2 n1 // Potentially read the first two numbers.\nfs1 >> n1;\nfs2 >> n2;\n// This loop is entered only if there were two numbers. \n// Note that the last successfully read number is written only for the shorter input (if any).\nwhile (fs1 && fs2)\n{\n if (n1 < n2)\n {\n fs3 << n1 << ' ';\n fs1 >> n1;\n }\n else\n {\n fs3 << n2 << ' ';\n fs2 >> n2;\n }\n}\n// Write-then-read because the last value read has not been written yet.\nwhile (fs1)\n{\n fs3 << n1;\n fs1 >> n1;\n}\nwhile (fs2)\n{\n fs3 << n2;\n fs2 >> n2;\n}\n" }, { "answer_id": 74602262, "author": "A M", "author_id": 9666018, "author_profile": "https://Stackoverflow.com/users/9666018", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\nusing namespace std::string_literals;\n\nvoid merge(const std::string& in1, const std::string& in2, const std::string& out) {\n if (std::ifstream ifs1{ in1 }, ifs2(in2); ifs1 and ifs2)\n if (std::ofstream ofs{ out }; ofs) {\n \n std::vector data{ std::istream_iterator<int>(ifs1), {} };\n data.insert(data.end(), std::istream_iterator<int>(ifs2), {});\n std::sort(data.begin(), data.end());\n std::copy(data.begin(), data.end(), std::ostream_iterator<int>(ofs, \" \"));\n }\n else std::cerr << \"\\nError: Could not open input files\\n\\n\";\n else std::cerr << \"\\nError: Could not open output files\\n\\n\";\n}\nint main() {\n merge(\"in1.txt\"s, \"in2.txt\"s, \"out.txt\"s);\n}\n" }, { "answer_id": 74604788, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 0, "selected": false, "text": "views::istream #include <algorithm>\n#include <fstream>\n#include <filesystem>\n#include <ranges>\n\nvoid merge(const std::filesystem::path& in1, const std::filesystem::path& in2, const std::filesystem::path& out)\n{\n auto in1_stream = std::ifstream(in1), in2_stream = std::ifstream(in2);\n auto out_stream = std::ofstream(out);\n std::ranges::merge(\n std::views::istream<int>(in1_stream), std::views::istream<int>(in2_stream),\n std::ostream_iterator<int>(out_stream, \" \")\n );\n}\n\nint main()\n{\n merge(\"input1.txt\", \"input2.txt\", \"output.txt\");\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20623966/" ]
74,601,508
<p>I have a file with words that are each in a separate line. I want to read each word and add quotes around it, and a comma after the word. After that I want the words back into a new text file with the added symbols.</p> <p>Example, this as input file:</p> <pre><code>ram shyam raja </code></pre> <p>I want this to be in the output file:</p> <pre><code>&quot;ram&quot;, &quot;shyam&quot;, &quot;raja&quot; </code></pre>
[ { "answer_id": 74601614, "author": "Bas van der Linden", "author_id": 11119684, "author_profile": "https://Stackoverflow.com/users/11119684", "pm_score": 2, "selected": false, "text": "# read lines from file\ntext = \"\"\nwith open('filename.txt', 'r') as ifile:\n text = ifile.readline()\n\n# get all sepearte string split by space\ndata = text.split(\" \")\n\n# add quotes to each one\ndata = [f\"\\\"{name}\\\"\" for name in data]\n\n# append them together with commas inbetween\nupdated_text = \", \".join(data)\n\n# write to some file\nwith open(\"outfilename.txt\", 'w') as ofile:\n ofile.write(updated_text)\n jeff adam bezos\n \"jeff\", \"adam\", \"bezos\"\n # read lines from file\nwords = []\nwith open('filename.txt', 'r') as ifile:\n words = [line.replace(\"\\n\", \"\") for line in ifile.readlines()]\n\n# add quotes to each one\nupdated_words = [f\"\\\"{word}\\\"\" for word in words]\n\n# append them together with commas inbetween\nupdated_text = \",\\n\".join(updated_words)\n\n# write to some file\nwith open(\"outfilename.txt\", 'w') as ofile:\n ofile.write(updated_text)\n jeff\nadam\nbezos\n \"jeff\",\n\"adam\",\n\"bezos\"\n" }, { "answer_id": 74606639, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 1, "selected": false, "text": "with open('text.txt', 'r') as r: lines = r.read().splitlines()\nwith open('text.txt', 'w') as w: w.writelines(f'\"{line}\",'+'\\n' for line in lines)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20183674/" ]
74,601,512
<p>I have some values in <strong>df</strong>:</p> <pre><code># A tibble: 7 × 1 var1 &lt;dbl&gt; 1 0 2 10 3 20 4 210 5 230 6 266 7 267 </code></pre> <p>that I would like to compare to a second dataframe called <strong>value_lookup</strong></p> <pre><code># A tibble: 4 × 2 var1 value &lt;dbl&gt; &lt;dbl&gt; 1 0 0 2 200 10 3 230 20 4 260 30 </code></pre> <p>In particual I would like to make a join based on <code>&gt;=</code> meaning that a value that is greater or equal to the number in <code>var1</code> gets a values of x. E.g. take the number 210 of the orginal dataframe. Since it is <code>&gt;= 200</code> and <code>&lt;230</code> it would get a value of 10.</p> <p>Here is the <strong>expected output</strong>:</p> <pre><code> var1 value 1 0 0 2 10 0 3 20 0 4 210 10 5 230 20 6 266 30 7 267 30 </code></pre> <p>I thought it should be doable using <code>{fuzzyjoin}</code> but I cannot get it done.</p> <pre><code>value_lookup &lt;- tibble(var1 = c(0, 200,230,260), value = c(0,10,20,30)) df &lt;- tibble(var1 = c(0,10,20,210,230,266,267)) library(fuzzyjoin) fuzzyjoin::fuzzy_left_join( x = df, y = value_lookup , by = &quot;var1&quot;, match_fun = list(`&gt;=`) ) </code></pre>
[ { "answer_id": 74601763, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 1, "selected": false, "text": "cut df$value <- value_lookup$value[cut(df$var1, \n c(value_lookup$var1, Inf), \n right=F)]\n# # A tibble: 7 x 2\n# var1 value\n# <dbl> <dbl>\n# 1 0 0\n# 2 10 0\n# 3 20 0\n# 4 210 10\n# 5 230 20\n# 6 266 30\n# 7 267 30\n" }, { "answer_id": 74601875, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 3, "selected": true, "text": "findInterval df$value <- value_lookup$value[findInterval(df$var1, value_lookup$var1)]\n var1 value\n1 0 0\n2 10 0\n3 20 0\n4 210 10\n5 230 20\n6 266 30\n7 267 30\n data.table roll = T var1 df library(data.table)\n\nsetDT(value_lookup)[setDT(df), on = 'var1', roll = T]\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14137004/" ]
74,601,515
<p>I have a text file that looks like this:</p> <pre><code>subjects ENGLISH, MATHS, SCIENCE Joe, A, A, B Dave, A, B, C Will, D, D, E </code></pre> <p>And I want to put it into a dictionary using Python</p> <pre><code>{’Joe’:{’ENGLISH’:A,’MATHS’:A,’SCIENCE’:B}, ’Dave’:{’ENGLISH’:A,’MATHS’:B,’SCIENCE’:C}, ’Will’:{’ENGLISH’:D,’MATHS’:D,’SCIENCE’:E}} </code></pre> <p>How would I go about doing this in one dictionary?</p>
[ { "answer_id": 74601640, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "pd.read_csv() pd df.to_dict('index')" }, { "answer_id": 74601702, "author": "Sash Sinha", "author_id": 6328256, "author_profile": "https://Stackoverflow.com/users/6328256", "pm_score": 1, "selected": false, "text": "file.txt subjects ENGLISH, MATHS, SCIENCE\n\nJoe, A, A, B\n\nDave, A, B, C\n\nWill, D, D, E\n * results = {}\nwith open('file.txt') as file:\n _, *subjects = next(file).split(' ') # Read header row\n subjects = [s[:-1] for s in subjects] # Remove trailing comma/newline from subjects\n for line in file:\n if line != '\\n': # Skip empty lines\n name, *grades = line.strip().split(', ')\n results[name] = dict(zip(subjects, grades))\nprint(results)\n subjects = ['ENGLISH', 'MATHS', 'SCIENCE']\nresults = {}\nwith open('file.txt') as file:\n next(file) # Skip header row since we have defined subjects in code...\n for line in file:\n if line != '\\n': # Skip empty lines\n name, *grades = line.strip().split(', ')\n results[name] = dict(zip(subjects, grades))\nprint(results)\n {'Joe': {'ENGLISH': 'A', 'MATHS': 'A', 'SCIENCE': 'B'}, 'Dave': {'ENGLISH': 'A', 'MATHS': 'B', 'SCIENCE': 'C'}, 'Will': {'ENGLISH': 'D', 'MATHS': 'D', 'SCIENCE': 'E'}}\n" }, { "answer_id": 74601720, "author": "Ravi Sharma", "author_id": 7049643, "author_profile": "https://Stackoverflow.com/users/7049643", "pm_score": -1, "selected": false, "text": "Name, ENGLISH, MATHS, SCIENCE\n\nJoe, A, A, B\n\nDave, A, B, C\n\nWill, D, D, E\n >>> import pandas as pd\n>>> pd.read_csv('file_path.csv',index_col='Name').transpose().to_dict()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14549181/" ]
74,601,552
<p>I have a Vue view, somethink like:</p> <pre><code>&lt;script setup lang=&quot;ts&quot;&gt; import { firstItem } from &quot;@/path/to/my/file&quot;; onMounted(async () =&gt; { let f1 = getFirstItem(); let f2 = getSecondItem(); }); </code></pre> <p>As you can see, there is an Import for <code>firstItem</code>, but I forgot to add an import for <code>secondItem</code>.</p> <p>My issue - Why such a code is passing <code>npm run serve</code> successfully? In fact, the website does not work (as expeted). How can I make <code>npm run serve</code> to fail instead of this confusing scenario that I was sure everything is OK with my code, and was not aware to this error?</p> <p>By The Way, <code>npm run lint</code> <strong>DO</strong> show this error, but I do not remember to run <code>npm run lint</code> bfore every <code>npm run serve</code></p>
[ { "answer_id": 74601693, "author": "Steven Spungin", "author_id": 5093961, "author_profile": "https://Stackoverflow.com/users/5093961", "pm_score": 1, "selected": false, "text": "npm run serve typescript global any" }, { "answer_id": 74610373, "author": "RK Coder", "author_id": 5699936, "author_profile": "https://Stackoverflow.com/users/5699936", "pm_score": 1, "selected": true, "text": "lint serve \"scripts\": {\n \"serve\": \"vue-cli-service lint && vue-cli-service serve\", ...\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5699936/" ]
74,601,586
<p>I added new field <strong>'approved'</strong> to <strong>USERS</strong> table. Field is index for now it could be 0 or 1. On user login I want to check this field and if it's 0 do not User let login. How to do in Laravel 9 breeze?</p>
[ { "answer_id": 74601870, "author": "Дима Свободин", "author_id": 5502766, "author_profile": "https://Stackoverflow.com/users/5502766", "pm_score": 0, "selected": false, "text": "$user = User::where('email', $this->email)->first();\n\nif(!$user->approved) {\n throw message here and redirect \n}\n" }, { "answer_id": 74603696, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": 1, "selected": false, "text": "attempt() authenticate() app\\Http\\Requests\\Auth\\LoginRequest.php public function authenticate()\n {\n $this->ensureIsNotRateLimited();\n\n if (! Auth::attempt(array_merge($this->validated(),[\n fn($query) => $query->where('approved', 1) // check if the user is approved if not it will not authenticate the user\n ]), $this->boolean('remember')))\n {\n RateLimiter::hit($this->throttleKey());\n\n throw ValidationException::withMessages([\n 'email' => trans('auth.failed'),\n ]);\n }\n\n RateLimiter::clear($this->throttleKey());\n }\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5502766/" ]
74,601,591
<p>I'm trying to understand loaders in <code>react-router@6.4</code>. How and why is a <code>BrowserRouter</code> doing a DB call? Is this just a contrived example and this is meant to be a client db call for illustration purposes or a there some undocumented server activity taking place here?</p> <p><a href="https://reactrouter.com/en/main/route/loader" rel="nofollow noreferrer">https://reactrouter.com/en/main/route/loader</a></p> <pre><code>createBrowserRouter([ { element: &lt;Teams /&gt;, path: &quot;teams&quot;, loader: async () =&gt; { return fakeDb.from(&quot;teams&quot;).select(&quot;*&quot;); }, children: [ { element: &lt;Team /&gt;, path: &quot;:teamId&quot;, loader: async ({ params }) =&gt; { return fetch(`/api/teams/${params.teamId}.json`); }, }, ], }, ]); </code></pre>
[ { "answer_id": 74603875, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": true, "text": "react-router-dom loader createBrowserRouter([\n {\n element: <Teams />,\n path: \"teams\",\n loader: async () => {\n return fakeDb.from(\"teams\").select(\"*\");\n },\n children: [\n {\n element: <Team />,\n path: \":teamId\",\n loader: async ({ params }) => {\n return fetch(`/api/teams/${params.teamId}.json`);\n },\n },\n ],\n },\n]);\n Teams useLoaderData fetch" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1236657/" ]
74,601,612
<p>I am executing following command of <code>find</code> in linux. <code>find /Volumes/app -user john -mtime 60</code>. It gives the list of file modified.</p> <p>After adding <code>-printf '%TY %Tb %Td %TH:%TM %p\n'</code> in <code>find</code> command in gives list of files with date.</p> <p>Following is the output:</p> <pre><code>2022 Nov 28 19:05 . 2022 Nov 28 18:31 ./abc.py </code></pre> <p>But instead of date How to get time in milliseconds?</p>
[ { "answer_id": 74603875, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": true, "text": "react-router-dom loader createBrowserRouter([\n {\n element: <Teams />,\n path: \"teams\",\n loader: async () => {\n return fakeDb.from(\"teams\").select(\"*\");\n },\n children: [\n {\n element: <Team />,\n path: \":teamId\",\n loader: async ({ params }) => {\n return fetch(`/api/teams/${params.teamId}.json`);\n },\n },\n ],\n },\n]);\n Teams useLoaderData fetch" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19992549/" ]
74,601,617
<p>I am trying to remake javascript method &quot;Shift()&quot; to my c# library. The method should return the first item in array and rewrite array to new with correct length. code:</p> <pre><code> public static T Shift&lt;T&gt;(this ref T[] array) { T item = array[0]; if (array.Length == 1) { array = new T[] { }; return item; } T[] shiftedArray = new T[array.Length - 1]; for (int i = 1; i &lt; array.Length; i++) { shiftedArray[i - 1] = array[i]; } array = shiftedArray; return item; } </code></pre> <p>I want it to be extension and generic. Any ideas?</p>
[ { "answer_id": 74601888, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 3, "selected": true, "text": "shift List<T> public static T Shift<T>(this List<T> list)\n{\n T item = list[0];\n \n list.RemoveAt(0);\n\n return item;\n}\n this ref struct Span Memory public static T Shift<T>(this ref Memory<T> array)\n{\n T item = array.Span[0];\n\n if (array.Length == 1)\n { \n array = Memory<T>.Empty;\n return item;\n }\n \n array = array.Slice(1);\n\n return item;\n}\n\npublic static T Shift<T>(this ref Span<T> array)\n{\n T item = array[0];\n\n if (array.Length == 1)\n { \n array = Span<T>.Empty;\n return item;\n }\n \n array = array.Slice(1);\n\n return item;\n}\n Span<int> span = new [] { 1, 2, 3 };\nint i1 = span.Shift();\nint i2 = span.Shift();\n" }, { "answer_id": 74605983, "author": "matej.tydli", "author_id": 20584679, "author_profile": "https://Stackoverflow.com/users/20584679", "pm_score": 1, "selected": false, "text": " public static T Shift<T>(ref IEnumerable<T> collection)\n {\n T firstItem = collection.First();\n collection = collection.Skip(1);\n return firstItem;\n }\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584679/" ]
74,601,618
<p>I have a class with a generic method:</p> <pre><code>public record OperationCollectionGeneric&lt;OPERATIONTYPE&gt; where OPERATIONTYPE: notnull, Enum { public OPERATIONTYPE Group { get; } public OperationCollectionGeneric(string part1, string? part2 = null, string? part3 = null) { Group = Enum.Parse&lt;OPERATIONTYPE&gt;(part1, true); } </code></pre> <p>The <code>Enum.Parse()</code> method has the following error:</p> <blockquote> <p>Error CS0453 The type 'OPERATIONTYPE' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.Parse(ReadOnlySpan, bool)'</p> </blockquote> <p>How can I pass the make sure that OPERATIONTYPE parameter is of type Enum</p> <p>I tried to use the <code>where</code> keywork to set the enum type for the <code>OPERATIONTYPE</code> but it does not work.</p>
[ { "answer_id": 74601672, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 3, "selected": true, "text": "Enum.Parse struct public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE : struct, Enum\n" }, { "answer_id": 74601674, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": -1, "selected": false, "text": "System.Enum" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8444039/" ]
74,601,619
<p>I keep finding more idioms that lend themselves to <code>std::exchange</code>.</p> <p>Today I found myself <a href="https://stackoverflow.com/a/74600853/85371">writing this</a> in an answer:</p> <pre><code>do { path.push_front(v); } while (v != std::exchange(v, pmap[v])); </code></pre> <p>I like it a lot more than, say</p> <pre><code>do { path.push_front(v); if (v == pmap[v]) break; v= pmap[v]; } while (true); </code></pre> <p>Hopefully for obvious reasons.</p> <p>However, I'm not big on standardese and I can't help but worry that <code>lhs != rhs</code> doesn't guarantee that the right-hand side expression isn't fully evaluated before the left-hand-side. That would make it a tautologous comparison - which would by definition return <code>true</code>.</p> <p>The code, however, does run correctly, apparently evaluating <code>lhs</code> first.</p> <p>Does anyone know</p> <ul> <li>whether the standard guarantees this evaluation order</li> <li>if it has changed in recent standards, which standard version first specified it?</li> </ul> <hr /> <p>PS. I realize that this is a special case of <code>f(a,b)</code> where <code>f</code> is <code>operator!=</code>. I've tried to answer my own query using the information found here but have failed to reach a conclusion to date:</p> <ul> <li><a href="https://en.cppreference.com/w/cpp/language/eval_order" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/language/eval_order</a></li> <li><a href="https://en.wikipedia.org/wiki/Sequence_point" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Sequence_point</a></li> <li><a href="https://stackoverflow.com/questions/2934904/order-of-evaluation-in-c-function-parameters">Order of evaluation in C++ function parameters</a></li> <li><a href="https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17">What are the evaluation order guarantees introduced by C++17?</a></li> </ul>
[ { "answer_id": 74601853, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 4, "selected": false, "text": "!= v std::exchange(v, pmap[v]) equal(..) std::exchange" }, { "answer_id": 74603738, "author": "duck", "author_id": 20625353, "author_profile": "https://Stackoverflow.com/users/20625353", "pm_score": 4, "selected": false, "text": "!= operator !=(T, T) != != v operator !=(const T&, const T&) T::operator !=(const T&) const v v exchange v v" }, { "answer_id": 74607694, "author": "Wolfgang Bangerth", "author_id": 2068775, "author_profile": "https://Stackoverflow.com/users/2068775", "pm_score": 2, "selected": false, "text": "do {\n path.push_front(v);\n} while ([&v,&pmap]() mutable\n {\n auto old_v = v; \n v = pmap[v];\n return v != old_v;\n } ());\n std::exchange()" }, { "answer_id": 74669488, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "v != std::exchange(v, pmap[v]) v std::exchange(v, pmap[v]) std::atomic_compare_exchange_strong <atomic> header std::exchange std::atomic_compare_exchange_strong std::atomic<int> v{ ... }; // initialize v with the initial value\nstd::map<int, int> pmap{ ... }; // initialize pmap with the map of values\nstd::deque<int> path;\n\nwhile (true)\n{\n// Perform an atomic compare-and-exchange operation.\n// If v is equal to pmap[v], set v to pmap[v] and return true.\n// Otherwise, do nothing and return false.\nif (!std::atomic_compare_exchange_strong(&v, &pmap[v], pmap[v]))\nbreak;\npath.push_front(v);\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85371/" ]
74,601,634
<p>I currently have 2 lists with different classes in them: <code>List&lt;Player&gt;</code> and <code>List&lt;Monster&gt;</code>.</p> <p>I want to get these two lists in a single Datagrid as follows:<a href="https://i.stack.imgur.com/kuppI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kuppI.png" alt="enter image description here" /></a></p> <p>The reason I need them to be in one Datagrid, is that I need to sort on Initiative, and show the order from high to low. The Datagrid also need to work with any number of players/monsters. The classes look as follows:</p> <pre><code>public partial class Player { public bool IsInParty { get; set; } public string Name { get; set; } public int Ac { get; set; } public string ArmorType { get; set; } public string[] Speed { get; set; } public int InitiativeBonus { get; set; } public string[] DmgVul { get; set; } public string[] DmgRes { get; set; } public string[] DmgImm { get; set; } public string[] CondImm { get; set; } public string[] Senses { get; set; } public string[] Languages { get; set; } public NameValuePair[] Conditions { get; set; } public int Id { get; set; } } </code></pre> <pre><code>public partial class Monster { public BaseMonster Stats { get; set; } public int Id { get; set; } public string Name { get; set; } public int Hp { get; set; } public List&lt;int&gt; Damage { get; set; } public bool IsOverhealed =&gt; Hp &gt; Stats.MaxHp; public bool IsBloody =&gt; Hp &lt;= Stats.MaxHp / 2.0; public bool IsNearDeath =&gt; Hp &lt;= Stats.MaxHp / 4.0; public bool IsDead =&gt; Hp &lt;= 0; public List&lt;NameValuePair&gt; Conditions { get; set; } } </code></pre> <pre><code>public partial class BaseMonster { public int DefaultId { get; set; } public string DefaultName { get; set; } public string Type { get; set; } public string Allignment { get; set; } public int Ac { get; set; } public string ArmorType { get; set; } public int MaxHp { get; set; } public string HitDice { get; set; } public string[] Speed { get; set; } public int Str { get; set; } public int Dex { get; set; } public int Con { get; set; } public int Int { get; set; } public int Wis { get; set; } public int Cha { get; set; } public string[] SavThrProf { get; set; } public string[] SkillProf { get; set; } public string[] DmgVul { get; set; } public string[] DmgRes { get; set; } public string[] DmgImm { get; set; } public string[] CondImm { get; set; } public string[] Senses { get; set; } public string[] Languages { get; set; } public string Challenge { get; set; } public NameValuePair[] Traits { get; set; } public NameValuePair[] Actions { get; set; } public NameValuePair[] LegendaryActions { get; set; } public string LairActions { get; set; } public string RegionalEffects { get; set; } } </code></pre> <p>Because I am relatively new to front-end and xaml, I have a little trouble how to take on this problem. Currently I've managed to get the following with some test data:</p> <p><a href="https://i.stack.imgur.com/kEv08.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kEv08.png" alt="enter image description here" /></a></p> <pre><code>&lt;Grid Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot;&gt; &lt;DataGrid x:Name=&quot;creatureDatagrid&quot;&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header=&quot;Name&quot; Binding=&quot;{Binding Name}&quot;/&gt; &lt;DataGridTextColumn Header=&quot;ID&quot; Binding=&quot;{Binding Id}&quot;/&gt; &lt;DataGridTextColumn Header=&quot;AC&quot; Binding=&quot;{Binding Ac}&quot;/&gt; &lt;DataGridTextColumn Header=&quot;HP&quot; Binding=&quot;{Binding Hp}&quot;/&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;Grid/&gt; </code></pre> <p>As you can see, some values work fine, but in this case AC is not working, because AC in found in <code>BaseMonster</code> in the <code>Monster</code> class</p>
[ { "answer_id": 74602318, "author": "Mykhailo Svyrydovych", "author_id": 13251244, "author_profile": "https://Stackoverflow.com/users/13251244", "pm_score": 1, "selected": false, "text": "List<ITableEntry>\n" }, { "answer_id": 74603904, "author": "ASh", "author_id": 1506454, "author_profile": "https://Stackoverflow.com/users/1506454", "pm_score": 0, "selected": false, "text": "<DataGridTextColumn Header=\"AC\">\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"Ac\" />\n <Binding Path=\"Stats.Ac\" />\n </PriorityBinding>\n </DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" }, { "answer_id": 74603920, "author": "Fruchtzwerg", "author_id": 5235574, "author_profile": "https://Stackoverflow.com/users/5235574", "pm_score": 2, "selected": true, "text": "public interface ICreature\n{\n int Id { get; set; }\n //Other common properties\n}\n public IEnumerable<ICreature> Creatures { get; } = Players.Concat(Monsters);\n <DataGrid ItemsSource=\"{Binding Creatures}\">\n <DataGrid.Columns>\n <DataGridTextColumn Header=\"CustomProperty\" Binding=\"{Binding Name}\"/>\n <!-- More custom properties -->\n </DataGrid.Columns>\n</DataGrid>\n <DataGridTextColumn Header=\"MixedProperty\"\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"PlayersProperty\"/>\n <Binding Path=\"MonstersProperty\"/>\n </PriorityBinding>\n <DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19328937/" ]
74,601,644
<p>I am working with dictionaries and classes and I want to check that the dictionaries and the classes have the same field types.</p> <p>For example, I have a dataclass of this form</p> <pre><code>@dataclasses.dataclass class FlatDataclass: first_field: str second_field: int </code></pre> <p>and I have a dictionary of this form</p> <pre><code>my_dict={first_field:&quot;a_string&quot;, second_field:&quot;5&quot;} </code></pre> <p>I want to check that the values of the dictionary have the right type for the class.</p> <p>So far I can get the types for the dictionary, from this:</p> <pre><code>dct_value_types = list(type(x).__name__ for x in list(dct.values())) </code></pre> <p>returns ['str', 'str']</p> <p>however</p> <pre><code>[f.type for f in dataclasses.fields(klass)] </code></pre> <p>[&lt;class 'str'&gt;, &lt;class 'int'&gt;]</p> <p>rather than ['str', 'str'], so I can't compare them.</p> <p>How would you get the types in a way you can compare them?</p>
[ { "answer_id": 74602318, "author": "Mykhailo Svyrydovych", "author_id": 13251244, "author_profile": "https://Stackoverflow.com/users/13251244", "pm_score": 1, "selected": false, "text": "List<ITableEntry>\n" }, { "answer_id": 74603904, "author": "ASh", "author_id": 1506454, "author_profile": "https://Stackoverflow.com/users/1506454", "pm_score": 0, "selected": false, "text": "<DataGridTextColumn Header=\"AC\">\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"Ac\" />\n <Binding Path=\"Stats.Ac\" />\n </PriorityBinding>\n </DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" }, { "answer_id": 74603920, "author": "Fruchtzwerg", "author_id": 5235574, "author_profile": "https://Stackoverflow.com/users/5235574", "pm_score": 2, "selected": true, "text": "public interface ICreature\n{\n int Id { get; set; }\n //Other common properties\n}\n public IEnumerable<ICreature> Creatures { get; } = Players.Concat(Monsters);\n <DataGrid ItemsSource=\"{Binding Creatures}\">\n <DataGrid.Columns>\n <DataGridTextColumn Header=\"CustomProperty\" Binding=\"{Binding Name}\"/>\n <!-- More custom properties -->\n </DataGrid.Columns>\n</DataGrid>\n <DataGridTextColumn Header=\"MixedProperty\"\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"PlayersProperty\"/>\n <Binding Path=\"MonstersProperty\"/>\n </PriorityBinding>\n <DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
74,601,671
<p>I'm trying to pull out a list of items in a table which have more than 1 end date of 12/31/2100, as items should only have 1 (per price line). Here's the query I have so far:</p> <pre><code>SELECT PCL.*, SKUP.SKU_DESC,COUNT(CASE WHEN CONVERT(DATE,PCL.DATEEND) = CONVERT(DATE,&quot;12/31/2100&quot;)) AS [Count] FROM PCL LEFT JOIN SKUP ON PCL.SKU = SKUP.SKU WHERE PCL.PRICELINE = &quot;R12-RETAILER&quot; GROUP BY PCL.SKU WHERE [Count] &gt; 1 </code></pre> <p>PCL is the price table, just bringing in the SKUP table for the item descriptions. When I run this query in Access, I get an error &quot;Syntax error (missing operator) in query expression 'COUNT(CASE WHEN CONVERT(DATE,PCL.DATEEND) = CONVERT(DATE,&quot;12/31/2100&quot;))'.&quot;</p> <p>Would someone be able to help me identify how this could be corrected or help point me toward an article which may better explain this?</p> <p>I've been googling a lot this morning trying to find better examples for this specific application, but still learning a lot about the Group By and Count functions in SQL queries</p> <p>Edit to describe my desired result, I'm just trying to pull out the records from the table which have 2+ of the date 12/31/2100, because there should only be 1 &quot;ongoing&quot; price for each item. If I can export it, I should be able to determine where the previous price should have ended based on the start dates.</p>
[ { "answer_id": 74602318, "author": "Mykhailo Svyrydovych", "author_id": 13251244, "author_profile": "https://Stackoverflow.com/users/13251244", "pm_score": 1, "selected": false, "text": "List<ITableEntry>\n" }, { "answer_id": 74603904, "author": "ASh", "author_id": 1506454, "author_profile": "https://Stackoverflow.com/users/1506454", "pm_score": 0, "selected": false, "text": "<DataGridTextColumn Header=\"AC\">\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"Ac\" />\n <Binding Path=\"Stats.Ac\" />\n </PriorityBinding>\n </DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" }, { "answer_id": 74603920, "author": "Fruchtzwerg", "author_id": 5235574, "author_profile": "https://Stackoverflow.com/users/5235574", "pm_score": 2, "selected": true, "text": "public interface ICreature\n{\n int Id { get; set; }\n //Other common properties\n}\n public IEnumerable<ICreature> Creatures { get; } = Players.Concat(Monsters);\n <DataGrid ItemsSource=\"{Binding Creatures}\">\n <DataGrid.Columns>\n <DataGridTextColumn Header=\"CustomProperty\" Binding=\"{Binding Name}\"/>\n <!-- More custom properties -->\n </DataGrid.Columns>\n</DataGrid>\n <DataGridTextColumn Header=\"MixedProperty\"\n <DataGridTextColumn.Binding>\n <PriorityBinding>\n <Binding Path=\"PlayersProperty\"/>\n <Binding Path=\"MonstersProperty\"/>\n </PriorityBinding>\n <DataGridTextColumn.Binding>\n</DataGridTextColumn>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19745110/" ]
74,601,694
<p>I want to replace one character at each iteration from a string. I already wrote some code that produces the following output:</p> <p>est</p> <p>st</p> <p>t</p> <p>This is fine and my expected result.</p> <hr /> <p>But when I add the input: &quot;hello&quot;, my output changes:</p> <p>ello</p> <p>llo</p> <p>o</p> <p>As you can see, the two &quot;l&quot;'s get removed at the same time. The reason is the following:</p> <p>&quot;replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence&quot;.</p> <p>As you can see from the documentation, each substring gets replaced. Is there an alternative function in the String class? Note that I only want to use String and no other third party library.</p> <hr /> <p>Maybe the replace-first function does achieve that? But since it requires regex I don't know how to use it ;(</p> <p>Thanks for any help in advance!</p> <p>Here is my code:</p> <pre><code>public static boolean isAnagram(String first, String second){ final int first_len = first.length(); final int second_len = second.length(); if (first_len != second_len){ return false; } //String newWord = oldWord.replace(oldChar,newChar) for (int i = 0; i &lt; first_len; i++) { char ch = first.charAt(i); first = first.replace(ch, ' '); System.out.println(first); for (int j = 0; j &lt; first_len; j++){ if (second.charAt(j) == ch) { second = second.replace(second.charAt(j), ' '); } } } if (first.trim().isEmpty() &amp;&amp; second.trim().isEmpty()){ return true; } return false; } </code></pre>
[ { "answer_id": 74601983, "author": "Nitroxy", "author_id": 20624395, "author_profile": "https://Stackoverflow.com/users/20624395", "pm_score": 2, "selected": false, "text": "\"Hello\".substring(1);" }, { "answer_id": 74602524, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public static boolean isAnagram(String first, String second) {\n\n final int first_len = first.length();\n final int second_len = second.length();\n if (first_len != second_len) {\n return false;\n }\n \n // If you want your anagram check to be case sensitive, comment out the following 2 lines\n first = first.toLowerCase();\n second = second.toLowerCase();\n \n for (int i = 0; i < first_len; i++) {\n final char ch = first.charAt(i);\n second = second.replaceFirst(Pattern.quote(String.valueOf(ch)), \"\");\n }\n\n if (second.trim().isEmpty()) {\n return true;\n }\n return false;\n}\n replaceFirst Pattern.quote" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16930849/" ]
74,601,721
<p>I need to get a limited data based on the criteria of Ind being 'Y'. But it should only capture the first row when Ind changes from 'N' or 'O' value to 'Y'. In the Check_Date it should update that first value.</p> <p>Input Data:</p> <pre><code>ID Date Ind 2 201905 N 2 201906 N 2 201907 N 2 201908 N 2 201909 N 2 201910 N 2 201911 N 2 201912 Y 2 202001 Y 2 202002 Y 2 202003 Y 2 202004 Y 2 202005 N 2 202006 N 2 202007 N 2 202008 Y 3 201906 N </code></pre> <p>Result:</p> <pre><code>ID Date Ind Check_Date 2 201912 Y 201912 2 202008 Y 202008 </code></pre> <p>I didn't find a complete approach when I searched and was only able to filter out the data with Ind as Y. When I applied minimum condition to the date based on below code, it gave me limited data with first instance of ID that was Y on a particular Date. What am I doing wrong?</p> <pre><code>library(dplyr) PO %&gt;% group(ID) filter(Date == min(Date)) %&gt;% filter(Ind == 'Y') %&gt;% slice(1) %&gt;% # takes the first occurrence if there is a tie ungroup() </code></pre>
[ { "answer_id": 74601983, "author": "Nitroxy", "author_id": 20624395, "author_profile": "https://Stackoverflow.com/users/20624395", "pm_score": 2, "selected": false, "text": "\"Hello\".substring(1);" }, { "answer_id": 74602524, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public static boolean isAnagram(String first, String second) {\n\n final int first_len = first.length();\n final int second_len = second.length();\n if (first_len != second_len) {\n return false;\n }\n \n // If you want your anagram check to be case sensitive, comment out the following 2 lines\n first = first.toLowerCase();\n second = second.toLowerCase();\n \n for (int i = 0; i < first_len; i++) {\n final char ch = first.charAt(i);\n second = second.replaceFirst(Pattern.quote(String.valueOf(ch)), \"\");\n }\n\n if (second.trim().isEmpty()) {\n return true;\n }\n return false;\n}\n replaceFirst Pattern.quote" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624148/" ]
74,601,729
<p>As in the topic, I'm making a request to an endpoint, which in return gives me a json string. Sample json string (picked up 6 substrings, there is about thousand more):</p> <pre><code>{&quot;probability&quot;:0.0062596053,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;apple&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.27482307,&quot;top&quot;:0.4361664,&quot;width&quot;:0.14311266,&quot;height&quot;:0.37521422}}, {&quot;probability&quot;:0.0061301645,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;apple&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.0,&quot;top&quot;:0.44423538,&quot;width&quot;:0.09239961,&quot;height&quot;:0.37426883}}, {&quot;probability&quot;:0.0059485333,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;carrot&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.037714787,&quot;top&quot;:0.0,&quot;width&quot;:0.15685204,&quot;height&quot;:0.27176687}}, {&quot;probability&quot;:0.005887271,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;tomato&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.5249929,&quot;top&quot;:0.70379305,&quot;width&quot;:0.44499594,&quot;height&quot;:0.29620594}}, {&quot;probability&quot;:0.0057223,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;apple&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.79498,&quot;top&quot;:0.34279144,&quot;width&quot;:0.19351125,&quot;height&quot;:0.39170527}}, {&quot;probability&quot;:0.0056102676,&quot;tagId&quot;:&quot;sometagid&quot;,&quot;tagName&quot;:&quot;apple&quot;,&quot;boundingBox&quot;:{&quot;left&quot;:0.030394234,&quot;top&quot;:0.21933028,&quot;width&quot;:0.16375154,&quot;height&quot;:0.3037323}}, </code></pre> <p>What do I need? I need this string to be splitted into these 6 (+1000) objects (preferably to an array) and I want to pick only these object that contain <code>probability*100 &gt; 50</code>.</p> <p>I've already made a class that contains such values as:</p> <pre><code>public class ResponseJsonNode { public double probability { get; set; } public string tagId { get; set; } public string tagName { get; set; } public BoundingBox boundingBox { get; set; } } </code></pre> <p>And BoundingBox is another class:</p> <pre><code>public class BoundingBox { double left { get; set; } double top { get; set; } double width { get; set; } double height { get; set; } } </code></pre> <p>Reproducible example (well not quite really because i can't post endpoint and key here):</p> <pre><code>using System.Net; using System.Text.Json; using ConsoleApp1; WebRequest request = HttpWebRequest.Create(&quot;SomeUriEndpoint&quot;); request.Method = &quot;POST&quot;; request.Headers.Add(&quot;some key&quot;, &quot;some more key&quot;); request.Headers.Add(&quot;some content type&quot;, &quot;some more content type&quot;); var f = File.Open(args[0], FileMode.Open); using (var ms = new MemoryStream()) { f.CopyTo(ms); var fileBytes = ms.ToArray(); request.ContentLength = fileBytes.Length; Stream stream = request.GetRequestStream(); stream.Write(fileBytes, 0, fileBytes.Length); stream.Close(); //imageStringBase64 = Convert.ToBase64String(fileBytes); } HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result; string json = new StreamReader(response.GetResponseStream()).ReadToEnd(); //JsonObject jo = (JsonObject)json; List&lt;ResponseJsonNode&gt; jsonNodeList = JsonSerializer.Deserialize&lt;List&lt;ResponseJsonNode&gt;&gt;(json); foreach(ResponseJsonNode rj in jsonNodeList) { Console.WriteLine(rj); } </code></pre> <p>And this gives me an error:</p> <pre><code>The JSON value could not be converted to System.Collections.Generic.List </code></pre> <p>This does not work also:</p> <pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result; string json = new StreamReader(response.GetResponseStream()).ReadToEnd(); //JsonObject jo = (JsonObject)json; //List&lt;ResponseJsonNode&gt; jsonNodeList = JsonSerializer.Deserialize&lt;List&lt;ResponseJsonNode&gt;&gt;(json); JsonArray jsonArray = JsonNode.Parse(json).AsArray(); List&lt;ResponseJsonNode&gt; nodes = new List&lt;ResponseJsonNode&gt;(); foreach(JsonObject jo in jsonArray) { nodes.Add(new ResponseJsonNode { probability = Convert.ToDouble(jo[&quot;probability&quot;]), tagName = (string)jo[&quot;tagName&quot;] }); } var stats = new Dictionary&lt;string, double&gt;(); foreach (ResponseJsonNode rjn in nodes) { if (rjn.probability * 100 &gt; 50) if (stats.ContainsKey(rjn.tagName)) { stats[rjn.tagName]++; } else { stats[rjn.tagName] = 1; } } </code></pre> <p>Throws an error: <code>System.InvalidOperationException: The node must be of type 'JsonArray'</code></p> <p>I have tried to parse it with numerous tutorials but every one of them seems deprecated or does not work (example shown above). So what is the best possible solution for converting json string into a iterable JsonObject? (Not specificly JsonObject class that is in c# libraries but something that i could iterate on)</p>
[ { "answer_id": 74601983, "author": "Nitroxy", "author_id": 20624395, "author_profile": "https://Stackoverflow.com/users/20624395", "pm_score": 2, "selected": false, "text": "\"Hello\".substring(1);" }, { "answer_id": 74602524, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public static boolean isAnagram(String first, String second) {\n\n final int first_len = first.length();\n final int second_len = second.length();\n if (first_len != second_len) {\n return false;\n }\n \n // If you want your anagram check to be case sensitive, comment out the following 2 lines\n first = first.toLowerCase();\n second = second.toLowerCase();\n \n for (int i = 0; i < first_len; i++) {\n final char ch = first.charAt(i);\n second = second.replaceFirst(Pattern.quote(String.valueOf(ch)), \"\");\n }\n\n if (second.trim().isEmpty()) {\n return true;\n }\n return false;\n}\n replaceFirst Pattern.quote" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15816553/" ]
74,601,730
<p>The following codes gives the total duration that a light has been switched on.</p> <pre><code>CREATE TABLE switch_times ( id SERIAL PRIMARY KEY, is1 BOOLEAN, id_dec INTEGER, label TEXT, ts TIMESTAMP WITH TIME ZONE default current_timestamp ); CREATE VIEW makecount AS SELECT *, row_number() OVER (PARTITION BY id_dec ORDER BY id) AS count FROM switch_times; select c1.label, SUM(c2.ts-c1.ts) AS sum from (makecount AS c1 inner join makecount AS c2 ON c2.count = c1.count + 1) where c2.is1=FALSE AND c1.id_dec = c2.id_dec AND c2.is1 != c1.is1 GROUP BY c1.label; </code></pre> <p>Link to working demo <a href="https://dbfiddle.uk/ZR8pLEBk" rel="nofollow noreferrer">https://dbfiddle.uk/ZR8pLEBk</a></p> <p>Any suggestions on how to alter the code so that it would give the sum over a given specific time period, say the 25th, during which all three lights were switched on for 12 hours? Problem 1: current code gives total sum, as follows. Problem 2: all durations that have not ended are disregarded, because there is no switch off time.</p> <pre><code>label sum 0x29 MH3 1 day 03:00:00 0x2B MH1 1 day 01:00:00 0x2C MH2 1 day 02:00:00 </code></pre> <p>The expected results is just over a a given date, i.e.</p> <pre><code>label sum 0x29 MH3 12:00:00 0x2B MH1 12:00:00 0x2C MH2 12:00:00 </code></pre>
[ { "answer_id": 74601983, "author": "Nitroxy", "author_id": 20624395, "author_profile": "https://Stackoverflow.com/users/20624395", "pm_score": 2, "selected": false, "text": "\"Hello\".substring(1);" }, { "answer_id": 74602524, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public static boolean isAnagram(String first, String second) {\n\n final int first_len = first.length();\n final int second_len = second.length();\n if (first_len != second_len) {\n return false;\n }\n \n // If you want your anagram check to be case sensitive, comment out the following 2 lines\n first = first.toLowerCase();\n second = second.toLowerCase();\n \n for (int i = 0; i < first_len; i++) {\n final char ch = first.charAt(i);\n second = second.replaceFirst(Pattern.quote(String.valueOf(ch)), \"\");\n }\n\n if (second.trim().isEmpty()) {\n return true;\n }\n return false;\n}\n replaceFirst Pattern.quote" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896646/" ]
74,601,781
<p>We're currently using Hibernate 5.6 but are trying to upgrade to Hibernate 6.1. In one entity we have this property:</p> <pre class="lang-java prettyprint-override"><code>@Type(type = &quot;text&quot;) private String someText; </code></pre> <p>But in Hibernate 6.1, the <code>type</code> field in the <code>@Type</code> annotation is removed. Now the <code>@Type</code> annotation is defined like this:</p> <pre class="lang-java prettyprint-override"><code>@java.lang.annotation.Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Type { /** * The implementation class which implements {@link UserType}. */ Class&lt;? extends UserType&lt;?&gt;&gt; value(); /** * Parameters to be injected into the custom type after it is * instantiated. The {@link UserType} implementation must implement * {@link org.hibernate.usertype.ParameterizedType} to receive the * parameters. */ Parameter[] parameters() default {}; } </code></pre> <p>Question: What's the equivalent of <code>@Type(type = &quot;text&quot;)</code> in Hibernate 6.1?</p>
[ { "answer_id": 74601889, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "@Type @Column @Column(columnDefinition=\"TEXT\")\nprivate String someText;\n" }, { "answer_id": 74602072, "author": "Georgii Lvov", "author_id": 15000097, "author_profile": "https://Stackoverflow.com/users/15000097", "pm_score": 3, "selected": true, "text": "text LONGVARCHAR @JdbcTypeCode @JdbcTypeCode(Types.LONGVARCHAR)\nprivate String text;\n" }, { "answer_id": 74662438, "author": "Gavin King", "author_id": 2889760, "author_profile": "https://Stackoverflow.com/users/2889760", "pm_score": 0, "selected": false, "text": "@JdbcType(LongVarcharJdbcType.class)\n @JdbcTypeCode(Types.LONGVARCHAR)" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398441/" ]
74,601,790
<p>I have problem and I don't know how to fix it. So i have component in which I've declared an array of objects. I want to set its state separately but I don't want to declare multiple useStates.</p> <p>I have an array of objects which look like this:</p> <pre><code>const [card, setCard] = useState({ name: &quot;&quot;, questions: [ { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, { question: &quot;&quot;, answer: &quot;&quot;, }, ], }); </code></pre> <p>and here's component:</p> <pre class="lang-js prettyprint-override"><code>const NewCard = () =&gt; { const handleNameChange = (event) =&gt; { setCard({ name: event.target.value, ...questions }); }; return ( &lt;div className=&quot;newcard-container&quot;&gt; &lt;div className=&quot;card-container&quot;&gt; &lt;h3&gt;Podaj nazwe fiszki&lt;/h3&gt; &lt;input type=&quot;text&quot; value={card.name} /&gt; &lt;/div&gt; &lt;div className=&quot;questions-container&quot;&gt; {card.questions.map((q) =&gt; { return ( &lt;div className=&quot;question&quot;&gt; &lt;h4&gt;Podaj pytanie &lt;/h4&gt; &lt;input type=&quot;text&quot; value={q.question} /&gt; &lt;h4&gt;Podaj odpowiedź&lt;/h4&gt; &lt;input type=&quot;text&quot; value={q.answer} /&gt; &lt;/div&gt; ); })} &lt;button&gt;Dodaj pytanie&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ); }; </code></pre> <p>I've tried to figure out how to change the setState to get that approach but I didn't made it. Any ideas how can I get that?</p>
[ { "answer_id": 74601855, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "setCard((card) => { ...card , name: event.target.value });\n" }, { "answer_id": 74602027, "author": "Guilherme Nascimento", "author_id": 18029579, "author_profile": "https://Stackoverflow.com/users/18029579", "pm_score": 0, "selected": false, "text": "\n const [ card, setCard ] = useState( {\n name: \"\",\n questions: {\n 1: {\n statement: \"\",\n answer: \"\",\n },\n 2: {\n statement: \"\",\n answer: \"\",\n },\n //...\n }\n } );\n\n // To set an especifique answer or question, you can set the state like this:\n setCard( prev => ( {\n ...prev,\n questions: {\n ...prev.questions,\n 1: {\n ...prev.questions[ 1 ],\n answer: \"New answer\"\n }\n }\n } ) );\n\n // To add a new question, you can set the state like this:\n setCard( prev => ( {\n ...prev,\n questions: {\n ...prev.questions,\n [ Object.keys( prev.questions ).length + 1 ]: {\n statement: \"\",\n answer: \"\",\n }\n }\n } ) );\n\n // To remove a question, you can set the state like this:\n setCard( prev => {\n const questions = { ...prev.questions };\n delete questions[ 1 ];\n return {\n ...prev,\n questions\n };\n } );\n\n \n // Solution with array\n const [card, setCard] = useState({\n name: \"\",\n questions: [\n {\n question: \"\",\n answer: \"\",\n },\n {\n question: \"\",\n answer: \"\",\n },\n //...\n ],\n } );\n\n // To set an especifique answer or question, you will need the index of the question, or null to set a new question.\n\n const setCardQuestions = ( index, question, answer ) => {\n setCard( ( prev ) => {\n const questions = [...prev.questions];\n if ( index === null ) {\n questions.push( {\n question,\n answer,\n } );\n } else {\n questions[ index ] = {\n question,\n answer,\n };\n }\n return {\n ...prev,\n questions,\n };\n });\n };\n\n // To remove a question, you will need the index of the question.\n const removeCardQuestion = ( index ) => {\n setCard( ( prev ) => {\n const questions = [...prev.questions];\n questions.splice( index, 1 );\n return {\n ...prev,\n questions,\n };\n });\n }\n\n" }, { "answer_id": 74602032, "author": "AbsoluteZero", "author_id": 20539156, "author_profile": "https://Stackoverflow.com/users/20539156", "pm_score": 3, "selected": true, "text": "import React, { useState, useCallback } from 'react';\n\nexport function App() {\n const [card, setCard] = useState({\n name: \"\",\n questions: [\n {\n id: 'question-1',\n question: \"Question 1\",\n answer: \"\",\n },\n {\n id: 'question-2',\n question: \"Question 2\",\n answer: \"\",\n },\n {\n id: 'question-3',\n question: \"Question 3\",\n answer: \"\",\n },\n ]\n });\n\n const handleCardNameChange = useCallback((ev) => {\n setCard((c) => ({ ...c, name: ev.target.value }))\n }, [setCard]);\n\n const handleAnswerChange = useCallback((cardId, value) => {\n const updatedQuestions = card.questions.map((c) => {\n \n if (c.id !== cardId) {\n return c;\n }\n\n return {\n ...c,\n answer: value,\n }\n });\n\n setCard({\n ...card,\n questions: updatedQuestions,\n })\n }, [card, setCard]);\n\n return (\n <div>\n <input placeholder=\"Card Title\" value={card.name} onChange={handleCardNameChange} />\n {card.questions.map((c) => (\n <div key={c.id}>\n <p>Q: {c.question}</p>\n <input placeholder=\"Answer\" value={c.answer} onChange={(ev) => handleAnswerChange(c.id, ev.target.value)} />\n </div>\n ))}\n </div>\n );\n}\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12649378/" ]
74,601,802
<p>I have this file directory: <a href="https://i.stack.imgur.com/0RLHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0RLHd.png" alt="enter image description here" /></a> When I open this project in browser: Fatal error: Class 'Phalcon\Mvc\Application' not found in...</p> <p>I read that I have to install composer but when I install composer this errors occure: <a href="https://i.stack.imgur.com/ClLx6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ClLx6.png" alt="enter image description here" /></a></p> <p>How can I run my project?</p> <p>My composer.json file consists:</p> <pre><code> &quot;require&quot;: { &quot;phalcon/incubator-mailer&quot;: &quot;^1.0&quot;, &quot;smi2/phpclickhouse&quot;: &quot;^1.4&quot;, &quot;hybridauth/hybridauth&quot;: &quot;^3.8&quot; } }``` </code></pre>
[ { "answer_id": 74601855, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "setCard((card) => { ...card , name: event.target.value });\n" }, { "answer_id": 74602027, "author": "Guilherme Nascimento", "author_id": 18029579, "author_profile": "https://Stackoverflow.com/users/18029579", "pm_score": 0, "selected": false, "text": "\n const [ card, setCard ] = useState( {\n name: \"\",\n questions: {\n 1: {\n statement: \"\",\n answer: \"\",\n },\n 2: {\n statement: \"\",\n answer: \"\",\n },\n //...\n }\n } );\n\n // To set an especifique answer or question, you can set the state like this:\n setCard( prev => ( {\n ...prev,\n questions: {\n ...prev.questions,\n 1: {\n ...prev.questions[ 1 ],\n answer: \"New answer\"\n }\n }\n } ) );\n\n // To add a new question, you can set the state like this:\n setCard( prev => ( {\n ...prev,\n questions: {\n ...prev.questions,\n [ Object.keys( prev.questions ).length + 1 ]: {\n statement: \"\",\n answer: \"\",\n }\n }\n } ) );\n\n // To remove a question, you can set the state like this:\n setCard( prev => {\n const questions = { ...prev.questions };\n delete questions[ 1 ];\n return {\n ...prev,\n questions\n };\n } );\n\n \n // Solution with array\n const [card, setCard] = useState({\n name: \"\",\n questions: [\n {\n question: \"\",\n answer: \"\",\n },\n {\n question: \"\",\n answer: \"\",\n },\n //...\n ],\n } );\n\n // To set an especifique answer or question, you will need the index of the question, or null to set a new question.\n\n const setCardQuestions = ( index, question, answer ) => {\n setCard( ( prev ) => {\n const questions = [...prev.questions];\n if ( index === null ) {\n questions.push( {\n question,\n answer,\n } );\n } else {\n questions[ index ] = {\n question,\n answer,\n };\n }\n return {\n ...prev,\n questions,\n };\n });\n };\n\n // To remove a question, you will need the index of the question.\n const removeCardQuestion = ( index ) => {\n setCard( ( prev ) => {\n const questions = [...prev.questions];\n questions.splice( index, 1 );\n return {\n ...prev,\n questions,\n };\n });\n }\n\n" }, { "answer_id": 74602032, "author": "AbsoluteZero", "author_id": 20539156, "author_profile": "https://Stackoverflow.com/users/20539156", "pm_score": 3, "selected": true, "text": "import React, { useState, useCallback } from 'react';\n\nexport function App() {\n const [card, setCard] = useState({\n name: \"\",\n questions: [\n {\n id: 'question-1',\n question: \"Question 1\",\n answer: \"\",\n },\n {\n id: 'question-2',\n question: \"Question 2\",\n answer: \"\",\n },\n {\n id: 'question-3',\n question: \"Question 3\",\n answer: \"\",\n },\n ]\n });\n\n const handleCardNameChange = useCallback((ev) => {\n setCard((c) => ({ ...c, name: ev.target.value }))\n }, [setCard]);\n\n const handleAnswerChange = useCallback((cardId, value) => {\n const updatedQuestions = card.questions.map((c) => {\n \n if (c.id !== cardId) {\n return c;\n }\n\n return {\n ...c,\n answer: value,\n }\n });\n\n setCard({\n ...card,\n questions: updatedQuestions,\n })\n }, [card, setCard]);\n\n return (\n <div>\n <input placeholder=\"Card Title\" value={card.name} onChange={handleCardNameChange} />\n {card.questions.map((c) => (\n <div key={c.id}>\n <p>Q: {c.question}</p>\n <input placeholder=\"Answer\" value={c.answer} onChange={(ev) => handleAnswerChange(c.id, ev.target.value)} />\n </div>\n ))}\n </div>\n );\n}\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20146550/" ]
74,601,879
<p>I have a date in format of YYYY-MM-DD (2022-11-01). I want to convert it to 'YYYYMMDD' format (without hyphen). Pls support.</p> <p>I tried this...</p> <p>df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... but no luck</p>
[ { "answer_id": 74601942, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "strftime %Y%m%d df[\"ConvertedDate\"] = df[\"DateOfBirth\"].dt.strftime('%Y%m%d')\n" }, { "answer_id": 74601950, "author": "ShadowCrafter_01", "author_id": 15174310, "author_profile": "https://Stackoverflow.com/users/15174310", "pm_score": -1, "selected": false, "text": "from datetime import datetime \n\ninitial = \"2022-11-01\"\ntime = datetime.strptime(initial, \"%Y-%m-%d\")\nprint(time.strftime(\"%Y%m%d\"))\n" }, { "answer_id": 74601987, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 0, "selected": false, "text": "df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n import pandas as pd\n\nvalues = {'DateOfBirth': ['2021-01-14', '2022-11-01', '2022-11-01']}\n\ndf = pd.DataFrame(values)\ndf['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n\nprint (df)\n DateOfBirth ConvertedDate\n0 2021-01-14 20210114\n1 2022-11-01 20221101\n2 2022-11-01 20221101\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624319/" ]
74,601,892
<p>I do tests using py test. There is some kind of warning in the terminal, so I could just skip it, but I would like to remove it from the terminal.</p> <pre><code>RemovedInDjango50Warning: The USE_L10N setting is deprecated. Starting with Djan go 5.0, localized formatting of data will always be enabled. For example Django will display numbers and dates using the format of the current locale. warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning) </code></pre> <p>Help me, please!!!!!!</p> <p><a href="https://i.stack.imgur.com/2HPWN.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74601942, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "strftime %Y%m%d df[\"ConvertedDate\"] = df[\"DateOfBirth\"].dt.strftime('%Y%m%d')\n" }, { "answer_id": 74601950, "author": "ShadowCrafter_01", "author_id": 15174310, "author_profile": "https://Stackoverflow.com/users/15174310", "pm_score": -1, "selected": false, "text": "from datetime import datetime \n\ninitial = \"2022-11-01\"\ntime = datetime.strptime(initial, \"%Y-%m-%d\")\nprint(time.strftime(\"%Y%m%d\"))\n" }, { "answer_id": 74601987, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 0, "selected": false, "text": "df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n import pandas as pd\n\nvalues = {'DateOfBirth': ['2021-01-14', '2022-11-01', '2022-11-01']}\n\ndf = pd.DataFrame(values)\ndf['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n\nprint (df)\n DateOfBirth ConvertedDate\n0 2021-01-14 20210114\n1 2022-11-01 20221101\n2 2022-11-01 20221101\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554157/" ]
74,601,906
<p>I have a csv file with &quot;years&quot; in row[0] and I need to get a count of how many times each year occurs and pair it with that year in a dictionary. To be clear, the year is the key and the amount of times it occurs in the csv is the value.</p> <p>Here's what I have, but I am missing something. I just can't figure out how to get the count of each year to pair it with that year.</p> <pre><code>def incidents_per_year(): dict = {} count = 0 with open(&quot;saved_data.csv&quot;) as f: reader = csv.reader(f) next(reader) for row in reader: count += 1 year = row[0] dict[year] = count return dict </code></pre> <p>Here is the part of the csv file (overall it's 50,000 rows so this is a small subset).</p> <pre class="lang-none prettyprint-override"><code>year,month,hour_of_day,incident_type_primary,day_of_week 2022,6,8,LARCENY/THEFT,Monday 2016,10,5,ASSAULT,Tuesday 2016,8,12,LARCENY/THEFT,Wednesday 2014,9,5,LARCENY/THEFT,Sunday 2015,8,7,ASSAULT,Wednesday 2016,11,2,LARCENY/THEFT,Tuesday 2015,7,11,ASSAULT,Friday 2015,4,12,LARCENY/THEFT,Friday 2016,3,2,BURGLARY,Wednesday 2014,10,4,LARCENY/THEFT,Thursday 2016,8,3,LARCENY/THEFT,Friday 2016,1,12,LARCENY/THEFT,Monday 2016,3,1,BURGLARY,Friday 2014,8,7,BURGLARY,Saturday 2017,4,10,UUV,Wednesday 2017,6,5,BURGLARY,Thursday 2017,1,4,BURGLARY,Wednesday 2016,7,9,BURGLARY,Thursday 2015,9,9,LARCENY/THEFT,Monday 2017,4,12,LARCENY/THEFT,Thursday 2016,3,4,LARCENY/THEFT,Friday 2016,4,5,BURGLARY,Thursday 2017,10,12,LARCENY/THEFT,Sunday 2015,7,11,ASSAULT,Monday 2012,5,12,LARCENY/THEFT,Friday 2014,12,11,LARCENY/THEFT,Thursday 2015,3,4,LARCENY/THEFT,Tuesday 2017,11,8,LARCENY/THEFT,Wednesday 2011,7,17,LARCENY/THEFT,Thursday 2015,9,17,ROBBERY,Wednesday 2015,5,12,BURGLARY,Thursday 2013,11,14,ASSAULT,Tuesday 2015,6,16,LARCENY/THEFT,Friday 2010,10,18,LARCENY/THEFT,Monday 2007,8,21,LARCENY/THEFT,Tuesday 2015,5,16,LARCENY/THEFT,Tuesday 2013,11,8,LARCENY/THEFT,Wednesday 2007,6,15,BURGLARY,Sunday 2012,5,19,ASSAULT,Tuesday 2007,8,20,LARCENY/THEFT,Thursday 2018,7,18,LARCENY/THEFT,Sunday 2019,2,2,BURGLARY,Tuesday 2012,11,20,BURGLARY,Monday 2012,6,15,ASSAULT,Wednesday 2011,10,21,THEFT OF SERVICES,Monday 2008,11,23,LARCENY/THEFT,Wednesday 2014,7,4,BURGLARY,Wednesday 2013,11,9,LARCENY/THEFT,Wednesday 2021,7,11,ASSAULT,Saturday 2018,7,12,LARCENY/THEFT,Friday 2013,2,0,LARCENY/THEFT,Friday 2007,1,0,ROBBERY,Thursday 2008,7,4,ASSAULT,Saturday 2007,8,4,BURGLARY,Saturday 2019,12,17,LARCENY/THEFT,Thursday 2018,7,0,LARCENY/THEFT,Wednesday 2010,2,12,BURGLARY,Sunday 2012,4,3,BURGLARY,Tuesday 2012,1,23,LARCENY/THEFT,Monday 2006,1,23,LARCENY/THEFT,Wednesday 2015,6,0,LARCENY/THEFT,Tuesday 2015,4,21,BURGLARY,Wednesday 2017,5,11,ROBBERY,Tuesday 2017,9,16,LARCENY/THEFT,Wednesday 2016,7,12,LARCENY/THEFT,Friday 2006,6,6,LARCENY/THEFT,Friday 2010,5,0,BURGLARY,Thursday 2010,11,21,ROBBERY,Wednesday 2011,2,3,BURGLARY,Friday 2017,8,0,LARCENY/THEFT,Wednesday 2011,12,23,BURGLARY,Friday 2012,8,0,LARCENY/THEFT,Saturday 2012,7,22,ROBBERY,Thursday 2016,9,8,ASSAULT,Saturday 2013,7,7,BURGLARY,Friday 2010,4,5,ASSAULT,Saturday 2022,3,13,LARCENY/THEFT,Saturday 2009,5,13,BURGLARY,Thursday 2010,2,12,ASSAULT,Saturday 2011,12,20,LARCENY/THEFT,Friday 2007,10,4,BURGLARY,Thursday 2007,8,19,LARCENY/THEFT,Saturday 2011,12,4,LARCENY/THEFT,Saturday 2012,10,23,UUV,Friday 2018,4,19,UUV,Sunday 2010,5,13,LARCENY/THEFT,Wednesday 2017,5,11,BURGLARY,Saturday 2009,9,2,ASSAULT,Thursday 2016,6,0,LARCENY/THEFT,Wednesday 2012,4,4,LARCENY/THEFT,Monday 2009,9,19,BURGLARY,Tuesday 2009,6,10,BURGLARY,Monday 2007,10,0,LARCENY/THEFT,Wednesday 2016,5,1,ASSAULT,Tuesday 2010,10,0,ROBBERY,Friday 2013,10,11,LARCENY/THEFT,Monday 2018,9,19,BURGLARY,Friday 2006,6,14,BURGLARY,Wednesday 2010,5,21,ASSAULT,Sunday 2010,6,10,LARCENY/THEFT,Monday 2018,9,10,LARCENY/THEFT,Friday 2007,11,0,LARCENY/THEFT,Tuesday 2008,8,22,ASSAULT,Thursday 2016,10,19,LARCENY/THEFT,Wednesday 2018,1,1,LARCENY/THEFT,Tuesday 2015,8,7,BURGLARY,Friday 2016,4,20,LARCENY/THEFT,Tuesday 2015,10,1,LARCENY/THEFT,Thursday 2010,3,15,ASSAULT,Monday 2014,4,4,ASSAULT,Monday 2011,10,21,LARCENY/THEFT,Friday 2016,9,12,LARCENY/THEFT,Thursday 2011,8,10,LARCENY/THEFT,Wednesday 2012,10,16,LARCENY/THEFT,Friday 2016,3,20,ASSAULT,Saturday 2020,11,11,UUV,Tuesday 2013,11,5,LARCENY/THEFT,Wednesday 2010,4,4,BURGLARY,Friday 2011,9,23,ASSAULT,Friday 2008,10,14,LARCENY/THEFT,Thursday 2015,6,0,UUV,Saturday 2010,12,23,LARCENY/THEFT,Saturday 2015,6,14,LARCENY/THEFT,Tuesday 2008,10,22,ASSAULT,Friday 2010,11,12,BURGLARY,Monday 2006,5,20,ASSAULT,Sunday 2012,9,16,BURGLARY,Sunday 2020,7,3,ASSAULT,Thursday 2014,1,5,BURGLARY,Tuesday 2015,4,1,ASSAULT,Thursday 2014,10,7,LARCENY/THEFT,Sunday 2007,11,9,LARCENY/THEFT,Wednesday 2008,7,17,BURGLARY,Sunday 2011,4,23,BURGLARY,Saturday 2014,7,17,LARCENY/THEFT,Wednesday 2008,10,10,LARCENY/THEFT,Tuesday 2007,7,18,LARCENY/THEFT,Sunday 2011,3,18,ROBBERY,Wednesday 2010,12,0,LARCENY/THEFT,Thursday 2013,5,0,LARCENY/THEFT,Tuesday 2006,9,14,LARCENY/THEFT,Friday 2014,2,1,ROBBERY,Thursday 2020,5,17,UUV,Sunday 2007,4,23,LARCENY/THEFT,Sunday 2015,6,12,LARCENY/THEFT,Monday 2010,1,5,ROBBERY,Monday 2011,11,18,LARCENY/THEFT,Tuesday 2008,10,23,LARCENY/THEFT,Thursday 2019,8,17,UUV,Friday 2006,9,17,LARCENY/THEFT,Friday 2015,7,9,LARCENY/THEFT,Monday 2013,2,23,ROBBERY,Sunday 2012,8,15,ASSAULT,Sunday 2015,3,0,LARCENY/THEFT,Friday 2006,12,15,BURGLARY,Thursday 2021,12,10,LARCENY/THEFT,Thursday 2006,11,11,BURGLARY,Sunday 2009,7,0,LARCENY/THEFT,Tuesday 2006,5,17,LARCENY/THEFT,Thursday 2016,7,0,BURGLARY,Wednesday 2017,1,14,LARCENY/THEFT,Tuesday 2010,11,13,LARCENY/THEFT,Tuesday 2015,9,13,BURGLARY,Wednesday 2008,10,1,BURGLARY,Wednesday 2009,4,22,LARCENY/THEFT,Thursday 2016,5,20,ASSAULT,Wednesday 2009,7,12,LARCENY/THEFT,Thursday 2021,6,20,LARCENY/THEFT,Sunday </code></pre>
[ { "answer_id": 74601942, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "strftime %Y%m%d df[\"ConvertedDate\"] = df[\"DateOfBirth\"].dt.strftime('%Y%m%d')\n" }, { "answer_id": 74601950, "author": "ShadowCrafter_01", "author_id": 15174310, "author_profile": "https://Stackoverflow.com/users/15174310", "pm_score": -1, "selected": false, "text": "from datetime import datetime \n\ninitial = \"2022-11-01\"\ntime = datetime.strptime(initial, \"%Y-%m-%d\")\nprint(time.strftime(\"%Y%m%d\"))\n" }, { "answer_id": 74601987, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 0, "selected": false, "text": "df['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n import pandas as pd\n\nvalues = {'DateOfBirth': ['2021-01-14', '2022-11-01', '2022-11-01']}\n\ndf = pd.DataFrame(values)\ndf['ConvertedDate'] = pd.to_datetime(df['DateOfBirth'], format='%Y-%m-%d').dt.strftime('%Y%m%d')\n\nprint (df)\n DateOfBirth ConvertedDate\n0 2021-01-14 20210114\n1 2022-11-01 20221101\n2 2022-11-01 20221101\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624307/" ]
74,601,918
<p>I have dataframe where one column looks like</p> <pre><code>Average Weight (Kg) 0.647 0.88 0 0.73 1.7 - 2.1 1.2 - 1.5 2.5 NaN 1.5 - 1.9 1.3 - 1.5 0.4 1.7 - 2.9 </code></pre> <p>Reproducible data</p> <pre><code>df = pd.DataFrame([0.647,0.88,0,0.73,'1.7 - 2.1','1.2 - 1.5',2.5 ,np.NaN,'1.5 - 1.9','1.3 - 1.5',0.4,'1.7 - 2.9'],columns=['Average Weight (Kg)']) </code></pre> <p>where I would like to take average of range entries and replace it in the dataframe e.g. 1.7 - 2.1 will be replaced by 1.9 , following code doesn't work <code>TypeError: 'float' object is not iterable</code></p> <pre><code>np.where(df['Average Weight (Kg)'].str.contains('-'), df['Average Weight (Kg)'].str.split('-') .apply(lambda x: statistics.mean((list(map(float, x)) ))), df['Average Weight (Kg)']) </code></pre>
[ { "answer_id": 74602175, "author": "Christian Sloper", "author_id": 8111755, "author_profile": "https://Stackoverflow.com/users/8111755", "pm_score": 2, "selected": true, "text": "new_average =(df.avg.str.split('-').str[1].astype(float) + df.avg.str.split('-').str[0].astype(float) ) / 2\ndf[\"avg\"] = new_average.fillna(df.avg)\n 0 0.647\n1 0.880\n2 0.000\n3 0.730\n4 1.900\n5 1.350\n6 2.500\n7 NaN\n8 1.700\n9 1.400\n10 0.400\n11 2.300\nName: avg2, dtype: float64\n" }, { "answer_id": 74602258, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": false, "text": "\\s-\\s float df['Average Weight (Kg)'] = df['Average Weight (Kg)'].astype(\n str).str.split(r'\\s-\\s').explode().astype(float).groupby(level=0).mean()\n Average Weight (Kg)\n0 0.647\n1 0.880\n2 0.000\n3 0.730\n4 1.900\n5 1.350\n6 2.500\n7 NaN\n8 1.700\n9 1.400\n10 0.400\n11 2.300\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15381947/" ]
74,601,928
<p>I am trying to scrape the link from a button. If I click the button, it opens a new tab and I can't navigate in it. So I thought I'd scrape the link, go to it via webdriver.get(link) and do it that way since this will be a background program. I cannot find any tutorials on this using the most recent version of selenium. This is in Python</p> <p>I tried using</p> <pre><code>wd.find_element(&quot;xpath&quot;, 'xpath here') </code></pre> <p>but that just scrapes the button title. Is there a different tag I should be using?</p> <p>I've also tried just clicking the button but that opens a new tab and I don't know how to navigate on it, since it doesn't work by default and I'm still fairly new to Chromedriver.</p> <p>I can't use beautifulsoup to my knowledge, since the webpage must be logged in.</p>
[ { "answer_id": 74602175, "author": "Christian Sloper", "author_id": 8111755, "author_profile": "https://Stackoverflow.com/users/8111755", "pm_score": 2, "selected": true, "text": "new_average =(df.avg.str.split('-').str[1].astype(float) + df.avg.str.split('-').str[0].astype(float) ) / 2\ndf[\"avg\"] = new_average.fillna(df.avg)\n 0 0.647\n1 0.880\n2 0.000\n3 0.730\n4 1.900\n5 1.350\n6 2.500\n7 NaN\n8 1.700\n9 1.400\n10 0.400\n11 2.300\nName: avg2, dtype: float64\n" }, { "answer_id": 74602258, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": false, "text": "\\s-\\s float df['Average Weight (Kg)'] = df['Average Weight (Kg)'].astype(\n str).str.split(r'\\s-\\s').explode().astype(float).groupby(level=0).mean()\n Average Weight (Kg)\n0 0.647\n1 0.880\n2 0.000\n3 0.730\n4 1.900\n5 1.350\n6 2.500\n7 NaN\n8 1.700\n9 1.400\n10 0.400\n11 2.300\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19917796/" ]
74,601,949
<p>I would like to generate a deck of card objects in a standard, 52 card deck of playing cards that contain information about each card's suit and rank using C++.</p> <p>The way I have been doing this so far is creating enumerated types for both the &quot;Rank&quot; and &quot;Suit&quot; information. So:</p> <pre><code>enum Rank {Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King}; enum Suit {Heart, Spades, Diamonds, Clubs}; </code></pre> <p>Then, I define a class 'Card' like this: `</p> <pre><code>class Card { public: Rank CardRank; Suit CardSuit; }; </code></pre> <p>` Now I need to generate an exhaustive list of all card objects using the two enumerated types (which I was going to do with some kind of &quot;Generate Deck&quot; function&quot;). This sounds like it's going to involve some kind of for loop.</p> <p>I tried to adapt the answer <a href="https://stackoverflow.com/questions/261963/how-can-i-iterate-over-an-enum">here </a>to my situation, which looked like:</p> <pre><code>for ( int i = Ace; i != King; i++ ) { Card DummyCard; DummyCard.CardRank = static_cast&lt;Rank&gt;(i); std::cout &lt;&lt; &quot;This is &quot; &lt;&lt; DummyCard.CardRank &lt;&lt; std::endl; //This line is just to check what the program is doing </code></pre> <p>};</p> <p>I'm having two problems:</p> <ol> <li><p>The program just counts the int values, rather than returning what I want (which is the rank values).</p> </li> <li><p>That answer was dealing only with iterating over one a single enum and didn't deal with two enum types that are part of a class. I imagine I would need a nested for loop to iterate over the suits (in addition to the ranks), but I'm not really sure what that would look like.</p> </li> </ol> <p>So how can I iterate over two enum types that are both part of a class in order to generate an exhaustive list of class objects?</p>
[ { "answer_id": 74602110, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\n\nenum Rank {Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King};\nenum Suit {Heart, Spades, Diamonds, Clubs};\n\n\n\nstruct Card { \n Rank CardRank;\n Suit CardSuit;\n};\n\nint main() {\n std::vector<Card> cards;\n for (int rank = 0; rank < King+1; ++rank) { \n for (int suit = 0; suit < Clubs+1; ++ suit) {\n cards.push_back({static_cast<Rank>(rank),static_cast<Suit>(suit)});\n }\n }\n\n for (const auto& card : cards) { \n std::cout << card.CardRank << \" \" << card.CardSuit <<\"\\n\";\n } \n \n}\n static_cast<Rank>(i) Rank int Rank int i != King King i < King+1;" }, { "answer_id": 74602310, "author": "LimikEcho", "author_id": 20533779, "author_profile": "https://Stackoverflow.com/users/20533779", "pm_score": 1, "selected": false, "text": "std::map<Rank, std::string> std::map<Suit, std::string> i != King i <= King for (int r = Ace; r <= King; ++r) {\n for (int s = Heart; s <= Clubs; ++s) {\n Card DummyCard;\n DummyCard.CardRank = static_cast<Rank>(r);\n DummyCard.CardSuit = static_cast<Suit>(s);\n std::cout << r << \" of \" << s << std::endl;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583612/" ]
74,601,979
<p>I have a pyspark dataframe <code>store_df</code> :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">store</th> <th style="text-align: center;">ID</th> <th style="text-align: center;">Div</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">637</td> <td style="text-align: center;">4000000970</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">637</td> <td style="text-align: center;">4000000435</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">637</td> <td style="text-align: center;">4000055542</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">637</td> <td style="text-align: center;">4000042206</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">638</td> <td style="text-align: center;">2200015935</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">638</td> <td style="text-align: center;">2200000483</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">638</td> <td style="text-align: center;">4000014114</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">640</td> <td style="text-align: center;">4000000162</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">640</td> <td style="text-align: center;">2200000067</td> <td style="text-align: center;">Pac</td> </tr> <tr> <td style="text-align: center;">642</td> <td style="text-align: center;">2200000067</td> <td style="text-align: center;">Mac</td> </tr> <tr> <td style="text-align: center;">642</td> <td style="text-align: center;">4000044148</td> <td style="text-align: center;">Mac</td> </tr> <tr> <td style="text-align: center;">642</td> <td style="text-align: center;">4000014114</td> <td style="text-align: center;">Mac</td> </tr> </tbody> </table> </div> <p>I want to remove <code>ID</code>(present in store_df) from the dataframe <code>final_list</code> dynamically for each <code>store</code> in store_df based on <code>Div</code>.</p> <p><code>final_list</code> pyspark df :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Div</th> <th style="text-align: center;">ID</th> <th style="text-align: center;">Rank</th> <th style="text-align: center;">Category</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000970</td> <td style="text-align: center;">1</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000432</td> <td style="text-align: center;">2</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000405</td> <td style="text-align: center;">3</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000042431</td> <td style="text-align: center;">4</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200028596</td> <td style="text-align: center;">5</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000032</td> <td style="text-align: center;">6</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200028594</td> <td style="text-align: center;">7</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000014114</td> <td style="text-align: center;">8</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2230001789</td> <td style="text-align: center;">9</td> <td style="text-align: center;">D</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001789</td> <td style="text-align: center;">10</td> <td style="text-align: center;">C</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001787</td> <td style="text-align: center;">11</td> <td style="text-align: center;">D</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001786</td> <td style="text-align: center;">12</td> <td style="text-align: center;">C</td> </tr> <tr> <td style="text-align: center;">Mac</td> <td style="text-align: center;">2200001789</td> <td style="text-align: center;">1</td> <td style="text-align: center;">C</td> </tr> <tr> <td style="text-align: center;">Mac</td> <td style="text-align: center;">2200001787</td> <td style="text-align: center;">2</td> <td style="text-align: center;">D</td> </tr> <tr> <td style="text-align: center;">Mac</td> <td style="text-align: center;">2200001786</td> <td style="text-align: center;">3</td> <td style="text-align: center;">C</td> </tr> </tbody> </table> </div> <p>For eg:for store 637 the <code>upd_final_list</code> should look like this(<code>ID</code> 4000000970 eliminated):-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Div</th> <th style="text-align: center;">ID</th> <th style="text-align: center;">Rank</th> <th style="text-align: center;">Category</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000432</td> <td style="text-align: center;">2</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000405</td> <td style="text-align: center;">3</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000042431</td> <td style="text-align: center;">4</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200028596</td> <td style="text-align: center;">5</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000000032</td> <td style="text-align: center;">6</td> <td style="text-align: center;">A</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200028594</td> <td style="text-align: center;">7</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">4000014114</td> <td style="text-align: center;">8</td> <td style="text-align: center;">B</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2230001789</td> <td style="text-align: center;">9</td> <td style="text-align: center;">D</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001789</td> <td style="text-align: center;">10</td> <td style="text-align: center;">C</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001787</td> <td style="text-align: center;">11</td> <td style="text-align: center;">D</td> </tr> <tr> <td style="text-align: center;">Pac</td> <td style="text-align: center;">2200001786</td> <td style="text-align: center;">12</td> <td style="text-align: center;">C</td> </tr> </tbody> </table> </div> <p>Likewise this list is to be customised for other stores based on their <code>ID</code>. How do I do this?</p>
[ { "answer_id": 74602110, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\n\nenum Rank {Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King};\nenum Suit {Heart, Spades, Diamonds, Clubs};\n\n\n\nstruct Card { \n Rank CardRank;\n Suit CardSuit;\n};\n\nint main() {\n std::vector<Card> cards;\n for (int rank = 0; rank < King+1; ++rank) { \n for (int suit = 0; suit < Clubs+1; ++ suit) {\n cards.push_back({static_cast<Rank>(rank),static_cast<Suit>(suit)});\n }\n }\n\n for (const auto& card : cards) { \n std::cout << card.CardRank << \" \" << card.CardSuit <<\"\\n\";\n } \n \n}\n static_cast<Rank>(i) Rank int Rank int i != King King i < King+1;" }, { "answer_id": 74602310, "author": "LimikEcho", "author_id": 20533779, "author_profile": "https://Stackoverflow.com/users/20533779", "pm_score": 1, "selected": false, "text": "std::map<Rank, std::string> std::map<Suit, std::string> i != King i <= King for (int r = Ace; r <= King; ++r) {\n for (int s = Heart; s <= Clubs; ++s) {\n Card DummyCard;\n DummyCard.CardRank = static_cast<Rank>(r);\n DummyCard.CardSuit = static_cast<Suit>(s);\n std::cout << r << \" of \" << s << std::endl;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74601979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14353779/" ]
74,602,023
<p>I have a Discord Bot, it turns on, but it doesn't answer to commands. Here's my code</p> <pre><code>const Discord = require(&quot;discord.js&quot;); const client = new Discord.Client( {intents: 32767}, ); { partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'USER', 'GUILD_MEMBER'] } client.on('ready', () =&gt; { console.log('Estoy ON') client.user.setActivity('Ark Survival Evolved', { type: &quot;PLAYING&quot;}); }); client.once('message', (message) =&gt; { if(message.content.startsWith('ping')) { message.channel.send(`pong !!`); } }); client.login('MY TOKEN'); </code></pre> <p>I need help. I tried to do everything, but it doesn't work. I'm in the latest version of node.js and in the latest version in discord.js I have tried in 5 versions, but I can't do anything.</p> <p>I tried to use a prefix, without prefix... But it dont works. I have tried 3 codes and nothing.</p>
[ { "answer_id": 74602107, "author": "ShadowCrafter_01", "author_id": 15174310, "author_profile": "https://Stackoverflow.com/users/15174310", "pm_score": 0, "selected": false, "text": "client.on('messageCreate', message => {\n if(message.content.startsWith('ping')) {\n message.channel.send(`pong !!`);\n }\n});\n" }, { "answer_id": 74607230, "author": "Jeffplays2005", "author_id": 15120975, "author_profile": "https://Stackoverflow.com/users/15120975", "pm_score": 1, "selected": false, "text": "32767 message Discord.Client const client = new Discord.Client({\n intents: [\n Discord.GatewayIntentBits.GuildMessages,\n Discord.GatewayIntentBits.DirectMessages,\n Discord.GatewayIntentBits.MessageContent\n ],\n partials: [\n Discord.Partials.User,\n Discord.Partials.Message\n Discord.Partials.Channel\n Discord.Partials.Reaction\n Discord.Partials.GuildMember\n ]\n});\n\nclient.on('ready', () => {\n console.log('Estoy ON');\n client.user.setActivity('Ark Survival Evolved', { type: \"PLAYING\"});\n});\n\nclient.once('messageCreate', (message) => {\n if(message.content.startsWith('ping')) {\n message.channel.send(`pong !!`);\n }\n});\n\nclient.login('token');\n message messageCreate" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624394/" ]
74,602,029
<p>I have two complex objects that have some form of lifetime relation between each other. My goal is to remove this relation to have both objects completely independent.</p> <p>Is there a quick way to tell what causes lifetime relations between objects?</p>
[ { "answer_id": 74602107, "author": "ShadowCrafter_01", "author_id": 15174310, "author_profile": "https://Stackoverflow.com/users/15174310", "pm_score": 0, "selected": false, "text": "client.on('messageCreate', message => {\n if(message.content.startsWith('ping')) {\n message.channel.send(`pong !!`);\n }\n});\n" }, { "answer_id": 74607230, "author": "Jeffplays2005", "author_id": 15120975, "author_profile": "https://Stackoverflow.com/users/15120975", "pm_score": 1, "selected": false, "text": "32767 message Discord.Client const client = new Discord.Client({\n intents: [\n Discord.GatewayIntentBits.GuildMessages,\n Discord.GatewayIntentBits.DirectMessages,\n Discord.GatewayIntentBits.MessageContent\n ],\n partials: [\n Discord.Partials.User,\n Discord.Partials.Message\n Discord.Partials.Channel\n Discord.Partials.Reaction\n Discord.Partials.GuildMember\n ]\n});\n\nclient.on('ready', () => {\n console.log('Estoy ON');\n client.user.setActivity('Ark Survival Evolved', { type: \"PLAYING\"});\n});\n\nclient.once('messageCreate', (message) => {\n if(message.content.startsWith('ping')) {\n message.channel.send(`pong !!`);\n }\n});\n\nclient.login('token');\n message messageCreate" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2600312/" ]
74,602,057
<p>I have the following api route:</p> <pre><code>GET /api/v1/users POST /api/v1/users // middleware auth </code></pre> <p>In my <code>api.php</code> I have the following code for this:</p> <pre class="lang-php prettyprint-override"><code>Route::group(['prefix' =&gt; 'v1'], function() { require __DIR__ . '/v1/api/users.php'; }); </code></pre> <p>In my <code>v1/api/users.php</code> I have this code:</p> <pre class="lang-php prettyprint-override"><code>Route::middleware('auth:sanctum')-&gt;group(function () { Route::post('/users', function (Request $request) { return []; })-&gt;name('create'); }); Route::get('/users', function (Request $request) { return []; })-&gt;name('index'); </code></pre> <p>My goal is to give the name a prefix <code>users.</code>. So that I can then the route name: <code>users.delete</code> or <code>users.index</code> as the name. <strong>Here my attempt:</strong> For this reason I tried to wrap the above code into a Route::group:</p> <pre class="lang-php prettyprint-override"><code>Route::group(['name' =&gt; 'users.'], function() { Route::middleware('auth:sanctum')-&gt;group(function () { Route::post('/users', function (Request $request) { return $request-&gt;user(); })-&gt;name('delete'); Route::get('/users', function (Request $request) { return []; })-&gt;name('index'); }); </code></pre> <p><strong>Problem</strong> However, Laravel then no longer recognises the wrapped routes. How can I rewrite this so that it works?</p>
[ { "answer_id": 74602112, "author": "John Zwarthoed", "author_id": 4920105, "author_profile": "https://Stackoverflow.com/users/4920105", "pm_score": 2, "selected": true, "text": "Route::name('users.')->group(function () {\n Route::get('/users', function () {\n // Route assigned name \"users.index\"...\n })->name('index');\n});\n" }, { "answer_id": 74602245, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": 0, "selected": false, "text": "name() middleware() Route::middleware('auth:sanctum')->name('users.')->group(function () {\n\n Route::post('/users', function (Request $request) {\n return $request->user();\n })->name('delete');\n\n Route::get('/users', function (Request $request) {\n return [];\n })->name('index');\n});\n group() Route::group(['name' => 'users.', 'middleware' => 'auth:sanctum'], function() {\n Route::post('/users', function (Request $request) {\n return $request->user();\n })->name('delete');\n\n Route::get('/users', function (Request $request) {\n return [];\n })->name('index');\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14807111/" ]
74,602,061
<p>I have function in C with 3 params. I want to call that function with pre-defined values. Is there any solution?</p> <p>My idea which does not work.</p> <pre><code>#define PRE_DEFINED_MACRO (10, 15 , true) void myFunc(uint8_t temp, uint32_t value, bool valid) { .... } .... //call the function like that myFunc(PRE_DEFINED_MACRO); </code></pre>
[ { "answer_id": 74602160, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 3, "selected": true, "text": "myFunc(PRE_DEFINED_MACRO);\n myFunc((10, 15 , true));\n myFunc PRE_DEFINED_MACRO;\n #define MYFUNC_ARGS 10, 15 , true\n\n// ...\n\nmyFunc(MYFUNC_ARGS);\n myFunc()" }, { "answer_id": 74602178, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "#define PRE_DEFINED_MACRO 10, 15, true\n myFunc((10, 15, true));" }, { "answer_id": 74602353, "author": "Peter - Reinstate Monica", "author_id": 3150802, "author_profile": "https://Stackoverflow.com/users/3150802", "pm_score": 1, "selected": false, "text": "#define MY_FUNC_DEFAULTS() myFunc(10, 15, true)\n if(cond) MY_FUNC_DEFAULTS(); else g(); void myFunc(uint8_t temp = 10, uint32_t value = 15, bool valid = true);\n myFunc();\nmyFunc(1);\nmyFunc(1,2);\nmyFunc(1,2,false);\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5166312/" ]
74,602,093
<p>I was wondering if there is a way to test a function embedded within another function in Scala? Or the only to test it is to lift it as a top level function??</p> <pre class="lang-scala prettyprint-override"><code> def processNumbers(n: Int): Int = { def isEven(num: Int): Boolean = num % 2 == 0 if (isEven(n)) 0 else -1 } </code></pre> <p>For example, in the code snippet above I would like to be able to unit test <code>isEven</code> without having to make it the top level function.</p> <p>By &quot;top-level&quot;, I meant writing it at the same level as the &quot;parent&quot; function. In this case it would look like:</p> <pre class="lang-scala prettyprint-override"><code> def isEven(num: Int): Boolean = num % 2 == 0 def processNumbers(n: Int): Int = if (isEven(n)) 0 else -1 </code></pre>
[ { "answer_id": 74602365, "author": "Mateusz Kubuszok", "author_id": 1305121, "author_profile": "https://Stackoverflow.com/users/1305121", "pm_score": 2, "selected": false, "text": "private" }, { "answer_id": 74603221, "author": "senjin.hajrulahovic", "author_id": 7451566, "author_profile": "https://Stackoverflow.com/users/7451566", "pm_score": 2, "selected": true, "text": "public class StackoverflowQuestionClass {\n public int processNumbers(int n) {\n return this.isEven$1(n) ? 0 : -1;\n }\n\n private final boolean isEven$1(int num) {\n return num % 2 == 0;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879109/" ]
74,602,128
<p>I'm wondering if Tensorflow Machine Learning Model can train data that has None valuess? I have a Data table with multiple data (in each row) and in some of these rows, there are columns with None/Null value:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>50</td> <td>None</td> <td>2</td> </tr> <tr> <td>2</td> <td>100</td> <td>None</td> </tr> </tbody> </table> </div> <p>Or should I not have None values in my dataset and instead set all of them to 0? But then I think 0 is not a really good representation of the value because the reason why there are None values is simply because I couldn't get data for them. But 0 kind of means like a value...</p>
[ { "answer_id": 74602365, "author": "Mateusz Kubuszok", "author_id": 1305121, "author_profile": "https://Stackoverflow.com/users/1305121", "pm_score": 2, "selected": false, "text": "private" }, { "answer_id": 74603221, "author": "senjin.hajrulahovic", "author_id": 7451566, "author_profile": "https://Stackoverflow.com/users/7451566", "pm_score": 2, "selected": true, "text": "public class StackoverflowQuestionClass {\n public int processNumbers(int n) {\n return this.isEven$1(n) ? 0 : -1;\n }\n\n private final boolean isEven$1(int num) {\n return num % 2 == 0;\n }\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624481/" ]
74,602,141
<p>I need to extract the time from an excel file. The time in excel is expressed in hours:minutes:seconds. The c# code i have that reads the time is:</p> <pre><code>DateTime dt = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString()); string GetTime = String.Format(&quot;{0:t}&quot;, dt); </code></pre> <p>This code works perfect with one file but when i insert another similar file it does not reads the time. Does anyone know why this happens.</p> <p>Excel table that DOES read the time:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>Date</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>18/11/2022</td> <td>11:51:00</td> </tr> </tbody> </table> </div> <p>Excel table that DOES NOT read the time:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>Date</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>08/08/2022</td> <td>06:54:00</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74602334, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 2, "selected": false, "text": "DateTime Value TimeSpan time = ((DateTime)worksheet.Cells[row, 3].Value).TimeOfDay;\n" }, { "answer_id": 74621672, "author": "Valkyrie", "author_id": 19175784, "author_profile": "https://Stackoverflow.com/users/19175784", "pm_score": 0, "selected": false, "text": "FromOADate DateTime dt = DateTime.FromOADate((double)worksheet.Cells[row, 3].Value); " } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19175784/" ]
74,602,161
<p>Enviroment:</p> <p>1 Linux Serves Micro integrator installed (4.1.0) Micro Integrator Dashboard installed (4.1.0)</p> <p>The micro-integrator connects to the Dashboard, but when I try to login, the dashboard says &quot;No running micro integrator instances found. Pls start a server a login&quot;:</p> <p><a href="https://i.stack.imgur.com/vPq7W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vPq7W.png" alt="enter image description here" /></a></p> <p>any help?</p> <p>Thanks! Daniel</p> <p>I reviewed both deployment.toml files, and everything seems to be ok.</p>
[ { "answer_id": 74602334, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 2, "selected": false, "text": "DateTime Value TimeSpan time = ((DateTime)worksheet.Cells[row, 3].Value).TimeOfDay;\n" }, { "answer_id": 74621672, "author": "Valkyrie", "author_id": 19175784, "author_profile": "https://Stackoverflow.com/users/19175784", "pm_score": 0, "selected": false, "text": "FromOADate DateTime dt = DateTime.FromOADate((double)worksheet.Cells[row, 3].Value); " } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446823/" ]
74,602,197
<p>When I try to update a Tafel record, I receive an error. Restaurant has a navigational collection of Tafels. I'm not quite sure if I should add the restaurant as a parameter but a Tafel has a composite primary key and restaurantId is part of it (together with a tablenumber)... I'm quite new to EF.. I check for possible nulls at first, then if they both exist and whether the 'tafel' record has any changes to it.</p> <pre><code>public void UpdateTafel(Tafel tafel, Restaurant restaurant) { if (tafel == null) throw new RestaurantManagerException(&quot;UpdateTafel: Tafel mag niet null zijn&quot;); if (restaurant == null) throw new RestaurantManagerException(&quot;UpdateTafel: Restaurant mag niet null zijn&quot;); try { if (!_restaurantRepository.BestaatRestaurant(restaurant.Id)) throw new RestaurantManagerException(&quot;GeefAlleTafelsVanRestaurant - restaurant bestaat niet&quot;); if (!_restaurantRepository.BestaatTafel(tafel.Tafelnummer, restaurant)) throw new RestaurantManagerException(&quot;GeefAlleTafelsVanRestaurant - tafel bestaat niet&quot;); Tafel db = _restaurantRepository.GeefTafel(tafel.Tafelnummer, restaurant); if (tafel.IsDezelfde(db)) throw new ReservatieManagerException(&quot;Niks gewijzigd&quot;); _restaurantRepository.UpdateTafel(tafel, restaurant); } catch (Exception ex) { throw new ReservatieManagerException(&quot;UpdateTafel&quot;, ex); } } </code></pre> <p>However when he gets to the repository method where EF has to actually update the said Tafel record with following method:</p> <pre><code>public void UpdateTafel(Tafel tafel, Restaurant restaurant) { _context.Tafels.Update(tafel); _context.SaveChanges(); } </code></pre> <p>I receive an exception stating that another instance of Restaurant with the same key is already being tracked allthough I don't see quite how/where this happens...</p> <pre><code> Inner Exception 1: InvalidOperationException: The instance of entity type 'Restaurant' cannot be tracked because another instance with the key value '{Id: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. </code></pre> <pre><code>public void UpdateTafel(Tafel tafel, Restaurant restaurant) { _context.Entry(restaurant).State = EntityState.Detached; _context.Tafels.Update(tafel); _context.SaveChanges(); } </code></pre>
[ { "answer_id": 74602432, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 1, "selected": false, "text": "tafel .Find .Update" }, { "answer_id": 74606607, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 0, "selected": false, "text": "if (!_restaurantRepository.BestaatRestaurant(restaurant.Id)) throw new RestaurantManagerException(\"GeefAlleTafelsVanRestaurant - restaurant bestaat niet\");\n var restaurant = _context.Restaurants.SingleOrDefault(r => r.Id == restaurantId);\n AsNoTracking() public void UpdateTafel(TafelViewModel tafel, int restaurantId)\n{\n if (tafel == null) throw new RestaurantManagerException(\"UpdateTafel: Tafel mag niet null zijn\");\n\n try\n {\n var restaurant = _restaurantRepository.BestaatRestaurant(restaurantId); // Fetch the restaurant and return it after validating, Throw if not found/valid.\n\n if (!_restaurantRepository.BestaatTafel(tafel.Tafelnummer)) \n throw new RestaurantManagerException(\"GeefAlleTafelsVanRestaurant - tafel bestaat niet\");\n Tafel existingTafel = _restaurantRepository.GeefTafel(tafel.Tafelnummer); // Ensure this eager loads Tafel.Restaurant\n // If the Restaurant has changed then update the reference in our tracked entities.\n if (existingTafel.Restaurant.Id != restaurant.Id)\n existingTafel.Restaurant = restaurant; \n // I'm assuming this is doing something like updating the database instance with the values in the passed in reference? If so you could pass the Restaurant instance above in and do that check/update here.\n if (tafel.IsDezelfde(existingTafel)) throw new ReservatieManagerException(\"Niks gewijzigd\");\n _restaurantRepository.SaveChanges();\n }\n catch (Exception ex)\n {\n throw new ReservatieManagerException(\"UpdateTafel\", ex);\n }\n}\n SaveChanges Update Update" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14687910/" ]
74,602,227
<p>I'm working on a code to filter my table, but I'm struggling to set the 'Key:=Range(&quot;&quot;)' , so far I've tested a code without setting Dims and it works, but I want a more pratical approach, so the code will work in all worksheets (active worksheet) in my workbook. Error im getting: Method range of object _'Global' failed. Error 1004</p> <p>So on resume, im new on VBA and dont now how to set MyTable(Tbl) on the 'Key:=Range(&quot;Tbl[[#All],[Column1]]&quot;)</p> <pre><code>Sub MAKE_FILTER() Dim ws As Worksheet Dim wb As Workbook Set wb = ThisWorkbook Set ws = ActiveSheet Dim Tbl As Object Set Tbl = ws.ListObjects(1) Tbl.Range.AutoFilter Field:=1, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor Tbl.Sort.SortFields.Clear Tbl.Sort.SortFields.Add2 Key:=Range(&quot;Tbl[[#All],[DANFE]]&quot;), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With Tbl.Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With Tbl.Sort.SortFields.Clear Tbl.Sort.SortFields.Add2 Key:=Range(&quot;Tbl[[#All],[Nº NF-e]]&quot;), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With Tbl.Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub </code></pre> <p>Without DIMs:</p> <pre><code>Sub Macro1() 'without DIMs ActiveSheet.ListObjects(&quot;Tabela14212255&quot;).Range.AutoFilter Field:=1, _ Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor 'ok ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;).Sort. _ SortFields.Clear 'ok ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;).Sort. _ SortFields.Add2 Key:=Range(&quot;Tabela14212255[[#All],[DANFE]]&quot;), SortOn:= _ xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;). _ Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;).Sort. _ SortFields.Clear ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;).Sort. _ SortFields.Add2 Key:=Range(&quot;Tabela14212255[[#All],[Nº NF-e]]&quot;), SortOn:= _ xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets(&quot;NOVEMBRO 2022&quot;).ListObjects(&quot;Tabela14212255&quot;). _ Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub </code></pre>
[ { "answer_id": 74602432, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 1, "selected": false, "text": "tafel .Find .Update" }, { "answer_id": 74606607, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 0, "selected": false, "text": "if (!_restaurantRepository.BestaatRestaurant(restaurant.Id)) throw new RestaurantManagerException(\"GeefAlleTafelsVanRestaurant - restaurant bestaat niet\");\n var restaurant = _context.Restaurants.SingleOrDefault(r => r.Id == restaurantId);\n AsNoTracking() public void UpdateTafel(TafelViewModel tafel, int restaurantId)\n{\n if (tafel == null) throw new RestaurantManagerException(\"UpdateTafel: Tafel mag niet null zijn\");\n\n try\n {\n var restaurant = _restaurantRepository.BestaatRestaurant(restaurantId); // Fetch the restaurant and return it after validating, Throw if not found/valid.\n\n if (!_restaurantRepository.BestaatTafel(tafel.Tafelnummer)) \n throw new RestaurantManagerException(\"GeefAlleTafelsVanRestaurant - tafel bestaat niet\");\n Tafel existingTafel = _restaurantRepository.GeefTafel(tafel.Tafelnummer); // Ensure this eager loads Tafel.Restaurant\n // If the Restaurant has changed then update the reference in our tracked entities.\n if (existingTafel.Restaurant.Id != restaurant.Id)\n existingTafel.Restaurant = restaurant; \n // I'm assuming this is doing something like updating the database instance with the values in the passed in reference? If so you could pass the Restaurant instance above in and do that check/update here.\n if (tafel.IsDezelfde(existingTafel)) throw new ReservatieManagerException(\"Niks gewijzigd\");\n _restaurantRepository.SaveChanges();\n }\n catch (Exception ex)\n {\n throw new ReservatieManagerException(\"UpdateTafel\", ex);\n }\n}\n SaveChanges Update Update" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17684300/" ]
74,602,231
<pre><code>I wanna print the rule like following: rule(0,0,0) = 0 rule(0,0,1) = 1 rule(0,1,0) = 1 rule(0,1,1) = 1 rule(1,0,0) = 1 rule(1,0,1) = 0 rule(1,1,0) = 0 rule(1,1,1) = 0 </code></pre> <p>I tried to write a set of “if-else” conditions that test for zeroes and ones in the input values, returning the corresponding value from the table as output but it didnt work</p>
[ { "answer_id": 74602293, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 1, "selected": false, "text": "rule <- function(x, y, z) {\n +((4 * x + 2 * y + z) %in% 1:4)\n}\n rule <- function(x, y, z) {\n bitwXor(x, bitwOr(y, z))\n}\n rule1 <- function(a, b, c) +(abs(4 * a + 2 * b + c - 2.5) < 2)\nrule2 <- function(a, b, c) +xor(a, b | c)\nrule3 <- function(x, y, z) +((4 * x + 2 * y + z) %in% 1:4)\nrule4 <- function(x, y, z) bitwXor(x, bitwOr(y, z))\n\nabc <- matrix(sample(0:1, 3e6, 1), 1e6, 3)\n\nmicrobenchmark::microbenchmark(\n rule1 = rule1(abc[, 1], abc[, 2], abc[, 3]),\n rule2 = rule2(abc[, 1], abc[, 2], abc[, 3]),\n Thomas1 = rule3(abc[, 1], abc[, 2], abc[, 3]),\n Thomas2 = rule4(abc[, 1], abc[, 2], abc[, 3]),\n check = \"identical\"\n)\n Unit: milliseconds\n expr min lq mean median uq max neval\n rule1 16.1315 22.82880 32.91071 24.48080 28.29635 113.1915 100\n rule2 33.6093 40.93665 50.12914 44.77415 48.90045 128.0033 100\n Thomas1 26.6938 34.78615 43.34770 37.63255 42.49940 114.3973 100\n Thomas2 9.1119 12.25080 18.46705 16.26445 18.46835 105.1263 100\n" }, { "answer_id": 74602297, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 1, "selected": false, "text": "switch rule <- function(a, b, c) {\n x <- paste0(a, b, c)\n switch(\n x,\n \"000\" = 0,\n \"001\" = 1,\n ......\n )\n}\n" }, { "answer_id": 74602358, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 2, "selected": false, "text": "rule <- function(a, b, c) +(abs(4*a + 2*b + c - 2.5) < 2)\n rule <- function(a, b, c) +xor(a, b | c)\n rule1 <- function(a, b, c) +(abs(4*a + 2*b + c - 2.5) < 2)\nrule2 <- function(a, b, c) +xor(a, b | c)\nrule3 <- function(x, y, z) +((4 * x + 2 * y + z) %in% 1:4)\n\nabc <- matrix(sample(0:1, 3e6, 1), 1e6, 3)\n\nmicrobenchmark::microbenchmark(rule1 = rule1(abc[,1], abc[,2], abc[,3]),\n rule2 = rule2(abc[,1], abc[,2], abc[,3]),\n Thomas = rule3(abc[,1], abc[,2], abc[,3]),\n check = \"identical\")\n#> Unit: milliseconds\n#> expr min lq mean median uq max neval\n#> rule1 13.5161 16.58425 20.74505 17.69030 20.22745 53.9513 100\n#> rule2 32.7552 35.05735 39.41473 36.27760 39.38165 74.8564 100\n#> Thomas 24.6562 28.39065 33.78937 29.70875 33.19045 65.9709 100\n" }, { "answer_id": 74602431, "author": "I_O ", "author_id": 20513099, "author_profile": "https://Stackoverflow.com/users/20513099", "pm_score": 0, "selected": false, "text": "rule <- function(first, second, third){\n bits_as_decimal = paste(first, second, third, sep = '') |>\n strtoi(base = 2)\n bits_as_decimal %in% 1:4 |> as.integer()\n}\n strtoi" }, { "answer_id": 74602434, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 1, "selected": true, "text": "rule = function(n1, n2, n3){\n combin = list(c(0,0,0), c(1,0,0), c(0,1,0), c(0,0,1), c(1,1,0), c(1,0,1), c(0,1,1), c(1,1,1))\n result = c(0, 1, 1, 1, 0, 0, 1, 0)\n \n index = which(sapply(combin, function(x){identical(x, c(n1, n2, n3))}))\n result[index]\n}\n\nrule(0, 1, 0)\n[1] 1\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20609481/" ]
74,602,257
<p>I am trying to pass the animationController as an argument to my statefullwidget . But getting this error .</p> <blockquote> <p>The instance member '_controller' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression</p> </blockquote> <p>I am just trying to add animation to a nav change via bottom navigator .</p> <p>my parent widget looks like this .</p> <pre><code>class _DashboardState extends State&lt;Dashboard&gt; with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 150)); _controller.forward(); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } List&lt;Widget&gt; widgetList = [ DashboardView(), CallLogs( animationController: _controller, ), ContactLogs(), UserProfile() ]; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: widgetList[context.watch&lt;NavigationIndex&gt;().index], ), bottomNavigationBar: const BottomNavigator(), ); } } </code></pre> <p>and child looks like this</p> <pre><code>import 'package:flutter/material.dart'; class CallLogs extends StatefulWidget { final AnimationController animationController; const CallLogs({super.key, required this.animationController}); @override State&lt;CallLogs&gt; createState() =&gt; _CallLogsState(); } class _CallLogsState extends State&lt;CallLogs&gt; { @override Widget build(BuildContext context) { return Container( child: const Text(&quot;Call logs&quot;), ); } } </code></pre> <p>Any help will be appreciated . Thanks in advance . Cheers .</p>
[ { "answer_id": 74602368, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "getter State AnimationController get controller => _controller;\n widgetList _controller controller List<Widget> widgetList = [\n DashboardView(),\n CallLogs(\n animationController: controller,\n ),\n ContactLogs(),\n UserProfile()\n ];\n" }, { "answer_id": 74602377, "author": "Rahul", "author_id": 16569443, "author_profile": "https://Stackoverflow.com/users/16569443", "pm_score": 1, "selected": true, "text": "List<Widget> widgetList = List<Widget> get widgetList => " }, { "answer_id": 74602511, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "late late List<Widget> widgetList = [\n DashboardView(),\n CallLogs(\n animationController: _controller,\n ),\n ContactLogs(),\n UserProfile()\n ];\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9194957/" ]
74,602,288
<p>I have a gRPC client and I want to have a method that simplifies its use. The method should return <code>IAsyncEnumerable</code> of items being streamed from the gRPC server. I have a specified timeout for the streaming not to exceed. If the timeout occurs, I want to just walk away with all the items I managed to fetch so far.</p> <p>Here's what I tried to do:</p> <pre class="lang-cs prettyprint-override"><code> public async IAsyncEnumerable&lt;Item&gt; Search( SearchParameters parameters, CancellationToken cancellationToken, IDictionary&lt;string, string&gt; headers = null) { try { await _client.Search( MapInput(parameters), cancellationToken: cancellationToken, deadline: DateTime.UtcNow.Add(_configuration.Timeout), headers: MapHeaders(headers)) .ResponseStream.ForEachAsync(item =&gt; { yield return MapSingleItem(item); // compilation error }); } catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded) { _logger.LogWarning(&quot;Steam finished due to timeout, a limited number of items has been returned&quot;); } } </code></pre> <p>Logically, that should work. However, the <code>yield</code> keyword is not supported within lambdas, so it does not compile. Is there any other way I could write it?</p>
[ { "answer_id": 74603828, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 2, "selected": false, "text": "IAsyncEnumerable<Item> Channel<T> IAsyncEnumerable<Item> break return CancellationTokenSource public async IAsyncEnumerable<Item> Search(\n SearchParameters parameters, \n [EnumeratorCancellation] CancellationToken cancellationToken = default,\n IDictionary<string, string> headers = null)\n{\n Channel<Item> channel = Channel.CreateUnbounded<Item>();\n using var linkedCTS = CancellationTokenSource\n .CreateLinkedTokenSource(cancellationToken);\n\n Task producer = Task.Run(async () =>\n {\n try\n {\n await _client.Search(\n MapInput(parameters),\n cancellationToken: linkedCTS.Token,\n deadline: DateTime.UtcNow.Add(_configuration.Timeout),\n headers: MapHeaders(headers))\n .ResponseStream.ForEachAsync(item =>\n {\n channel.Writer.TryWrite(item);\n }).ConfigureAwait(false);\n channel.Writer.Complete();\n }\n catch (Exception ex) { channel.Writer.Complete(ex); }\n });\n\n try\n {\n await foreach (var item in channel.Reader.ReadAllAsync()\n .ConfigureAwait(false))\n {\n yield return item;\n }\n }\n finally\n {\n linkedCTS.Cancel();\n await producer.ConfigureAwait(false);\n }\n}\n IAsyncEnumerable<Item> OperationCanceledException stoppingToken OperationCanceledException producer" }, { "answer_id": 74604016, "author": "Aron", "author_id": 1808494, "author_profile": "https://Stackoverflow.com/users/1808494", "pm_score": -1, "selected": false, "text": "var input = Observable.Create<Item>((observer, cancellationToken) => \n Task.Factory.StartNew(() =>\n {\n try\n {\n var items = _client.Search(\n MapInput(parameters),\n cancellationToken: cancellationToken,\n deadline: DateTime.UtcNow.Add(_configuration.Timeout),\n headers: MapHeaders(headers));\n foreach(var item in items)\n observer.OnNext(item);\n }\n catch(Exception ex)\n {\n observer.OnError(ex);\n }\n }, TaskCreationOptions.LongRunning)\n);\n\nvar inputObservable = input\n .Publish()\n .RefCount();\n\n\nvar timeout = inputObs\n .Throttle(TimeSpan.FromSeconds(10));\nvar outputObs = inputObservable\n .TakeUntil(timeout);\n \n\nreturn outputObs\n .ToAsyncEnumerable()\n .ToListAsync();\n IEnumerable" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021151/" ]
74,602,330
<p>I am working with Azure's form recognizer service to OCR some factory blueprints. Some of the text in these blueprints are printed vertically, but Azure seems to only do OCR horizontally. However, in their Form recognizer studio the engine is actually OCRing vertically as well, but even when I use their code this does not seem to work for me.</p> <p>Has anyone here had similar issues, and what did they do about this problem? I am essentially looking for some option I can give to the engine to OCR vertical (or any directional) text.</p>
[ { "answer_id": 74603828, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 2, "selected": false, "text": "IAsyncEnumerable<Item> Channel<T> IAsyncEnumerable<Item> break return CancellationTokenSource public async IAsyncEnumerable<Item> Search(\n SearchParameters parameters, \n [EnumeratorCancellation] CancellationToken cancellationToken = default,\n IDictionary<string, string> headers = null)\n{\n Channel<Item> channel = Channel.CreateUnbounded<Item>();\n using var linkedCTS = CancellationTokenSource\n .CreateLinkedTokenSource(cancellationToken);\n\n Task producer = Task.Run(async () =>\n {\n try\n {\n await _client.Search(\n MapInput(parameters),\n cancellationToken: linkedCTS.Token,\n deadline: DateTime.UtcNow.Add(_configuration.Timeout),\n headers: MapHeaders(headers))\n .ResponseStream.ForEachAsync(item =>\n {\n channel.Writer.TryWrite(item);\n }).ConfigureAwait(false);\n channel.Writer.Complete();\n }\n catch (Exception ex) { channel.Writer.Complete(ex); }\n });\n\n try\n {\n await foreach (var item in channel.Reader.ReadAllAsync()\n .ConfigureAwait(false))\n {\n yield return item;\n }\n }\n finally\n {\n linkedCTS.Cancel();\n await producer.ConfigureAwait(false);\n }\n}\n IAsyncEnumerable<Item> OperationCanceledException stoppingToken OperationCanceledException producer" }, { "answer_id": 74604016, "author": "Aron", "author_id": 1808494, "author_profile": "https://Stackoverflow.com/users/1808494", "pm_score": -1, "selected": false, "text": "var input = Observable.Create<Item>((observer, cancellationToken) => \n Task.Factory.StartNew(() =>\n {\n try\n {\n var items = _client.Search(\n MapInput(parameters),\n cancellationToken: cancellationToken,\n deadline: DateTime.UtcNow.Add(_configuration.Timeout),\n headers: MapHeaders(headers));\n foreach(var item in items)\n observer.OnNext(item);\n }\n catch(Exception ex)\n {\n observer.OnError(ex);\n }\n }, TaskCreationOptions.LongRunning)\n);\n\nvar inputObservable = input\n .Publish()\n .RefCount();\n\n\nvar timeout = inputObs\n .Throttle(TimeSpan.FromSeconds(10));\nvar outputObs = inputObservable\n .TakeUntil(timeout);\n \n\nreturn outputObs\n .ToAsyncEnumerable()\n .ToListAsync();\n IEnumerable" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20090214/" ]
74,602,339
<p>Field | Type | Null | Key | Default | Extra</p> <p>| Student_id | int | NO | PRI | NULL | auto_increment</p> <p>As I need when I insert data in table its auto increment automatically insert value but when i try this query <code>insert into student_info values(&quot;Harry&quot;,75,89,50,56);</code> I am getting this error as <strong>ERROR 1136 (21S01): Column count doesn't match value count at row 1</strong></p> <p>And when I write query like this</p> <pre><code>insert into student_info values(1,&quot;Harry&quot;,75,89,50,56); </code></pre> <p>The data get inserted</p> <p>I dont want to insert Student_id by manually as I have declared this column as <code>AUTO_INCREMENT</code></p> <p>Mysql Version 8.0</p>
[ { "answer_id": 74602393, "author": "Sergey Kudriavtsev", "author_id": 625594, "author_profile": "https://Stackoverflow.com/users/625594", "pm_score": 2, "selected": false, "text": "INSERT INTO student_info(Name, Column2, Column3, Column4, Column5) \nVALUES(\"Harry\",75,89,50,56);\n" }, { "answer_id": 74602396, "author": "David Ansermot", "author_id": 785593, "author_profile": "https://Stackoverflow.com/users/785593", "pm_score": 1, "selected": false, "text": "INSERT INTO student_info(Student_id, Name, Col1, Col2, Col3, Col4) \nVALUES('',\"Harry\",75,89,50,56);\n" }, { "answer_id": 74602399, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 3, "selected": true, "text": "INSERT INSERT INTO student_info (Name, SomeValue, AnotherValue, AnotherColumn, AndAnotherColumn) \nVALUES (\"Harry\",75,89,50,56)\n AUTOINCREMENT" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16045443/" ]
74,602,364
<p>so I'm trying to allocate memory for an array of strings thats in a struct: This is the struct:</p> <pre><code>typedef struct{ int aisleNumber; char **aisleProducts; }Aisle; </code></pre> <p>And this is how I allocate the memory:</p> <pre><code>Aisle.aisleProducts = (aisleProducts*)malloc( sizeof(aisleProducts) ); </code></pre> <p>For now, I only need space for one string in the array, hence why I'm not multiplying the size. Still doesn't work and I don't know why...</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 74602425, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "malloc n * sizeof(char*) malloc char* char** #include <stdlib.h>\naisles.aisleProducts = malloc( n * sizeof(*Aisle.aisleProducts) );\n #include <stdlib.h>\naisles.aisleProducts = malloc( n * sizeof(char*) );\n #include <stdlib.h>\naisles.aisleProducts = malloc( sizeof(char* [n]) );\n" }, { "answer_id": 74602463, "author": "MichiBros", "author_id": 10972726, "author_profile": "https://Stackoverflow.com/users/10972726", "pm_score": 1, "selected": false, "text": "// Allocate space for the starting pointers\nAisle.aisleProducts = (char**) malloc(sizeof(char*) * 4);\n// Then more space for each individual string (for convenience, let's give each one of them 64 bytes)\nfor (int i = 0; i < 4; i++)\n{\n Aisle.aisleProducts[i] = (char*) malloc(sizeof(char) * 64);\n}\n// Assign your strings...\n" }, { "answer_id": 74602509, "author": "kun", "author_id": 17072334, "author_profile": "https://Stackoverflow.com/users/17072334", "pm_score": 0, "selected": false, "text": "Aisle* pAisle = (Aisle*)malloc(sizeof(Aisle));\npAisle->aisleProducts = (char**)malloc(sizeof(char*));\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18361723/" ]
74,602,376
<p>I'm trying to copy a string of characters in another string using dynamic memory allocation but it doesn't work:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char* s1, * s2, * s3; s1 = (char*)malloc(11 * sizeof(char)); s2 = (char*)malloc(11 * sizeof(char)); s3 = (char*)malloc(11 * sizeof(char)); fgets(s1, 11, stdin); fgets(s2, 11, stdin); int i = 0; do { *(s3 + i) = *(s1 + i); i++; } while (*(s1 + i) != '\n' &amp;&amp; *(s1 + i) != '\0'); puts(s3); return 0; } </code></pre>
[ { "answer_id": 74602425, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "malloc n * sizeof(char*) malloc char* char** #include <stdlib.h>\naisles.aisleProducts = malloc( n * sizeof(*Aisle.aisleProducts) );\n #include <stdlib.h>\naisles.aisleProducts = malloc( n * sizeof(char*) );\n #include <stdlib.h>\naisles.aisleProducts = malloc( sizeof(char* [n]) );\n" }, { "answer_id": 74602463, "author": "MichiBros", "author_id": 10972726, "author_profile": "https://Stackoverflow.com/users/10972726", "pm_score": 1, "selected": false, "text": "// Allocate space for the starting pointers\nAisle.aisleProducts = (char**) malloc(sizeof(char*) * 4);\n// Then more space for each individual string (for convenience, let's give each one of them 64 bytes)\nfor (int i = 0; i < 4; i++)\n{\n Aisle.aisleProducts[i] = (char*) malloc(sizeof(char) * 64);\n}\n// Assign your strings...\n" }, { "answer_id": 74602509, "author": "kun", "author_id": 17072334, "author_profile": "https://Stackoverflow.com/users/17072334", "pm_score": 0, "selected": false, "text": "Aisle* pAisle = (Aisle*)malloc(sizeof(Aisle));\npAisle->aisleProducts = (char**)malloc(sizeof(char*));\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20624632/" ]
74,602,409
<p>i'm new to kafka and figuring out its behavior.</p> <p>I have a kafka cluster that has three brokers in it. I have given 2GB for the cluster and my cluster disk storage reached 95%. So what i did was deleted the main topic which i used for testing. (This topic has replication factor of 3, min in sync replicas as 2, 8 partitions and retention time of 3 days) Main reason i deleted this topic is i always used this topic and every test data was produced to this topic. My intention was to free up the disk storage.(I thought when i delete the topic, all the persisted message from that topic will get removed so that i will get more disk space from my kafka cluster) When i deleted i noticed two things.</p> <ol> <li>One of the brokers disk usage went down. But other two brokers usage didn't change a bit.</li> <li>When i listed the topics in the cluster, deleted topics had a note infront of them saying &quot;Marked for deletion&quot;</li> </ol> <p>What is the reason for above behaviors ?</p> <p>Btw i have set delete.topic.enable = true and auto create topic also true in properties of Kafka brokers.</p>
[ { "answer_id": 74607046, "author": "nipuna", "author_id": 10866798, "author_profile": "https://Stackoverflow.com/users/10866798", "pm_score": 0, "selected": false, "text": "delete compact" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6844910/" ]
74,602,424
<p>i have a hierarchical query :</p> <pre><code>with temp1 as ( select distinct b.ID, b.LABEL, b.parent_id from my_table b where b.PROG_MODIF_ID=:P225_PROG_MODIF ) ,temp2 as ( select distinct b.ID, b.LABEL, p.id as p_id, b.parent_id from temp1 b left join temp1 p on p.id=b.parent_id ) select distinct b.ID, b.p_id, b.LABEL, b.parent_id from temp2 b start with b.p_id is null connect by prior b.id=b.p_id </code></pre> <p>the results i get with this query are correct but they are not ordered as need be : meaning every parents with its children below, instead they r ordered randomly even though the &quot;parent-child&quot; link is specified <code>b.id=b.p_id</code></p> <p>EDIT : the query at first had <code> order siblings by b.id</code> , but it wasn't working instead it was ordering the parents and siblings all the same and the result was parents in the middle of or below their children. EDIT 2 : i found that the problem was a CASE i was using in the query, somehow for some reason, when i add that CASE column the order goes nuts and when i remove it it works just fine...</p>
[ { "answer_id": 74603433, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "ORDER SIBLINGS BY SELECT DISTINCT\n id,\n label,\n PRIOR id AS p_id,\n parent_id\nFROM my_table\nSTART WITH\n parent_id IS NULL\nAND prog_modif_id = :P225_PROG_MODIF\nCONNECT BY\n PRIOR id = parent_id\nAND prog_modif_id = :P225_PROG_MODIF\nORDER SIBLINGS BY\n label\n" }, { "answer_id": 74611139, "author": "imstuckaf", "author_id": 14235961, "author_profile": "https://Stackoverflow.com/users/14235961", "pm_score": 0, "selected": false, "text": "select distinct \n b.ID,\n b.LABEL,\n b.parent_id\n --case when (select count(*) from budget_equip p where p.parent_id=b.id and p.PROG_MODIF_ID=:P225_PROG_MODIF)>0 then 'underline' else 'none' end as text_decoration\nfrom my_table b\nwhere b.PROG_MODIF_ID=:P225_PROG_MODIF\n\nSTART WITH --p.id IS NULL\n(select count(*) from budget_equip p where p.parent_id=b.id and p.PROG_MODIF_ID=:P225_PROG_MODIF)>0\nCONNECT BY\n PRIOR id = parent_id\nORDER SIBLINGS BY label\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74602424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14235961/" ]