qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,627,930
<p>I'm trying to create a forecast which takes the previous day's 'Forecast' total and adds it to the current day's 'Appt'. Something which is straightforward in Excel but I'm struggling in pandas. At the moment all I can get in pandas using .loc is this:</p> <pre><code>pd.DataFrame({'Date': ['2022-12-01', '2022-12-02','2022-12-03','2022-12-04','2022-12-05'], 'Appt': [12,10,5,4,13], 'Forecast': [37,0,0,0,0] }) </code></pre> <p>What I'm looking for it to do is this:</p> <pre><code>pd.DataFrame({'Date': ['2022-12-01', '2022-12-02','2022-12-03','2022-12-04','2022-12-05'], 'Appt': [12,10,5,4,13], 'Forecast': [37,47,52,56,69] }) </code></pre> <p>E.g. 'Forecast' total on the 1st December is 37. On the 2nd December the value in the 'Appt' column in 10. I want it to select 37 and + 10, then put this in the 'Forecast' column for the 2nd December. Then iterate over the rest of the column.</p> <p>I've tied using .loc() with the index, and experimented with .shift() but neither seem to work for what I'd like. Also looked into .rolling() but I think that's not appropriate either.</p> <p>I'm sure there must be a simple way to do this?</p> <p>Apologies, the original df has 'Date' as a datetime column.</p>
[ { "answer_id": 74628163, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 2, "selected": true, "text": "lubridate dplyr group_split library(dplyr)\nlibrary(lubridate)\n\ndf |>\n mutate(across(everything(), ymd)) |>\n group_by(date1, date2) |>\n mutate(new = list(seq(month(date1), month(date2)))) |>\n unnest_longer(new) |>\n group_split(.keep = FALSE)\n [[1]]\n# A tibble: 10 × 1\n new\n <int>\n 1 3\n 2 4\n 3 5\n 4 6\n 5 7\n 6 8\n 7 9\n 8 10\n 9 11\n10 12\n\n[[2]]\n# A tibble: 4 × 1\n new\n <int>\n1 9\n2 10\n3 11\n4 12\n\n[[3]]\n# A tibble: 3 × 1\n new\n <int>\n1 10\n2 11\n3 12\n\n[[4]]\n# A tibble: 3 × 1\n new\n <int>\n1 10\n2 11\n3 12\n\n[[5]]\n# A tibble: 2 × 1\n new\n <int>\n1 11\n2 12\n\n[[6]]\n# A tibble: 2 × 1\n new\n <int>\n1 11\n2 12\n\n[[7]]\n# A tibble: 12 × 1\n new\n <int>\n 1 1\n 2 2\n 3 3\n 4 4\n 5 5\n 6 6\n 7 7\n 8 8\n 9 9\n10 10\n11 11\n12 12\n\n[[8]]\n# A tibble: 10 × 1\n new\n <int>\n 1 3\n 2 4\n 3 5\n 4 6\n 5 7\n 6 8\n 7 9\n 8 10\n 9 11\n10 12\n\n[[9]]\n# A tibble: 6 × 1\n new\n <int>\n1 7\n2 8\n3 9\n4 10\n5 11\n6 12\n list2env df |>\n mutate(across(everything(), ymd)) |>\n group_by(date1, date2) |>\n mutate(new = list(seq(month(date1), month(date2)))) |>\n unnest_longer(new) |>\n group_split(.keep = FALSE) -> listdf\n\nnames(listdf) <- paste0(\"monthdf\", seq(length(listdf)))\nlist2env(listdf, .GlobalEnv)\n" }, { "answer_id": 74628166, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 0, "selected": false, "text": "purrr::pmap rowwise df %>%\n mutate(across(.fns = as.Date)) %>%\n pmap(~ as.Date(..1:..2))\n pmap_dfr pmap_dfc [[1]]\n[1] \"2018-11-01\" \"2018-11-02\" \"2018-11-03\" \"2018-11-04\" \"2018-11-05\" ...\n\n[[2]]\n[1] \"2018-10-28\" \"2018-10-29\" \"2018-10-30\" \"2018-10-31\" \"2018-11-01\" ...\n\n[[3]]\n[1] \"2019-01-22\" \"2019-01-21\" \"2019-01-20\" \"2019-01-19\" \"2019-01-18\" ...\n\n[[4]]\n[1] \"2019-03-22\" \"2019-03-23\" \"2019-03-24\" \"2019-03-25\" \"2019-03-26\" ...\n\n[[5]]\n[1] \"2018-10-03\" \"2018-10-04\" \"2018-10-05\" \"2018-10-06\" \"2018-10-07\" ...\n\n[[6]]\n[1] \"2018-09-10\" \"2018-09-11\" \"2018-09-12\" \"2018-09-13\" \"2018-09-14\" ...\n\n[[7]]\n[1] \"2020-07-01\" \"2020-07-02\" \"2020-07-03\" \"2020-07-04\" \"2020-07-05\" ...\n\n[[8]]\n[1] \"2018-03-02\" \"2018-03-03\" \"2018-03-04\" \"2018-03-05\" \"2018-03-06\" ...\n\n[[9]]\n[1] \"2018-11-09\" \"2018-11-10\" \"2018-11-11\" \"2018-11-12\" \"2018-11-13\" ...\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74627930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19996578/" ]
74,627,964
<p>I'm receiving an error while using the foreach loop in the blade.php. I have tried many things but everytime i recevie the same error while using foreachloop</p> <p>Here is my code Post.blade.php</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;ul&gt; @foreach($datafromtestmodel as $rows) &lt;li&gt; &lt;p&gt;{{$rows['name']}}&lt;/p&gt; &lt;p&gt;{{$rows['company']}}&lt;/p&gt; &lt;/li&gt; @endforeach &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Controller Function</p> <pre><code>public function index() { $testmodeldata = new testmodel; $datafromtestmodel = $testmodeldata -&gt;abc(); return view('post', compact('datafromtestmodel')); } </code></pre> <p>Model Function</p> <pre><code> public function abc(){ $blabla = ['name' =&gt; 'abc', 'company' =&gt; 'abc company']; return $blabla; } </code></pre> <p>Route</p> <pre><code>Route::get('post','PostController@index'); </code></pre>
[ { "answer_id": 74628158, "author": "Satyandra Shakya", "author_id": 12953436, "author_profile": "https://Stackoverflow.com/users/12953436", "pm_score": 3, "selected": true, "text": "public function abc(){\n $blabla = [['name' => 'abc', 'company' => 'abc company']];\n return $blabla;\n}\n @foreach($datafromtestmodel as $key => $value) //Here $key will be \"name\" and \"company\" and $value will be \"abc\" and \"abc company\" \n <li><p>{{$value}}</p></li>\n @endforeach\n" }, { "answer_id": 74628165, "author": "gaetan-hexadog", "author_id": 20637850, "author_profile": "https://Stackoverflow.com/users/20637850", "pm_score": 0, "selected": false, "text": "$datafromtestmodel ['name' => 'abc', 'company' => 'abc company'] public function abc(){\n $blabla = ['name' => 'abc', 'company' => 'abc company'];\n return [$blabla];\n }\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74627964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645380/" ]
74,628,003
<p>I'm creating an application where it simulates a football album for each user, the logic is that each user can open packages and receive players that in the future can be associated with teams that the user himself created. To save all the players that a user can receive I created a Player model ( many-to-many relationship with users and teams):</p> <pre><code>class Player(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(length=30), nullable=False) birthdate = db.Column(db.Date()) weight = db.Column(db.Numeric(precision=5, scale=2), nullable=False) height = db.Column(db.Integer(), nullable=False) users = db.relationship(User, secondary = 'user_player', overlaps='players') teams = db.relationship('Team', secondary = 'player_team', overlaps='players') </code></pre> <p>As much as a player (card) can be assigned to several users and several teams, it is not possible for a user to receive the same player in duplicate, where he could associate it with another team that he himself created. How can I make a user receive the same player more than once without having to create another record in the database?</p>
[ { "answer_id": 74628204, "author": "Sezer BOZKIR", "author_id": 5942941, "author_profile": "https://Stackoverflow.com/users/5942941", "pm_score": -1, "selected": false, "text": "from django.db import models\n\nclass Publication(models.Model):\n title = models.CharField(max_length=30)\n\n class Meta:\n ordering = ['title']\n\n def __str__(self):\n return self.title\n\nclass Article(models.Model):\n headline = models.CharField(max_length=100)\n publications = models.ManyToManyField(Publication)\n\n class Meta:\n ordering = ['headline']\n\n def __str__(self):\n return self.headline\n a1 = Article(headline='Django lets you build web apps easily')\np1 = Publication(title='The Python Journal')\np2 = Publication(title='Science News')\np3 = Publication(title='Science Weekly')\np1.save()\np2.save()\np3.save()\na1.save()\n a1.publications.add(p1, p2)\na1.publications.add(p3)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16401148/" ]
74,628,024
<p>i'm creating a function like this:</p> <pre><code>fun someFunction( callBack: () -&gt; Unit ){ callback.invoke() } </code></pre> <p>when i will use the function:</p> <pre><code>someFunction( callBack = callBackFun() ) </code></pre> <p>So the question is, since i don't know, how many parameter callBackFun() will have(could be 0 or multiple) since someFunction could be use in multiple situation. how can i create the callback with 0 or more argument (vararg didn't work in this situation)</p>
[ { "answer_id": 74628208, "author": "Javlon", "author_id": 12153321, "author_profile": "https://Stackoverflow.com/users/12153321", "pm_score": 0, "selected": false, "text": "vararg List fun someFunction(\n callBack: (args: List<Any>) -> Unit\n){\n callback.invoke(listOf<Any>())\n}\n" }, { "answer_id": 74628222, "author": "MoCoding", "author_id": 11617754, "author_profile": "https://Stackoverflow.com/users/11617754", "pm_score": 2, "selected": false, "text": "callBackFun() {} someFunction(\n callBack = { callBackFun() }\n)\n\nsomeFunction(\n callBack = { secondCallBackFun(arg1, arg2) }\n)\n\nsomeFunction(\n callBack = { thirdCallBackFun(arg1, arg2, arg3) }\n)\n someFunction(\n callBack = { \n val arg1 = \"test\"\n val arg2 = \"test2\"\n val arg3 = 21\n\n callBackFun()\n secondCallBackFun(arg1, arg2)\n thirdCallBackFun(arg1, arg2, arg3)\n }\n)\n () -> Unit" }, { "answer_id": 74628263, "author": "Azim Salimov", "author_id": 12028884, "author_profile": "https://Stackoverflow.com/users/12028884", "pm_score": 0, "selected": false, "text": "fun myFunction(vararg func: () -> Unit) {\n //Something to do\n}\n myFunction(\n { TODO() }, \n { TODO() }, \n { TODO() }, \n)\n myFunction(\n func = arrayOf(\n { TODO() },\n { TODO() },\n { TODO() },\n )\n)\n newFun() myFunction(\n func = arrayOf(\n ::newFun,\n ::newFun2,\n ::newFun3,\n )\n)\n myFunction(\n ::newFun,\n ::newFun2,\n ::newFun3,\n)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19411871/" ]
74,628,044
<p>I have a dataframe that looks like this</p> <pre><code> plots &lt;- data.frame(plot=c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;C&quot;, &quot;C&quot;, &quot;C&quot;), value= c(1,1,1,2,2,3,3,3)) plot value 1 A 1 2 A 1 3 A 1 4 B 2 5 B 2 6 C 3 7 C 3 8 C 3 </code></pre> <p>I want to have a third column <code>sum</code> where I would sum all the values from the same plots, so it would look like this:</p> <pre><code> plot value sum 1 A 1 3 2 A 1 3 3 A 1 3 4 B 2 4 5 B 2 4 6 C 3 9 7 C 3 9 8 C 3 9 </code></pre>
[ { "answer_id": 74628071, "author": "user2974951", "author_id": 2974951, "author_profile": "https://Stackoverflow.com/users/2974951", "pm_score": 2, "selected": true, "text": "> ave(plots$value,plots$plot,FUN=sum)\n[1] 3 3 3 4 4 9 9 9\n" }, { "answer_id": 74628122, "author": "Jan Z", "author_id": 20477576, "author_profile": "https://Stackoverflow.com/users/20477576", "pm_score": 2, "selected": false, "text": "library(tidyverse)\nplots %>% as_tibble() %>% group_by(plot) %>% mutate(sum=sum(value))\n # A tibble: 8 × 3\n# Groups: plot [3]\n plot value sum\n <chr> <dbl> <dbl>\n1 A 1 3\n2 A 1 3\n3 A 1 3\n4 B 2 4\n5 B 2 4\n6 C 3 9\n7 C 3 9\n8 C 3 9\n" }, { "answer_id": 74628212, "author": "ALİ AA", "author_id": 17482212, "author_profile": "https://Stackoverflow.com/users/17482212", "pm_score": -1, "selected": false, "text": "plots%>%group_by(plot)%>%summarise(n=sum(value),plot,.groups=\"drop\")%>%as.data.frame()\n\n plot n\n1 A 3\n2 A 3\n3 A 3\n4 B 4\n5 B 4\n6 C 9\n7 C 9\n8 C 9\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165603/" ]
74,628,064
<p>I am trying to cut a slice a list of images to split them over a few pages of a pdf I am generating. But im not sure what the syntax I need to use is. (or if there is a better way).</p> <pre><code> {% for page in image_pages %} // range loop for number of pages (passed from view) &lt;p style=&quot;page-break-before: always&quot;&gt;&lt;/p&gt; // new page break for each page &lt;div class=&quot;img-wrapper&quot;&gt; {% for image in project_images|slice:&quot;0:12&quot; %} &lt;div class=&quot;img-box&quot; style=&quot;margin: 5px&quot;&gt; &lt;img class=&quot;report-img&quot; src=&quot;{{ base_url }}{{ image.path.url }}&quot; /&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endfor %} </code></pre> <p>What i want to do is adjust this line</p> <pre><code> {% for image in project_images|slice:&quot;0:12&quot; %} </code></pre> <p>To something like (to print 12 images from total image list sent)</p> <pre><code> {% for image in project_images|slice:&quot;page*12:page*12+12&quot; %} </code></pre>
[ { "answer_id": 74629128, "author": "nigel222", "author_id": 5246906, "author_profile": "https://Stackoverflow.com/users/5246906", "pm_score": 3, "selected": true, "text": "display = []\nfor page in image_pages:\n display.append([\n page, \n project_images[page*12:page*12+12]\n ])\ncontext['display'] = display\n {% for page, image_list in display %}\n <p style=\"page-break-before: always\"></p> // new page break for each page\n <div class=\"img-wrapper\">\n {% for image in image_list %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n</div>\n{% endfor %}\n" }, { "answer_id": 74629156, "author": "Spirconi", "author_id": 14143473, "author_profile": "https://Stackoverflow.com/users/14143473", "pm_score": 0, "selected": false, "text": " {% for page in image_pages %}\n <p style=\"page-break-before: always\"></p>\n {% with start=page|mul:12 end=page|mul:12|add:12 %}\n \n {% with start|addstr:\":\"|addstr:end as imageSlice %}\n \n <div class=\"img-wrapper\">\n {% for image in project_images|slice:imageSlice %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n </div>\n \n\n {% endwith %}\n \n {% endwith %} \n{% endfor %}\n\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14143473/" ]
74,628,074
<p>I got a school project where I need to sort numbers using linked list. I had some trouble initializing my linked list and someone gave me the folllowing solution, but I don't really understand what is happening on a line and I would like some enlightenment.</p> <p>Here's the full function :</p> <pre><code>void stack_ini(t_lst **list_ptr, char **nbr) { for (; *nbr; ++nbr) { // Create a new node. t_lst *node = malloc(sizeof(t_lst)); node-&gt;content = ft_atoi(*nbr); node-&gt;next = NULL; // Insert it into the list. *list_ptr = node; list_ptr = &amp;node-&gt;next; } } </code></pre> <p>To complete, here's the t_lst struct :</p> <pre><code>typedef struct s_lst { int content; int position; int index; struct s_lst *next; } t_lst; </code></pre> <p>I pretty much understand everything that's happening before the last line :</p> <p><code>list_ptr = &amp;node-&gt;next;</code></p> <p>I dont get why I need to assign list_ptr to the adress of node-&gt;next. Isnt node-&gt;next supposed to be uninitialized and thus provoke a segfault ? Also, if node and list_ptr are unassigned to their ...-&gt;next, shouldnt it just be like overwritting their current value ?</p> <p>Sorry for my english and thanks for your answers.</p>
[ { "answer_id": 74629128, "author": "nigel222", "author_id": 5246906, "author_profile": "https://Stackoverflow.com/users/5246906", "pm_score": 3, "selected": true, "text": "display = []\nfor page in image_pages:\n display.append([\n page, \n project_images[page*12:page*12+12]\n ])\ncontext['display'] = display\n {% for page, image_list in display %}\n <p style=\"page-break-before: always\"></p> // new page break for each page\n <div class=\"img-wrapper\">\n {% for image in image_list %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n</div>\n{% endfor %}\n" }, { "answer_id": 74629156, "author": "Spirconi", "author_id": 14143473, "author_profile": "https://Stackoverflow.com/users/14143473", "pm_score": 0, "selected": false, "text": " {% for page in image_pages %}\n <p style=\"page-break-before: always\"></p>\n {% with start=page|mul:12 end=page|mul:12|add:12 %}\n \n {% with start|addstr:\":\"|addstr:end as imageSlice %}\n \n <div class=\"img-wrapper\">\n {% for image in project_images|slice:imageSlice %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n </div>\n \n\n {% endwith %}\n \n {% endwith %} \n{% endfor %}\n\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19495079/" ]
74,628,098
<p>I am making a website project and I'm trying to make a function that will add new rows (<code>&lt;tr&gt;</code>) into an already existing empty table (<code>&lt;table&gt;</code>) and create cells (<code>&lt;td&gt;</code>) inside these rows containing informantion from a .json file. The first row contains certain dates and the first cell in every other row contains names of people.</p> <p>Everything works just fine except for one thing. I want to add cells that fill the rest of the table. I will put some info about the people's schedules in those cells. I wanted to do it in the same function so that everything is added together right away but for some reason this specific part doesn't work.</p> <p>Here's an example of the JavaScript code:</p> <pre><code>for(let x in namesArray){ let tr = document.createElement('tr') tr.className = &quot;plan&quot;; tr.innerHTML= &quot;&lt;th class='name'&gt;&quot;+namesArray[x]+&quot;&lt;/th&gt;&quot;; document.querySelector('tbody').appendChild(tr); }; for(let i = 0; i &lt; amountOfDates; i++) { document.querySelectorAll(&quot;.plan&quot;).forEach(function(y){ let td = document.createElement('td'); td.className = &quot;class_plan&quot;; y.appendChild(td); }); document.querySelectorAll(&quot;.class_plan&quot;).forEach(function(x){ let span = document.createElement('span'); span.className = &quot;description&quot;; x.appendChild(span); }); </code></pre> <p>When I run the code the table works fine. The names are displayed properly, but it seems that the rest of the code doesn't work.</p> <p>From my understanding, the code doesn't register any elements with the class &quot;.plan&quot; which is why the other cells are not displayed in the table. I'm not sure how to overcome this problem though.</p> <p>This is how the table should've looked like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Date 1</th> <th>Date 2</th> </tr> </thead> <tbody> <tr> <td>Name 1</td> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Name 2</td> <td>Cell 3</td> <td>Cell 4</td> </tr> </tbody> </table> </div> <p>But instead the cells don't show up at all.</p> <p>I've tried separating this code into two different functions, but it still doesn't work.</p>
[ { "answer_id": 74629128, "author": "nigel222", "author_id": 5246906, "author_profile": "https://Stackoverflow.com/users/5246906", "pm_score": 3, "selected": true, "text": "display = []\nfor page in image_pages:\n display.append([\n page, \n project_images[page*12:page*12+12]\n ])\ncontext['display'] = display\n {% for page, image_list in display %}\n <p style=\"page-break-before: always\"></p> // new page break for each page\n <div class=\"img-wrapper\">\n {% for image in image_list %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n</div>\n{% endfor %}\n" }, { "answer_id": 74629156, "author": "Spirconi", "author_id": 14143473, "author_profile": "https://Stackoverflow.com/users/14143473", "pm_score": 0, "selected": false, "text": " {% for page in image_pages %}\n <p style=\"page-break-before: always\"></p>\n {% with start=page|mul:12 end=page|mul:12|add:12 %}\n \n {% with start|addstr:\":\"|addstr:end as imageSlice %}\n \n <div class=\"img-wrapper\">\n {% for image in project_images|slice:imageSlice %}\n <div class=\"img-box\" style=\"margin: 5px\">\n <img\n class=\"report-img\"\n src=\"{{ base_url }}{{ image.path.url }}\"\n />\n </div>\n {% endfor %}\n </div>\n \n\n {% endwith %}\n \n {% endwith %} \n{% endfor %}\n\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645077/" ]
74,628,099
<p>How to group tuples with adjacent indices in a python 2-dimensional tuple?</p> <p>I'm not familiar with the zip function yet. I've written the code like this, but it doesn't work very well. Any help would be appreciated. Thank you!!</p> <pre class="lang-py prettyprint-override"><code>coords = ((1, 2), (3, 4), (5, 6), (7, 8)) coords = tuple(zip(coords[0::2], coords[1::2])) print(coords) </code></pre> <p>real output:</p> <pre><code>(((1, 2), (3, 4)), ((5, 6), (7, 8))) </code></pre> <p>expected output:</p> <pre><code>((1, 2, 3, 4), (5, 6, 7, 8)) </code></pre>
[ { "answer_id": 74628262, "author": "Mushfirat Mohaimin", "author_id": 15760624, "author_profile": "https://Stackoverflow.com/users/15760624", "pm_score": 2, "selected": false, "text": "coords = ((1, 2), (3, 4), (5, 6), (7, 8))\ncoords = tuple([(tuple([i for i in coords[x]])+tuple([i for i in coords[x+1]])) for x in range(0,len(coords)-1,2)])\nprint(coords)\n ((1, 2, 3, 4), (5, 6, 7, 8))\n" }, { "answer_id": 74628318, "author": "atru", "author_id": 2763915, "author_profile": "https://Stackoverflow.com/users/2763915", "pm_score": 4, "selected": true, "text": "coords = ((1, 2), (3, 4), (5, 6), (7, 8))\n\ncoords = tuple(x + y for x, y in zip(coords[0::2], coords[1::2]))\n coords zip x y" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19106705/" ]
74,628,100
<p>A <a href="https://www.nuget.org/packages/RimDev.Stuntman" rel="nofollow noreferrer">NuGet package</a> my program is using, is an older version of a <a href="https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer" rel="nofollow noreferrer">NuGet package</a> that has a <a href="https://github.com/advisories/GHSA-q7cg-43mg-qp69" rel="nofollow noreferrer">security vulnerability</a>. I want to update the NuGet package within the NuGet package to a new version but have not discovered a way to do that.</p> <p>There is no update to the NuGet package with the dependency with the vulnerability but there is an update for the dependency NuGet with the vulnerability.</p> <p>Screenshot of nuget package in visual studio 2022 <a href="https://i.stack.imgur.com/pFg8b.png" rel="nofollow noreferrer">nuget package in visual studio</a></p> <p>I have tried adding '-IgnoreDependencies' to the install command but that installed the NuGet with the insecure NuGet package.</p> <p><code>Install-Package RimDev.Stuntman -Version 3.0.0 -IgnoreDependencies</code></p>
[ { "answer_id": 74628262, "author": "Mushfirat Mohaimin", "author_id": 15760624, "author_profile": "https://Stackoverflow.com/users/15760624", "pm_score": 2, "selected": false, "text": "coords = ((1, 2), (3, 4), (5, 6), (7, 8))\ncoords = tuple([(tuple([i for i in coords[x]])+tuple([i for i in coords[x+1]])) for x in range(0,len(coords)-1,2)])\nprint(coords)\n ((1, 2, 3, 4), (5, 6, 7, 8))\n" }, { "answer_id": 74628318, "author": "atru", "author_id": 2763915, "author_profile": "https://Stackoverflow.com/users/2763915", "pm_score": 4, "selected": true, "text": "coords = ((1, 2), (3, 4), (5, 6), (7, 8))\n\ncoords = tuple(x + y for x, y in zip(coords[0::2], coords[1::2]))\n coords zip x y" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20644994/" ]
74,628,101
<p>I have strings similar to this example:</p> <pre><code>str = ' area AMW1 = 93.3 m2 '; </code></pre> <p>And I would like to only extract the floating point number (possibly with sign &quot;-&quot;) <code>93.3</code>. The float I like to extract is always surrouned by white spaces.</p> <p>How can I do that?</p> <p>I tried</p> <pre><code>s = regexp(str,'\d+\.?\d*','match') </code></pre> <p>However, it matches also the <code>1</code> and the <code>2</code>. Various other expressions I found do not work neither...</p> <p>Thank you.</p>
[ { "answer_id": 74628199, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "regexp(str,'-?\\d+\\.\\d+','match')\n + regexp(str,'[-+]?\\d+\\.\\d+','match')\n regexp(str,'(?<!\\S)[-+]?\\d+\\.\\d+(?!\\S)','match')\n regexp(str,'(?<=\\s)[-+]?\\d+\\.\\d+(?=\\s)','match')\n (?<=\\s) (?<!\\S) [-+]? + - \\d+ \\. \\d+ (?!\\S) (?=\\s) \\d+\\.\\d+ \\d+(?:\\.\\d+)?" }, { "answer_id": 74628215, "author": "Борис Алексеев", "author_id": 20513929, "author_profile": "https://Stackoverflow.com/users/20513929", "pm_score": 1, "selected": false, "text": "re.compile(r'(?<=\\s)\\d+(\\.\\d+)?(?=\\s)')\n" }, { "answer_id": 74632609, "author": "Nick J", "author_id": 4598449, "author_profile": "https://Stackoverflow.com/users/4598449", "pm_score": 0, "selected": false, "text": "regexp sscanf textscan regexp >> str = ' area AMW1 = 93.3 m2 '\nstr = area AMW1 = 93.3 m2\n >> sscanf(str, \" %s %s %s %f %s \")\nans =\n\n 97.000\n 114.000\n 101.000\n 97.000\n 65.000\n 77.000\n 87.000\n 49.000\n 61.000\n 93.300\n 109.000\n 50.000\n * > sscanf(str, \" %*s %*s %*s %f %*s \")\nans = 93.300\n >> str = ' area AMW1 = -93.3 m2 '\nstr = area AMW1 = -93.3 m2\n\n>> sscanf(str, \" %*s %*s %*s %f %*s \")\nans = -93.300\n >> textscan(str, \" %s %s %s %f %s \")\nans =\n{\n [1,1] =\n {\n [1,1] = area\n }\n\n [1,2] =\n {\n [1,1] = AMW1\n }\n\n [1,3] =\n {\n [1,1] = =\n }\n\n [1,4] = -93.300\n [1,5] =\n {\n [1,1] = m2\n }\n\n}\n\n>> textscan(str, \" %*s %*s %*s %f %*s \")\nans =\n{\n [1,1] = -93.300\n}\n\n>> cell2mat(textscan(s, \" %*s %*s %*s %f %*s \"))\nans = -93.300\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605073/" ]
74,628,106
<p>I have a project which is completely in C++. Also I have one more file which is in typescript ( I wasn't able to find libraries equilvelent in C++). The typescript file is doing the following: 1 It has typescript CLI code kinda of generator that will generate some functions in respective files.</p> <p>My compiler is gcc.</p> <p>Can please someone tell me .. is it possible to link and compile it ? Is yes..How ?</p>
[ { "answer_id": 74628199, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "regexp(str,'-?\\d+\\.\\d+','match')\n + regexp(str,'[-+]?\\d+\\.\\d+','match')\n regexp(str,'(?<!\\S)[-+]?\\d+\\.\\d+(?!\\S)','match')\n regexp(str,'(?<=\\s)[-+]?\\d+\\.\\d+(?=\\s)','match')\n (?<=\\s) (?<!\\S) [-+]? + - \\d+ \\. \\d+ (?!\\S) (?=\\s) \\d+\\.\\d+ \\d+(?:\\.\\d+)?" }, { "answer_id": 74628215, "author": "Борис Алексеев", "author_id": 20513929, "author_profile": "https://Stackoverflow.com/users/20513929", "pm_score": 1, "selected": false, "text": "re.compile(r'(?<=\\s)\\d+(\\.\\d+)?(?=\\s)')\n" }, { "answer_id": 74632609, "author": "Nick J", "author_id": 4598449, "author_profile": "https://Stackoverflow.com/users/4598449", "pm_score": 0, "selected": false, "text": "regexp sscanf textscan regexp >> str = ' area AMW1 = 93.3 m2 '\nstr = area AMW1 = 93.3 m2\n >> sscanf(str, \" %s %s %s %f %s \")\nans =\n\n 97.000\n 114.000\n 101.000\n 97.000\n 65.000\n 77.000\n 87.000\n 49.000\n 61.000\n 93.300\n 109.000\n 50.000\n * > sscanf(str, \" %*s %*s %*s %f %*s \")\nans = 93.300\n >> str = ' area AMW1 = -93.3 m2 '\nstr = area AMW1 = -93.3 m2\n\n>> sscanf(str, \" %*s %*s %*s %f %*s \")\nans = -93.300\n >> textscan(str, \" %s %s %s %f %s \")\nans =\n{\n [1,1] =\n {\n [1,1] = area\n }\n\n [1,2] =\n {\n [1,1] = AMW1\n }\n\n [1,3] =\n {\n [1,1] = =\n }\n\n [1,4] = -93.300\n [1,5] =\n {\n [1,1] = m2\n }\n\n}\n\n>> textscan(str, \" %*s %*s %*s %f %*s \")\nans =\n{\n [1,1] = -93.300\n}\n\n>> cell2mat(textscan(s, \" %*s %*s %*s %f %*s \"))\nans = -93.300\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483318/" ]
74,628,191
<p>I tried to do something very simple but I do not understand why it not working for me</p> <p>so i have a component that include the details about the user are logged in and i want to request the details user and put them in the component</p> <p>so I do a axios.get to my back-end i get the detail set them in the state with success put them in the component but when I refresh the page i get state is undefined</p> <p>I add here the code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import axios from "axios"; import React, { useEffect, useState } from "react"; import { useParams, useNavigate } from 'react-router-dom' import './account.css' function Account(props) { const [user, setUser] = useState() const [currentPass, setCurrentPass] = useState() const [newPass, setNewPass] = useState() const [confirmPass, setConfirmPass] = useState() let navigate = useNavigate(); useEffect(() =&gt; { let userArr = [] try { axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/users/getMe`) .then(res =&gt; { console.log(res.data.data.user) //object userArr.push(res.data.data.user) console.log(userArr) setUser(userArr) console.log(user) }) } catch (error) { console.log(error) } }, []) const updatePassword = async (e) =&gt; { e.preventDefault() try { const res = await axios.create({ withCredentials: true }).patch(`http://127.0.0.1:3000/users/updatePassword`, { currentPassword: currentPass, newPassword: newPass, passwordConfirm: confirmPass }); if (!res) { return "not work" } console.log(res.data.data.user) navigate("/", { replace: true }); } catch (error) { console.log(error); } } return ( &lt;div className="account-container" &gt; &lt;div className="title-container"&gt; &lt;p className="title"&gt;My Account&lt;/p&gt; &lt;/div&gt; &lt;p className="sub-title"&gt;User information &lt;/p&gt; &lt;form className="form-user-information"&gt; &lt;div className="div-form-user-information"&gt; &lt;label className="label-form-user-information"&gt;Username&lt;/label&gt; &lt;textarea placeholder="Username..." /&gt; &lt;/div&gt; &lt;div className="div-form-user-information"&gt; &lt;label className="label-form-user-information"&gt;ssss&lt;/label&gt; &lt;textarea placeholder={user.map(el =&gt; { return el.email })} /&gt; &lt;/div&gt; &lt;div className="div-form-user-information"&gt; &lt;label className="label-form-user-information"&gt;First name&lt;/label&gt; &lt;textarea placeholder="First name..." /&gt; &lt;/div&gt; &lt;div className="div-form-user-information"&gt; &lt;label className="label-form-user-information"&gt;Last name&lt;/label&gt; &lt;textarea placeholder="Last name..." /&gt; &lt;/div&gt; &lt;/form&gt; &lt;div className="buttom-line"&gt;&lt;/div&gt; {/* //////CONTACT INFORMATION////////// */} &lt;p className="sub-title-contact"&gt;CONTACT INFORMATION &lt;/p&gt; &lt;form className="form-contact-information"&gt; &lt;div className="div-form-contact-information"&gt; &lt;label className="label-form-contact-information"&gt;Full Address&lt;/label&gt; &lt;textarea placeholder="Full Address..." /&gt; &lt;/div&gt; &lt;div className="div-form-contact-information"&gt; &lt;label className="label-form-contact-information"&gt;City&lt;/label&gt; &lt;textarea placeholder="City..." /&gt; &lt;/div&gt; &lt;div className="div-form-contact-information"&gt; &lt;label className="label-form-contact-information"&gt;Country&lt;/label&gt; &lt;textarea placeholder="Country..." /&gt; &lt;/div&gt; &lt;div className="div-form-contact-information"&gt; &lt;label className="label-form-contact-information"&gt;Postal code&lt;/label&gt; &lt;textarea placeholder="Postal code..." /&gt; &lt;/div&gt; &lt;/form&gt; &lt;div className="buttom-line-contact"&gt;&lt;/div&gt; {/* //////PASSWORD INFORMATION////////// */} &lt;p className="sub-title-password"&gt;UPDATE PASSWORD &lt;/p&gt; &lt;form className="form-password-information"&gt; &lt;div className="div-form-password-information"&gt; &lt;label className="label-form-password-information"&gt;Current Password&lt;/label&gt; &lt;textarea onChange={(e) =&gt; setCurrentPass(e.target.value)} placeholder="Current Password..." /&gt; &lt;/div&gt; &lt;div className="div-form-password-information"&gt; &lt;label className="label-form-password-information"&gt;New Password&lt;/label&gt; &lt;textarea onChange={(e) =&gt; setNewPass(e.target.value)} placeholder="New Password..." /&gt; &lt;/div&gt; &lt;div className="div-form-password-information"&gt; &lt;label className="label-form-password-information"&gt;Confirm Password&lt;/label&gt; &lt;textarea onChange={(e) =&gt; setConfirmPass(e.target.value)} placeholder="Confirm Password..." /&gt; &lt;/div&gt; &lt;button onClick={(e) =&gt; updatePassword(e)} className="btn-update-pass"&gt;Update password&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } export default Account;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74628199, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "regexp(str,'-?\\d+\\.\\d+','match')\n + regexp(str,'[-+]?\\d+\\.\\d+','match')\n regexp(str,'(?<!\\S)[-+]?\\d+\\.\\d+(?!\\S)','match')\n regexp(str,'(?<=\\s)[-+]?\\d+\\.\\d+(?=\\s)','match')\n (?<=\\s) (?<!\\S) [-+]? + - \\d+ \\. \\d+ (?!\\S) (?=\\s) \\d+\\.\\d+ \\d+(?:\\.\\d+)?" }, { "answer_id": 74628215, "author": "Борис Алексеев", "author_id": 20513929, "author_profile": "https://Stackoverflow.com/users/20513929", "pm_score": 1, "selected": false, "text": "re.compile(r'(?<=\\s)\\d+(\\.\\d+)?(?=\\s)')\n" }, { "answer_id": 74632609, "author": "Nick J", "author_id": 4598449, "author_profile": "https://Stackoverflow.com/users/4598449", "pm_score": 0, "selected": false, "text": "regexp sscanf textscan regexp >> str = ' area AMW1 = 93.3 m2 '\nstr = area AMW1 = 93.3 m2\n >> sscanf(str, \" %s %s %s %f %s \")\nans =\n\n 97.000\n 114.000\n 101.000\n 97.000\n 65.000\n 77.000\n 87.000\n 49.000\n 61.000\n 93.300\n 109.000\n 50.000\n * > sscanf(str, \" %*s %*s %*s %f %*s \")\nans = 93.300\n >> str = ' area AMW1 = -93.3 m2 '\nstr = area AMW1 = -93.3 m2\n\n>> sscanf(str, \" %*s %*s %*s %f %*s \")\nans = -93.300\n >> textscan(str, \" %s %s %s %f %s \")\nans =\n{\n [1,1] =\n {\n [1,1] = area\n }\n\n [1,2] =\n {\n [1,1] = AMW1\n }\n\n [1,3] =\n {\n [1,1] = =\n }\n\n [1,4] = -93.300\n [1,5] =\n {\n [1,1] = m2\n }\n\n}\n\n>> textscan(str, \" %*s %*s %*s %f %*s \")\nans =\n{\n [1,1] = -93.300\n}\n\n>> cell2mat(textscan(s, \" %*s %*s %*s %f %*s \"))\nans = -93.300\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573874/" ]
74,628,197
<p>Flutter / Dart - I have a simple app but am new to programming, so struggling.</p> <p>Currently, the setup is with all the TextInput boxes in a Column. I would like to change this to having them in a Row. I assumed this would be easy by simply replacing the Word Column with Row on line 44. But it doesn't work and when I try to run it, the &quot;errors_patch.dart&quot; page opens (which I have never seen before) with a highlighted error on line 51 &quot;int assertionStart, int assertionEnd, Object? message);&quot;.</p> <p>How can I simply change from Column to Row?</p> <p>How can I have the result show in real time rather than needing to click on the &quot;Subtraction&quot; button to get it?</p> <p>Many thanks in advance.</p> <p><a href="https://i.stack.imgur.com/0Ve3r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Ve3r.jpg" alt="enter image description here" /></a></p> <pre><code>import 'package:flutter/material.dart'; void main() =&gt; runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Help with a meal....'; return MaterialApp( debugShowCheckedModeBanner: false, title: appTitle, home: Scaffold( appBar: AppBar( title: const Text(appTitle), backgroundColor: Colors.grey, foregroundColor: Colors.black, ), body: const AddTwoNumbers(), ), ); } } class AddTwoNumbers extends StatefulWidget { const AddTwoNumbers({super.key}); @override // ignore: library_private_types_in_public_api _AddTwoNumbersState createState() =&gt; _AddTwoNumbersState(); } class _AddTwoNumbersState extends State&lt;AddTwoNumbers&gt; { TextEditingController num1controller = TextEditingController(); TextEditingController num2controller = TextEditingController(); TextEditingController num3controller = TextEditingController(); TextEditingController num4controller = TextEditingController(); String result = &quot;0&quot;; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(10.0), child: Column( children: &lt;Widget&gt;[ TextField( keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num1controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Target Level', hintText: 'Enter First Number', ), ), const SizedBox( height: 8, ), TextField( keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num2controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Level', hintText: 'Enter Second Number', ), ), const SizedBox( height: 8, ), TextField( keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num3controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Meal carbs', hintText: 'Enter Third Number', ), ), const SizedBox( height: 8, ), TextField( keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num4controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Meal carbs 2', hintText: 'Enter Fourth Number', ), ), const SizedBox( height: 8, ), Wrap(children: [ ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.purple), child: const Text(&quot;Subtraction&quot;), onPressed: () { setState(() { double sum = double.parse(num1controller.text) - double.parse(num2controller.text); result = sum.toStringAsFixed(1); }); }, ), const SizedBox( height: 20, width: 20, ), ]), Text('Difference between Target Level and Current Level: $result'), ], ), ); } } </code></pre> <p><a href="https://i.stack.imgur.com/9OtQD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9OtQD.jpg" alt="enter image description here" /></a></p> <pre><code>import 'package:flutter/material.dart'; void main() =&gt; runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Help with a meal....'; return MaterialApp( debugShowCheckedModeBanner: false, title: appTitle, home: Scaffold( appBar: AppBar( title: const Text(appTitle), backgroundColor: Colors.grey, foregroundColor: Colors.black, ), body: const AddTwoNumbers(), ), ); } } class AddTwoNumbers extends StatefulWidget { const AddTwoNumbers({super.key}); @override // ignore: library_private_types_in_public_api _AddTwoNumbersState createState() =&gt; _AddTwoNumbersState(); } class _AddTwoNumbersState extends State&lt;AddTwoNumbers&gt; { TextEditingController num1controller = TextEditingController(); TextEditingController num2controller = TextEditingController(); TextEditingController num3controller = TextEditingController(); TextEditingController num4controller = TextEditingController(); String result = &quot;0&quot;; _calculate() { if (num1controller.text.isNotEmpty &amp;&amp; num2controller.text.isNotEmpty) { setState(() { double sum = double.parse(num1controller.text) - double.parse(num2controller.text); result = sum.toStringAsFixed(1); }); } } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Container( padding: const EdgeInsets.all(10.0), child: Column( children: [ Row( children: &lt;Widget&gt;[ Expanded( child: TextField( onChanged: (value) =&gt; _calculate(), keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num1controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Target Level', hintText: 'Enter First Number', ), ), ), const SizedBox( width: 8, ), Expanded( child: TextField( onChanged: (value) =&gt; _calculate(), keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num2controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Level', hintText: 'Enter Second Number', ), ), ), const SizedBox( width: 8, ), Expanded( child: TextField( onChanged: (value) =&gt; _calculate(), keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num3controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Meal carbs', hintText: 'Enter Third Number', ), ), ), const SizedBox( width: 8, ), Expanded( child: TextField( onChanged: (value) =&gt; _calculate(), keyboardType: const TextInputType.numberWithOptions(decimal: true), controller: num4controller, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Current Meal carbs 2', hintText: 'Enter Fourth Number', ), ), ), const SizedBox( width: 8, ), ], ), Text( 'Difference between Target Level and Current Level: $result'), ], ), ), ), ); } } </code></pre>
[ { "answer_id": 74628199, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 3, "selected": true, "text": "regexp(str,'-?\\d+\\.\\d+','match')\n + regexp(str,'[-+]?\\d+\\.\\d+','match')\n regexp(str,'(?<!\\S)[-+]?\\d+\\.\\d+(?!\\S)','match')\n regexp(str,'(?<=\\s)[-+]?\\d+\\.\\d+(?=\\s)','match')\n (?<=\\s) (?<!\\S) [-+]? + - \\d+ \\. \\d+ (?!\\S) (?=\\s) \\d+\\.\\d+ \\d+(?:\\.\\d+)?" }, { "answer_id": 74628215, "author": "Борис Алексеев", "author_id": 20513929, "author_profile": "https://Stackoverflow.com/users/20513929", "pm_score": 1, "selected": false, "text": "re.compile(r'(?<=\\s)\\d+(\\.\\d+)?(?=\\s)')\n" }, { "answer_id": 74632609, "author": "Nick J", "author_id": 4598449, "author_profile": "https://Stackoverflow.com/users/4598449", "pm_score": 0, "selected": false, "text": "regexp sscanf textscan regexp >> str = ' area AMW1 = 93.3 m2 '\nstr = area AMW1 = 93.3 m2\n >> sscanf(str, \" %s %s %s %f %s \")\nans =\n\n 97.000\n 114.000\n 101.000\n 97.000\n 65.000\n 77.000\n 87.000\n 49.000\n 61.000\n 93.300\n 109.000\n 50.000\n * > sscanf(str, \" %*s %*s %*s %f %*s \")\nans = 93.300\n >> str = ' area AMW1 = -93.3 m2 '\nstr = area AMW1 = -93.3 m2\n\n>> sscanf(str, \" %*s %*s %*s %f %*s \")\nans = -93.300\n >> textscan(str, \" %s %s %s %f %s \")\nans =\n{\n [1,1] =\n {\n [1,1] = area\n }\n\n [1,2] =\n {\n [1,1] = AMW1\n }\n\n [1,3] =\n {\n [1,1] = =\n }\n\n [1,4] = -93.300\n [1,5] =\n {\n [1,1] = m2\n }\n\n}\n\n>> textscan(str, \" %*s %*s %*s %f %*s \")\nans =\n{\n [1,1] = -93.300\n}\n\n>> cell2mat(textscan(s, \" %*s %*s %*s %f %*s \"))\nans = -93.300\n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15953708/" ]
74,628,228
<p>I have 3d sphere and links around as different mesh component. Can i rotate links mesh around my sphere without this sphere?</p> <p><a href="https://i.stack.imgur.com/T4Z51.jpg" rel="nofollow noreferrer">My 3d model</a></p> <p>I want to interact separately with links mesh and sphere mesh and rotate separately sphere and links.</p>
[ { "answer_id": 74630358, "author": "antokhio", "author_id": 2461748, "author_profile": "https://Stackoverflow.com/users/2461748", "pm_score": 1, "selected": true, "text": "<mesh onClick={handleClick}/>\n // mesh / object reference \nconst ref = useRef()\n// cursor movement XY delta\nconst delta = useRef(null)\n\nuseFrame(() => {\n if (delta !== null)\n ref.current.rotation.set([delta.x,delta.y, 0])\n})\n\nreturn ( <…\n <mesh ref={ref}/>\n…/>)\n delta.current = { x, y }" }, { "answer_id": 74631933, "author": "Sergey Samokhvalov", "author_id": 19014453, "author_profile": "https://Stackoverflow.com/users/19014453", "pm_score": 1, "selected": false, "text": "useFrame((state, delta) => (ref.current.children[0].rotation.y -= 0.1001 * Math.PI / 180));\nuseFrame((state, delta) => (ref.current.children[1].rotation.z += 0.1001 * Math.PI / 180));" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19014453/" ]
74,628,255
<p>I am trying to replace values in a list <strong>word</strong>, on indexes specified by the list <strong>positions</strong>, by sampling values that exist in a third list called <strong>letters</strong>.</p> <p>Here's an example of how my lists look like:</p> <pre><code>word &lt;- c(&quot;A&quot;,&quot;E&quot;,&quot;C&quot;,&quot;A&quot;,&quot;R&quot;,&quot;O&quot;,&quot;P&quot;) positions &lt;- c(1,5,3,7) letters &lt;- c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;) </code></pre> <p>One important detail is that the value in <strong>word[position]</strong> should not remain the same after sampling, which can happen because of overlapping values in <strong>letters</strong> and <strong>word</strong></p> <p>The current code that I am using to do this is:</p> <pre><code>for (i in 1:length(positions)){ temp &lt;- word[[positions[i]]] word[[positions[i]]] &lt;- sample(letters, 1) while (word[[positions[i]]] == temp) { word[[positions[i]]] &lt;- sample(letters, 1) } } </code></pre> <p>While this works, I realize that it's extremely inefficient, as the order in which I change the values in the list doesn't matter. I've been trying to use of of the &quot;apply&quot; family of functions to solve this, but I am having trouble figuring out a solution.</p> <p>Thank you very much for the attention!</p>
[ { "answer_id": 74630358, "author": "antokhio", "author_id": 2461748, "author_profile": "https://Stackoverflow.com/users/2461748", "pm_score": 1, "selected": true, "text": "<mesh onClick={handleClick}/>\n // mesh / object reference \nconst ref = useRef()\n// cursor movement XY delta\nconst delta = useRef(null)\n\nuseFrame(() => {\n if (delta !== null)\n ref.current.rotation.set([delta.x,delta.y, 0])\n})\n\nreturn ( <…\n <mesh ref={ref}/>\n…/>)\n delta.current = { x, y }" }, { "answer_id": 74631933, "author": "Sergey Samokhvalov", "author_id": 19014453, "author_profile": "https://Stackoverflow.com/users/19014453", "pm_score": 1, "selected": false, "text": "useFrame((state, delta) => (ref.current.children[0].rotation.y -= 0.1001 * Math.PI / 180));\nuseFrame((state, delta) => (ref.current.children[1].rotation.z += 0.1001 * Math.PI / 180));" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11634028/" ]
74,628,273
<p>I would like to extend the TypeScript <code>Map</code> type in my react TypeScript app to allow me to use <code>.map()</code>, in a similar way as you might with an <code>Array</code>.</p> <p>I found <a href="https://stackoverflow.com/questions/31084619/map-a-javascript-es6-map">this post</a> that describes several methods, but the most natural to me for TypeScript is the answer by <a href="https://stackoverflow.com/questions/31084619/map-a-javascript-es6-map/70877028#70877028">Jeremy Lachkar</a>, although it isn't very popular. It means I don't have to introduce any awkward syntax in the client code and can just extend the <code>Map</code> object.</p> <p>His code looks like this:</p> <pre><code>export {} declare global { interface Map&lt;K, V&gt; { map&lt;T&gt;(predicate: (key: K, value: V) =&gt; T): Map&lt;V, T&gt; } } Map.prototype.map = function&lt;K, V, T&gt;(predicate: (value: V, key: K) =&gt; T): Map&lt;K, T&gt; { let map: Map&lt;K, T&gt; = new Map() this.forEach((value: V, key: K) =&gt; { map.set(key, predicate(value, key)) }) return map } </code></pre> <p>I have augmented this to make it, for me, what seems more natural (I think the <code>Map&lt;V, T&gt;</code> in the interface might be a mistake in any case):</p> <pre><code>export {} declare global { interface Map&lt;K, V&gt; { map&lt;T&gt;(predicate: (key: K, value: V) =&gt; T): Map&lt;K, T&gt;; } } Map.prototype.map = function&lt;K, V, T&gt;(predicate: (key: K, value: V) =&gt; T): Map&lt;K, T&gt; { let map: Map&lt;K, T&gt; = new Map(); this.forEach((key: K, value: V) =&gt; { map.set(key, predicate(key, value)); }); return map; } </code></pre> <p>This works great. I can now map over my <code>Map</code> and produce a new one. However, now none of the other methods on <code>Map</code>, such as <code>.set()</code>, are available to me, and my code throws errors. These are now <code>undefined</code>.</p> <p>Any idea how to deal with this? I'm imagining in my little head that this might be a <code>tsconfig.json</code> issue of some sort, but I don't know.</p>
[ { "answer_id": 74630358, "author": "antokhio", "author_id": 2461748, "author_profile": "https://Stackoverflow.com/users/2461748", "pm_score": 1, "selected": true, "text": "<mesh onClick={handleClick}/>\n // mesh / object reference \nconst ref = useRef()\n// cursor movement XY delta\nconst delta = useRef(null)\n\nuseFrame(() => {\n if (delta !== null)\n ref.current.rotation.set([delta.x,delta.y, 0])\n})\n\nreturn ( <…\n <mesh ref={ref}/>\n…/>)\n delta.current = { x, y }" }, { "answer_id": 74631933, "author": "Sergey Samokhvalov", "author_id": 19014453, "author_profile": "https://Stackoverflow.com/users/19014453", "pm_score": 1, "selected": false, "text": "useFrame((state, delta) => (ref.current.children[0].rotation.y -= 0.1001 * Math.PI / 180));\nuseFrame((state, delta) => (ref.current.children[1].rotation.z += 0.1001 * Math.PI / 180));" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343159/" ]
74,628,289
<p>I am new to C# and I have encountered an error stating that: InvalidArgument=Value of '2' is not valid for 'index'.</p> <p>I want to set the items in checkedlistbox checked if there is a match in listbox. Can anyone help me with this problem.</p> <p>This the part of my code where the problems appear.</p> <pre><code>for (int i = 0; i &lt; checklistbox.Items.Count; i++) { if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString()) { //Check only if they match! checklistbox.SetItemChecked(i, true); } } </code></pre>
[ { "answer_id": 74630358, "author": "antokhio", "author_id": 2461748, "author_profile": "https://Stackoverflow.com/users/2461748", "pm_score": 1, "selected": true, "text": "<mesh onClick={handleClick}/>\n // mesh / object reference \nconst ref = useRef()\n// cursor movement XY delta\nconst delta = useRef(null)\n\nuseFrame(() => {\n if (delta !== null)\n ref.current.rotation.set([delta.x,delta.y, 0])\n})\n\nreturn ( <…\n <mesh ref={ref}/>\n…/>)\n delta.current = { x, y }" }, { "answer_id": 74631933, "author": "Sergey Samokhvalov", "author_id": 19014453, "author_profile": "https://Stackoverflow.com/users/19014453", "pm_score": 1, "selected": false, "text": "useFrame((state, delta) => (ref.current.children[0].rotation.y -= 0.1001 * Math.PI / 180));\nuseFrame((state, delta) => (ref.current.children[1].rotation.z += 0.1001 * Math.PI / 180));" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645634/" ]
74,628,302
<p>I have a <code>.net api</code> and I want to test the api from a console app. The method I am trying to test is a <code>POST</code> Method.I serialize data from my console app into a json string and I want to post it to the API, but the API does not get hit and I dont get any errors from my console app.</p> <p>My <code>GET</code> calls work though. It is just the post I cant get to work.</p> <p>My API Controller-&gt;</p> <pre><code>using _ErrorLogger.Shared; using _ErrorLogger.Server.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Runtime.CompilerServices; namespace _ErrorLogger.Server.Controllers { [Route(&quot;api/[controller]&quot;)] [ApiController] public class ExceptionDetailsController : ControllerBase { private readonly IExceptionDetailsService _exceptionDetailsService; public ExceptionDetailsController(IExceptionDetailsService exceptionDetailsService) { _exceptionDetailsService = exceptionDetailsService; } [HttpGet] [Route(&quot;GetExceptions&quot;)] public async Task&lt;List&lt;ExceptionDetails&gt;&gt; GetAll() { return await _exceptionDetailsService.GetAllExceptionDetails(); } [HttpGet] [Route(&quot;GetExceptionByID/{id}&quot;)] public async Task&lt;ExceptionDetails&gt; GetByID(int id) { return await _exceptionDetailsService.GetExceptionDetails(id); } [HttpPost] [Route(&quot;CreateException&quot;)] public async Task&lt;IActionResult&gt; CreateException([FromBody]string obj) { //await _exceptionDetailsService.AddExceptionDetails(exceptionDetails); return Ok(); } [HttpPost] [Route(&quot;Test&quot;)] public async Task&lt;IActionResult&gt; Test([FromBody] string obj) { return Ok(); } } } </code></pre> <p>My Call from the console app -&gt;</p> <pre><code>public async void ExceptionsAnalyzer(Exception exception) { HttpClient _httpClient = new HttpClient(); StackTrace stack = new StackTrace(exception, true); StackFrame frame = stack.GetFrame(stack.FrameCount - 1); ExceptionDetails exceptionDetails = new ExceptionDetails { ExceptionMessage = exception.Message, InnerException = exception.InnerException?.ToString(), ExceptionType = exception.GetType().ToString(), ExceptionSourceFile = frame.GetFileName(), ExceptionSourceLine = frame.GetFileLineNumber().ToString(), ExceptionCaller = frame.GetMethod().ToString(), ExceptionStackTrace = exception.StackTrace, DateLogged = DateTime.Now }; string json = JsonSerializer.Serialize(exceptionDetails); //var stringContent = new StringContent(json, Encoding.UTF8, &quot;application/json&quot;); HttpResponseMessage response = await _httpClient.PostAsJsonAsync(&quot;http://localhost:5296/api/ExceptionDetails/CreateException&quot;, json); if (response.IsSuccessStatusCode) { } } </code></pre> <p>I am Expecting the api endpoint to be hit.</p>
[ { "answer_id": 74628347, "author": "CthenB", "author_id": 1885199, "author_profile": "https://Stackoverflow.com/users/1885199", "pm_score": 0, "selected": false, "text": "ExceptionDetails route CreateException <base url>/CreateException" }, { "answer_id": 74629796, "author": "Md Farid Uddin Kiron", "author_id": 9663070, "author_profile": "https://Stackoverflow.com/users/9663070", "pm_score": 3, "selected": true, "text": "ExceptionsAnalyzer static main method static async Task ExceptionsAnalyzer wait() await using System.Net.Http.Json;\n using System.Text.Json;\n \n // Calling method \n ExceptionsAnalyzer().Wait();\n //Defining Method in dotnet 6 console app \n static async Task ExceptionsAnalyzer()\n {\n HttpClient _httpClient = new HttpClient();\n var obj = \"Test data\";\n string json = JsonSerializer.Serialize(obj);\n HttpResponseMessage response = await _httpClient.PostAsJsonAsync(\"http://localhost:5094/api/ExceptionDetails/CreateException\", json);\n if (response.IsSuccessStatusCode)\n {\n \n }\n }\n Exception exception" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20280508/" ]
74,628,304
<p>There is a function that takes two arguments. The first argument is the number of digits in the number. The second argument is the number itself. (5, 12345). Arguments will be passed in this format). It is necessary to take the first and last digit of this number and add them. Then return the product of these new numbers.</p> <p>Example solution -&gt;</p> <pre><code>arguments(5, 12345) (1+5)*(2+4)*3 = If the number of digits is odd arguments(6, 123456) (1+6)*(2+5)*(3+4) = If the number of digits is even </code></pre> <p>Here is the code that I wrote, for some reason it outputs NaN constantly, how to fix it and how to write conditions for the loop?</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>var a = prompt("Number: "); a = Array.from(a).map(i =&gt; Number(i)); if (a.length % 2 == 0) { result = (a[0] + a[a.length - 1]) * (a[1] + a[a.length - 2]) * (a[1] + a[a.length - 2]); alert(result); } else { result = (a[0] + a[a.length - 1]) * (a[1] + a[a.length - 2]) * a[3]; alert(result); }</code></pre> </div> </div> </p>
[ { "answer_id": 74628629, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 2, "selected": true, "text": "let a = prompt(\"Number: \");\na = Array.from(a).map((i) => Number(i));\n\nconst n = Math.floor(a.length / 2);\nlet answer = a.length % 2 === 1 ? a[n] : 1;\n\nlet i = 0;\nwhile (i < n) {\n answer *= a[i] + a[a.length - (i + 1)];\n i++\n}\n\nalert(answer)" }, { "answer_id": 74628649, "author": "vaira", "author_id": 6384776, "author_profile": "https://Stackoverflow.com/users/6384776", "pm_score": 0, "selected": false, "text": "let argument = (Numberlength, num) => {\n\n let arr = [...(num + '')].map(Number)\n\n let i = 0;\n let j = Numberlength - 1; // last element or arr.length -1\n let product = 1;\n while (i <= j) {\n let sum = arr[i] + arr[j]\n if (i === j) { // incase odd we only need to add one\n sum = arr[i];\n }\n product *= sum;\n i++;\n j--;\n }\n return product\n}\nconsole.log(argument(1, 12345)); // 1 \nconsole.log(argument(2, 12345)); // 1 + 2 \nconsole.log(argument(3, 12345)); // (1 + 3) * 2\nconsole.log(argument(4, 12345)); // (1 + 4) * (2 + 3)\nconsole.log(argument(5, 12345)); // (1 + 5) * (2 + 4) * 3 " }, { "answer_id": 74628680, "author": "Faezeh Keshmiri", "author_id": 14361493, "author_profile": "https://Stackoverflow.com/users/14361493", "pm_score": 0, "selected": false, "text": "var a = prompt(\"Number: \");\na = Array.from(a).map(i => Number(I));\nvar result = 1;\nvar k = 0;\nfor (j = a.length - 1; j >= a.length / 2 ; j--) {\n result *= a[j] + a[k];\n k++;\n}\nif (a.length % 2 == 0) {\n alert(result);\n} else {\n result *= a[k];\n alert(result);\n}\n" }, { "answer_id": 74628690, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "let str = \"\";\n\nfunction check(len, num) {\n let numArray = Array.from(String(num), Number),\n temp = 1,\n result = 1;\n\n while (numArray.length != 0) {\n let first = numArray.shift();\n let last = numArray.pop();\n let checkIsAvailable = numArray[0];\n\n str = str + `(${first}`;\n\n if (last) {\n str += `+${last})`;\n } else {\n str += \")\";\n }\n\n if (checkIsAvailable) {\n str += \"*\";\n }\n\n if (first == undefined) first = 0;\n if (last == undefined) last = 0;\n\n result = result * (first + last);\n }\n\n return result;\n}\n\nlet sum = check(5, 1234567);\n\nconsole.log(sum);\n\nconsole.log(str);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20632770/" ]
74,628,306
<p>So I have a command where for example</p> <pre><code>SELECT something, string_agg(other, ';') FROM table GROUP BY something HAVING COUNT(*)&gt;1; </code></pre> <p>but I don't know how to separate in two columns, because it doesn't see string_agg as a column.</p> <p>This is my original</p> <pre><code>something | other | --------+--------+ example | yes, no | using | why, what | </code></pre> <p>and I would like this please</p> <pre><code>something | other | new --------+--------+------ example | yes | no using | why | what </code></pre>
[ { "answer_id": 74628629, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 2, "selected": true, "text": "let a = prompt(\"Number: \");\na = Array.from(a).map((i) => Number(i));\n\nconst n = Math.floor(a.length / 2);\nlet answer = a.length % 2 === 1 ? a[n] : 1;\n\nlet i = 0;\nwhile (i < n) {\n answer *= a[i] + a[a.length - (i + 1)];\n i++\n}\n\nalert(answer)" }, { "answer_id": 74628649, "author": "vaira", "author_id": 6384776, "author_profile": "https://Stackoverflow.com/users/6384776", "pm_score": 0, "selected": false, "text": "let argument = (Numberlength, num) => {\n\n let arr = [...(num + '')].map(Number)\n\n let i = 0;\n let j = Numberlength - 1; // last element or arr.length -1\n let product = 1;\n while (i <= j) {\n let sum = arr[i] + arr[j]\n if (i === j) { // incase odd we only need to add one\n sum = arr[i];\n }\n product *= sum;\n i++;\n j--;\n }\n return product\n}\nconsole.log(argument(1, 12345)); // 1 \nconsole.log(argument(2, 12345)); // 1 + 2 \nconsole.log(argument(3, 12345)); // (1 + 3) * 2\nconsole.log(argument(4, 12345)); // (1 + 4) * (2 + 3)\nconsole.log(argument(5, 12345)); // (1 + 5) * (2 + 4) * 3 " }, { "answer_id": 74628680, "author": "Faezeh Keshmiri", "author_id": 14361493, "author_profile": "https://Stackoverflow.com/users/14361493", "pm_score": 0, "selected": false, "text": "var a = prompt(\"Number: \");\na = Array.from(a).map(i => Number(I));\nvar result = 1;\nvar k = 0;\nfor (j = a.length - 1; j >= a.length / 2 ; j--) {\n result *= a[j] + a[k];\n k++;\n}\nif (a.length % 2 == 0) {\n alert(result);\n} else {\n result *= a[k];\n alert(result);\n}\n" }, { "answer_id": 74628690, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "let str = \"\";\n\nfunction check(len, num) {\n let numArray = Array.from(String(num), Number),\n temp = 1,\n result = 1;\n\n while (numArray.length != 0) {\n let first = numArray.shift();\n let last = numArray.pop();\n let checkIsAvailable = numArray[0];\n\n str = str + `(${first}`;\n\n if (last) {\n str += `+${last})`;\n } else {\n str += \")\";\n }\n\n if (checkIsAvailable) {\n str += \"*\";\n }\n\n if (first == undefined) first = 0;\n if (last == undefined) last = 0;\n\n result = result * (first + last);\n }\n\n return result;\n}\n\nlet sum = check(5, 1234567);\n\nconsole.log(sum);\n\nconsole.log(str);" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20349656/" ]
74,628,308
<p>I've been trying to parse a string and to get rid of parts of the string using the remove() function. In order to find the part which I wanted to remove I used an OR operator. However, it does not produce the outcome I expected. Can you help me?</p> <p>My code looks like this:</p> <pre><code>import numpy as np x = '-1,0;1,0;0,-1;0,+1' x = x.split(';') for i in x: if ('+' in i) or ('-' in i): x.remove(i) else: continue x = ';'.join(x) print(x) </code></pre> <p>The outcome I expect is:</p> <p>[1,0]</p> <p>Instead the outcome is:</p> <p>[1,0;0,+1]</p>
[ { "answer_id": 74628412, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 3, "selected": true, "text": "x = '-1,0;1,0;0,-1;0,+1'\n\nx = x.split(';')\n\nnew = []\n\nfor i in x:\n if ('+' in i) or ('-' in i):\n pass\n else:\n new.append(i)\n \nx = ';'.join(new) \nprint(x)\n 1,0\n" }, { "answer_id": 74628666, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 1, "selected": false, "text": "x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\ncounter = 0\nfor i in x:\n counter +=1\n if '+' in i or '-' in i:\n x.remove(i)\n\nprint(x, counter)\n x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\nexpected_result = [el for el in x\n if \"-\" not in el and\n \"+\" not in el]\n expected_2 = []\nfor i in x:\n if '+' not in i and '-' not in i:\n expected_2.append(i)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645724/" ]
74,628,348
<p><strong>I`m using Visual Studio 2022.</strong></p> <h2>The goal</h2> <p>Run Console application (.NET Framework) - on Mono (without Unity or other tools).</p> <h3>Console Application code:</h3> <pre class="lang-cs prettyprint-override"><code>internal class Program { private static Task Main(string[] args) { if (Type.GetType(&quot;Mono.Runtime&quot;) != null) { Console.WriteLine(&quot;Mono!&quot;); // Should be outputted 'Mono!' in console } else { Console.WriteLine(&quot;Something other!&quot;); } return Task.CompletedTask; } } </code></pre> <h3>Console Application .csproj</h3> <pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt; &lt;PropertyGroup&gt; &lt;OutputType&gt;Exe&lt;/OutputType&gt; &lt;TargetFramework&gt;net472&lt;/TargetFramework&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=&quot;'$(Configuration)|$(Platform)'=='Debug|AnyCPU'&quot;&gt; &lt;DebugType&gt;none&lt;/DebugType&gt; &lt;DefineConstants&gt;$(DefineConstants)TRACE&lt;/DefineConstants&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition=&quot;'$(Configuration)|$(Platform)'=='Release|AnyCPU'&quot;&gt; &lt;DebugType&gt;none&lt;/DebugType&gt; &lt;DefineConstants&gt;$(DefineConstants)TRACE&lt;/DefineConstants&gt; &lt;/PropertyGroup&gt; &lt;/Project&gt; </code></pre> <h2>My attempts:</h2> <p><a href="https://marketplace.visualstudio.com/items?itemName=Dresel.MonoHelper" rel="nofollow noreferrer">MonoHelper</a> extension which is available only on super old versions of Visual Studio and probably deprecated because there`s no support.</p> <p><code>Mono msbuild</code> Getting error after executing this line in <code>cmd</code>: C:\Program Files\Mono&gt;msbuild &quot;path_to_project_here.csproj&quot; -p:Configuration=Release</p> <pre><code>&quot;path_to_project_here.csproj&quot; (default target) (1) -&gt; path_to_project_here.csproj : error MSB4237: The SDK resolver type &quot;Dot NetMSBuildSdkResolver&quot; failed to load. The type initializer for 'Microsoft.DotNet.DotNetSdkResolver.VSSettings' threw a n exception. </code></pre> <p><a href="https://www.mono-project.com/archived/xbuild/" rel="nofollow noreferrer">xbuild</a> which is deprecated also, instead used <code>Mono msbuild</code></p> <p>Probably I wont be use <code>MonoDevelop</code> for such things, there`s should be easy way.</p>
[ { "answer_id": 74628412, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 3, "selected": true, "text": "x = '-1,0;1,0;0,-1;0,+1'\n\nx = x.split(';')\n\nnew = []\n\nfor i in x:\n if ('+' in i) or ('-' in i):\n pass\n else:\n new.append(i)\n \nx = ';'.join(new) \nprint(x)\n 1,0\n" }, { "answer_id": 74628666, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 1, "selected": false, "text": "x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\ncounter = 0\nfor i in x:\n counter +=1\n if '+' in i or '-' in i:\n x.remove(i)\n\nprint(x, counter)\n x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\nexpected_result = [el for el in x\n if \"-\" not in el and\n \"+\" not in el]\n expected_2 = []\nfor i in x:\n if '+' not in i and '-' not in i:\n expected_2.append(i)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15495138/" ]
74,628,349
<p>We have in our project one k8s cluster.</p> <p>We are trying to set up several environments: DEV, TEST, PROD.</p> <p>The idea was to install several instances of Airflow in different k8s namespaces. I am doing the fresh installation of Airflow from official Helm chart. Then I am observing very weird behavior of Airflow Scheduler and Worker pods. It seems like they are in conflict. Pods are crashing and then restarting very often.</p> <p><a href="https://i.stack.imgur.com/SKpPU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SKpPU.jpg" alt="enter image description here" /></a></p> <p>If I am deleting one of the namespaces and leave only one Airflow in k8s, it works fine.</p> <p>Has anyone faced the similar issue?</p>
[ { "answer_id": 74628412, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 3, "selected": true, "text": "x = '-1,0;1,0;0,-1;0,+1'\n\nx = x.split(';')\n\nnew = []\n\nfor i in x:\n if ('+' in i) or ('-' in i):\n pass\n else:\n new.append(i)\n \nx = ';'.join(new) \nprint(x)\n 1,0\n" }, { "answer_id": 74628666, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 1, "selected": false, "text": "x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\ncounter = 0\nfor i in x:\n counter +=1\n if '+' in i or '-' in i:\n x.remove(i)\n\nprint(x, counter)\n x = '-1,0;1,0;0,-1;0,+1'.split(';')\n\nexpected_result = [el for el in x\n if \"-\" not in el and\n \"+\" not in el]\n expected_2 = []\nfor i in x:\n if '+' not in i and '-' not in i:\n expected_2.append(i)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19059171/" ]
74,628,362
<p>I have created a custom post type called &quot;Home Page&quot; using <code>register_post_type</code> and below is my code.</p> <pre><code>$labels = array( 'name' =&gt; __( 'Home Page'), 'singular_name' =&gt; __( 'Home Page'), 'edit_item' =&gt; __( 'Edit Home Page'), ); $args = array( 'label' =&gt; __( 'Home Page'), 'description' =&gt; __( 'Custom Post Type'), 'labels' =&gt; $labels, 'hierarchical' =&gt; false, 'public' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'has_archive' =&gt; false, 'exclude_from_search' =&gt; true, 'publicly_queryable' =&gt; true, 'map_meta_cap' =&gt; fa, 'capabilities' =&gt; array( 'create_posts' =&gt; 'do_not_allow', 'delete_published_posts' =&gt; false, 'read_post' =&gt; false, ), ); register_post_type( 'homepage', $args ); </code></pre> <p>And I have used &quot;Advanced Custom Fields&quot; WordPress plugin to add custom fields to this new custom post type. These all working fine and its showing like below.</p> <p><a href="https://i.stack.imgur.com/rGYuf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rGYuf.png" alt="enter image description here" /></a></p> <p>But the thing I want is, I will only have 1 record so if I click on &quot;Home Page&quot; on the left side bar admin menu link, it should be redirected to that particular record with something like <code>post.php?post=37&amp;action=edit</code> in the URL.</p> <p>I already know doing <code>'show_in_menu' =&gt; false,</code> will hide the url from the left sidebar.</p> <p>But how can I hide this menu and directly go to edit page for only single record which I will always have?</p> <p>Can someone guide me what should I do from here on to achieve this?</p> <p>Thanks in advance.</p>
[ { "answer_id": 74632489, "author": "Moishy", "author_id": 1810810, "author_profile": "https://Stackoverflow.com/users/1810810", "pm_score": 1, "selected": false, "text": "register_post_type 'map_meta_cap' => true,\n'capabilities' => array(\n 'create_posts' => 'do_not_allow'\n)\n function redirect_edit_screen() {\n \n $current_screen = get_current_screen();\n \n if( $current_screen->id === \"edit-homepage\" ) {\n wp_safe_redirect( admin_url('post.php?post=37&action=edit') );\n exit();\n }\n}\nadd_action( 'current_screen', 'redirect_edit_screen' );\n" }, { "answer_id": 74636928, "author": "Mittul At TechnoBrave", "author_id": 6829420, "author_profile": "https://Stackoverflow.com/users/6829420", "pm_score": 1, "selected": false, "text": "// Adding custom menu for custom post type \nfunction add_link_to_category_tips_n_tricks() {\n $link = 'post.php?post=39&action=edit';\n add_menu_page( 'Home Page', 'Home Page', 'edit_pages', $link, '', 'dashicons-admin-home', 8 );\n}\nadd_action( 'admin_menu', 'add_link_to_category_tips_n_tricks' );\n" }, { "answer_id": 74638365, "author": "Muhammad Zohaib", "author_id": 4457943, "author_profile": "https://Stackoverflow.com/users/4457943", "pm_score": 0, "selected": false, "text": "$_GET[post_type'] $pagenow edit.php function redirect_to_edit() {\n\n global $pagenow;\n\n if ( isset($_GET['post_type']) && $_GET['post_type'] == 'homepage' && $pagenow == 'edit.php' ) {\n wp_redirect( admin_url('post.php?post=39&action=edit') );\n exit();\n }\n\n}\nadd_action('admin_init', 'redirect_to_edit');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6829420/" ]
74,628,389
<p>I got a warning something like</p> <pre><code>warnings.warn( No local packages or working download links found for tensorflow-text~=2.11.0 error: Could not find suitable distribution for Requirement.parse('tensorflow-text~=2.11.0') </code></pre> <p>and if I run <code>pip install 'tensorflow-text~=2.11.0'</code> I got :</p> <pre><code>ERROR: Could not find a version that satisfies the requirement tensorflow-text~=2.11.0 (from versions: 2.8.1, 2.8.2, 2.9.0rc0, 2.9.0rc1, 2.9.0, 2.10.0b2, 2.10.0rc0, 2.10.0) ERROR: No matching distribution found for tensorflow-text~=2.11.0 </code></pre> <p><em>tensorflow-text 2.11.0 available on pypi</em></p> <p>and if I run <code>pip install tensorflow-text</code> it installs tensorflow-text 2.10.0 and downgrade the whole tensorflow to 2.10.0</p> <p>Version Info:</p> <ol> <li>OS: Windows 10</li> <li>Environment: Conda (miniconda3)</li> <li>Python: 3.10.8</li> <li>Tensorflow: 2.11</li> </ol> <p>I've tried pip and conda-forge</p>
[ { "answer_id": 74628512, "author": "slb20", "author_id": 9902510, "author_profile": "https://Stackoverflow.com/users/9902510", "pm_score": 0, "selected": false, "text": "pip install tensorflow-text==2.11.0\n" }, { "answer_id": 74628554, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 0, "selected": false, "text": "tensorflow-text 2.11.0 pip install tensorflow-text\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9885741/" ]
74,628,390
<p>I have a list of dates like this and want to make sure that all dates within that list are within the same month and year. How would I accomplish that?</p> <pre><code>// Should yield true IEnumerable&lt;DateTime&gt; dates1 = new List&lt;DateTime&gt;() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 11, 2) }; // Should yield false IEnumerable&lt;DateTime&gt; dates2 = new List&lt;DateTime&gt;() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 10, 2) }; </code></pre>
[ { "answer_id": 74628455, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 4, "selected": true, "text": "DateTime firstDate = dates1.First();\nbool allSameMonthAndYear = dates1\n .All(d => d.Year == firstDate.Year && d.Month == firstDate.Month);\n" }, { "answer_id": 74628622, "author": "Roman Ryzhiy", "author_id": 7592390, "author_profile": "https://Stackoverflow.com/users/7592390", "pm_score": 1, "selected": false, "text": "var listIsValid = dates1.Any() && dates1.All(e => dates1.First().Month == e.Month && dates1.First().Year == e.Year);\n" }, { "answer_id": 74628670, "author": "Fildor", "author_id": 982149, "author_profile": "https://Stackoverflow.com/users/982149", "pm_score": 1, "selected": false, "text": "public static bool Test( IEnumerable<DateTime> testee )\n{\n return testee.GroupBy(x => new { Year = x.Year, Month = x.Month} ).Count() <= 1;\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203853/" ]
74,628,418
<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>const apiUrl2 = `https://api.quran.com/api/v4/verses/random?language=en&amp;words=true&amp;translations=en&amp;audio=1&amp;tafsirs=en`; fetch(apiUrl2) .then((response) =&gt; response.json()) .then(data =&gt; { console.log(data); for (let i = 0; i &lt; data.verse.words.length; i++) { // var result = Object.values(data.words[i]); let datas = data.verse.words[i]; console.log(datas.translation.text); // console.log(datas.sort()); let sorted=datas.position; const propertyNames=Object.keys(sorted); console.log(sorted); // console.log(result.sort()); // document.getElementById('hadithNumber').innerHTML += ' ' + sorted.sort(); // if (datas.position &lt;= i) { // let ayah = []; // ayah.push(); // console.log(ayah[i]); // } } }) .catch(error =&gt; { console.log(error); });</code></pre> </div> </div> </p> <p>So Basically, I've this <a href="https://api.quran.com/api/v4/verses/random?language=en&amp;words=true&amp;translations=en&amp;audio=1&amp;tafsirs=en" rel="nofollow noreferrer">API to fetch Holy Quran Ayat/Verses</a> in this API we have a key called Position according to which the words has to be shown to make the Ayat complete. JSON</p> <pre><code>&quot;verse&quot;: { &quot;id&quot;: 5890, &quot;verse_number&quot;: 6, &quot;verse_key&quot;: &quot;84:6&quot;, &quot;hizb_number&quot;: 59, &quot;rub_el_hizb_number&quot;: 236, &quot;ruku_number&quot;: 528, &quot;manzil_number&quot;: 7, &quot;sajdah_number&quot;: null, &quot;page_number&quot;: 589, &quot;juz_number&quot;: 30, &quot;words&quot;: [ { &quot;id&quot;: 6721, &quot;position&quot;: 2, &quot;audio_url&quot;: &quot;wbw/084_006_002.mp3&quot;, &quot;char_type_name&quot;: &quot;word&quot;, &quot;code_v1&quot;: &quot;ﭲ&quot;, &quot;page_number&quot;: 589, &quot;line_number&quot;: 6, &quot;text&quot;: &quot;ﭲ&quot;, &quot;translation&quot;: { &quot;text&quot;: &quot;mankind&quot;, &quot;language_name&quot;: &quot;english&quot; }, &quot;transliteration&quot;: { &quot;text&quot;: &quot;l-insānu&quot;, &quot;language_name&quot;: &quot;english&quot; } }, { &quot;id&quot;: 6722, &quot;position&quot;: 3, &quot;audio_url&quot;: &quot;wbw/084_006_003.mp3&quot;, &quot;char_type_name&quot;: &quot;word&quot;, &quot;code_v1&quot;: &quot;ﭳ&quot;, &quot;page_number&quot;: 589, &quot;line_number&quot;: 6, &quot;text&quot;: &quot;ﭳ&quot;, &quot;translation&quot;: { &quot;text&quot;: &quot;Indeed, you&quot;, &quot;language_name&quot;: &quot;english&quot; }, &quot;transliteration&quot;: { &quot;text&quot;: &quot;innaka&quot;, &quot;language_name&quot;: &quot;english&quot; } }, { &quot;id&quot;: 6723, &quot;position&quot;: 4, &quot;audio_url&quot;: &quot;wbw/084_006_004.mp3&quot;, &quot;char_type_name&quot;: &quot;word&quot;, &quot;code_v1&quot;: &quot;ﭴ&quot;, &quot;page_number&quot;: 589, &quot;line_number&quot;: 6, &quot;text&quot;: &quot;ﭴ&quot;, &quot;translation&quot;: { &quot;text&quot;: &quot;(are) laboring&quot;, &quot;language_name&quot;: &quot;english&quot; }, &quot;transliteration&quot;: { &quot;text&quot;: &quot;kādiḥun&quot;, &quot;language_name&quot;: &quot;english&quot; } },....} </code></pre> <p>As you can see in the response in words array we have a key called position we need to use that key to sort it and add text based on its value This is what I've tried till now.</p>
[ { "answer_id": 74628640, "author": "wei", "author_id": 7766525, "author_profile": "https://Stackoverflow.com/users/7766525", "pm_score": 3, "selected": true, "text": "function compare(a, b) {\n return a.position - b.position;\n}\n\nconst apiUrl2 = `https://api.quran.com/api/v4/verses/random?language=en&words=true&translations=en&audio=1&tafsirs=en`;\nfetch(apiUrl2)\n .then((response) => response.json())\n .then(data => {\n\n console.log(data);\n data.verse.words.sort(compare);\n for (let i = 0; i < data.verse.words.length; i++) {\n // var result = Object.values(data.words[i]);\n let datas = data.verse.words[i];\n console.log(datas.translation.text);\n // console.log(datas.sort());\n let sorted = datas.position;\n const propertyNames = Object.keys(sorted);\n console.log(sorted);\n\n // console.log(result.sort());\n // document.getElementById('hadithNumber').innerHTML += ' ' + sorted.sort();\n // if (datas.position <= i) {\n // let ayah = [];\n // ayah.push();\n // console.log(ayah[i]);\n // }\n }\n })\n .catch(error => {\n console.log(error);\n });" }, { "answer_id": 74628663, "author": "Djlewald", "author_id": 7960407, "author_profile": "https://Stackoverflow.com/users/7960407", "pm_score": -1, "selected": false, "text": "//this snippet comes from the above page, credit goes to its author\nconst items = [\n { name: \"Edward\", value: 21 },\n { name: \"Sharpe\", value: 37 },\n { name: \"And\", value: 45 },\n { name: \"The\", value: -12 },\n { name: \"Magnetic\", value: 13 },\n { name: \"Zeros\", value: 37 },\n];\n\n// sort by value\nitems.sort((a, b) => a.value - b.value);\n\n// sort by name\nitems.sort((a, b) => {\n const nameA = a.name.toUpperCase(); // ignore upper and lowercase\n const nameB = b.name.toUpperCase(); // ignore upper and lowercase\n if (nameA < nameB) {\n return -1;\n }\n if (nameA > nameB) {\n return 1;\n }\n\n // names must be equal\n return 0;\n});\n" }, { "answer_id": 74628699, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": 1, "selected": false, "text": "words array.sort() const array = [\n {text: \"John\", position: 34},\n {text: \"Peter\", position: 54},\n {text: \"Jake\", position: 25},\n {text: \"Jolly\", position: 2},\n];\n\nlet sorted_array = array.sort(function(a, b) {\n return a.position - b.position; // sorts the \"words\" array based on the value of \"position\"\n});\n\nconsole.log(sorted_array) sorted_array" }, { "answer_id": 74628732, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 0, "selected": false, "text": "const list = data.verse.words;\nlist.sort((a,b) => a.position - b.position);\nconst orderedTextArray = list.map((wordModel) => wordModel.translation.text);\nconst result = orderedTextArray.join(' ');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11189318/" ]
74,628,430
<p>actually i am trying to create a popup which allow user to see expanded view inside the popup when user click on expand view for the particular element there are series of more then one element</p> <p>Requirment:-the issue is that there are multiple elements, and whenever you click on the element, it should open inside the popup. u can think of it like there is a grid of contacts whenever u click on any of the contact it should be viewed in a popup</p> <p>my current Approch :-</p> <p>when user click on the element, i am saving the element refrence to the variable and trying to pass the refrence as children props</p> <p>but getting error</p> <p>suggestion for diffrent approch are welcomed.</p> <p>thanks in advance</p> <pre><code>import React from &quot;react&quot;; const Summary = () =&gt; { const [expand, SetExpand] = useState&lt;boolean&gt;(false); const expendRef = useRef&lt;HTMLDivElement&gt;(null); return &lt;div &gt; {expand &amp;&amp; &lt;&gt;&lt;span&gt;hello&lt;/span&gt; { }&lt;Popup show={expand}&gt; {expendRef.current?.parentNode } &lt;/Popup&gt;&lt;/&gt;} &lt;div ref={expendRef} className='summary-table col-md-6' onClick={()=&gt;SetExpand(!expand)&gt; Reference element &lt;/div&gt; &lt;/div&gt; } const Popup=(props)=&gt;{ render(&lt;&gt; &lt;h1&gt;Popup Element&lt;/h1&gt; &lt;div&gt;{props.children}&lt;/props&gt; &lt;&gt;) } export default Summary </code></pre>
[ { "answer_id": 74628635, "author": "Amr Eraky", "author_id": 13346156, "author_profile": "https://Stackoverflow.com/users/13346156", "pm_score": 0, "selected": false, "text": "ref import React from \"react\";\n\nconst Summary = () => {\n\n const [expand, SetExpand] = useState<boolean>(false);\n\n const renderContent = () => (\n <div ref={expendRef} className='summary-table col-md-6' onClick={()=>SetExpand(!expand)>\n Reference element\n </div>\n )\n\n return (\n <div >\n {expand && <><span>hello</span>\n <Popup show={expand}>\n {renderContent()}\n </Popup></>}\n {renderContent()}\n </div> \n}\n\nexport default Summary;\n" }, { "answer_id": 74633512, "author": "Paulo Fernando", "author_id": 19223586, "author_profile": "https://Stackoverflow.com/users/19223586", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [element, setElement] = useState() as any;\n\n const showElementOnPopUp = (e: any) => {\n if (!popupVisible) setPopupVisible(true);\n const elementClone = e.currentTarget.cloneNode(true);\n elementClone.querySelector(\"div\").style.display = \"block\";\n setElement(elementClone);\n };\n\n return (\n <div>\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 1\n <div style={{ display: \"none\" }}>\n <p>Number: 111111</p>\n <p>Address: House 1</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 2\n <div style={{ display: \"none\" }}>\n <p>Number: 222222</p>\n <p>Address: House 2</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 3\n <div style={{ display: \"none\" }}>\n <p>Number: 333333</p>\n <p>Address: House 3</p>\n </div>\n </div>\n\n {popupVisible && (\n <Popup element={element} setPopupVisible={setPopupVisible}></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { element, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <DOMElementContainer element={element} />\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nconst DOMElementContainer = ({ element }: any) => {\n const ref = useRef() as any;\n\n useEffect(() => {\n if (!element) return;\n ref.current.innerHTML = \"\";\n ref.current.appendChild(element);\n }, [element]);\n\n return <div ref={ref}></div>;\n};\n\nexport default Summary;\n import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [contactList, setContactList] = useState() as any;\n const [contactInfo, setContactInfo] = useState() as any;\n\n const someApiCall = () => {\n return Promise.resolve([\n { name: \"Contact 1\", number: \"11111\", address: \"House 1\" },\n { name: \"Contact 2\", number: \"222222\", address: \"House 2\" },\n { name: \"Contact 3\", number: \"333333\", address: \"House 3\" },\n ]);\n };\n\n useEffect(() => {\n someApiCall().then((data) => {\n console.log(data);\n\n setContactList(data);\n });\n }, []);\n\n return (\n <div>\n {contactList?.map((contact: any) => {\n return (\n <div\n onClick={() => {\n setContactInfo(contact);\n setPopupVisible(true);\n }}\n >\n {contact.name}\n </div>\n );\n })}\n\n {popupVisible && (\n <Popup\n contactInfo={contactInfo}\n setPopupVisible={setPopupVisible}\n ></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { contactInfo, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <p>Name: {contactInfo.name}</p>\n <p>Number: {contactInfo.number}</p>\n <p>Address: {contactInfo.address}</p>\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nexport default Summary;\n" }, { "answer_id": 74633927, "author": "Federico Madoery", "author_id": 9104437, "author_profile": "https://Stackoverflow.com/users/9104437", "pm_score": 1, "selected": false, "text": "const Summary = () => {\n const [expand, setExpand] = useState(false)\n const expendRef = useRef(null)\n\n return (\n <div>\n {expand && (\n <>\n <span>hello</span>\n <Popup show={expand} element={expendRef} />\n </>\n )}\n <div \n ref={expendRef} \n className=\"summary-table col-md-6\" \n onClick={() => setExpand(!expand)}\n >\n {'Reference element'}\n </div>\n </div>\n )\n}\n \nconst Popup = (props) => {\n return (\n <>\n <h1>Popup Element</h1>\n <div dangerouslySetInnerHTML={{ __html: props.element.current.outerHTML }} style={{ background: 'red' }} />\n {/* Background red is just to do it obvious, when its render */}\n </>\n )\n}\n\n .current.outerHTML" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12205765/" ]
74,628,431
<p>I am sending props <code>month_id</code> to child component from parent component by clicking on a <code>&lt;li&gt;</code>. My child component code is like below.</p> <pre><code>&lt;script&gt; export default { props: ['mosque_id', 'month_id'], data(){ return { prayer_times: [], } }, watch: { month_id() { this.getPrayerTime(); } }, methods:{ getPrayerTime: function () { axios.get('/api/v1/getPrayerTime/'+ this.mosque_id+'/'+ this.month_id) .then(function (response) { this.prayer_times = response.data; }.bind(this)); } }, } &lt;/script&gt; </code></pre> <p>But I am getting result little late. I have to click twice on <code>&lt;li&gt;</code> to get result. Am I using <code>watch</code> properly ?</p>
[ { "answer_id": 74628635, "author": "Amr Eraky", "author_id": 13346156, "author_profile": "https://Stackoverflow.com/users/13346156", "pm_score": 0, "selected": false, "text": "ref import React from \"react\";\n\nconst Summary = () => {\n\n const [expand, SetExpand] = useState<boolean>(false);\n\n const renderContent = () => (\n <div ref={expendRef} className='summary-table col-md-6' onClick={()=>SetExpand(!expand)>\n Reference element\n </div>\n )\n\n return (\n <div >\n {expand && <><span>hello</span>\n <Popup show={expand}>\n {renderContent()}\n </Popup></>}\n {renderContent()}\n </div> \n}\n\nexport default Summary;\n" }, { "answer_id": 74633512, "author": "Paulo Fernando", "author_id": 19223586, "author_profile": "https://Stackoverflow.com/users/19223586", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [element, setElement] = useState() as any;\n\n const showElementOnPopUp = (e: any) => {\n if (!popupVisible) setPopupVisible(true);\n const elementClone = e.currentTarget.cloneNode(true);\n elementClone.querySelector(\"div\").style.display = \"block\";\n setElement(elementClone);\n };\n\n return (\n <div>\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 1\n <div style={{ display: \"none\" }}>\n <p>Number: 111111</p>\n <p>Address: House 1</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 2\n <div style={{ display: \"none\" }}>\n <p>Number: 222222</p>\n <p>Address: House 2</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 3\n <div style={{ display: \"none\" }}>\n <p>Number: 333333</p>\n <p>Address: House 3</p>\n </div>\n </div>\n\n {popupVisible && (\n <Popup element={element} setPopupVisible={setPopupVisible}></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { element, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <DOMElementContainer element={element} />\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nconst DOMElementContainer = ({ element }: any) => {\n const ref = useRef() as any;\n\n useEffect(() => {\n if (!element) return;\n ref.current.innerHTML = \"\";\n ref.current.appendChild(element);\n }, [element]);\n\n return <div ref={ref}></div>;\n};\n\nexport default Summary;\n import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [contactList, setContactList] = useState() as any;\n const [contactInfo, setContactInfo] = useState() as any;\n\n const someApiCall = () => {\n return Promise.resolve([\n { name: \"Contact 1\", number: \"11111\", address: \"House 1\" },\n { name: \"Contact 2\", number: \"222222\", address: \"House 2\" },\n { name: \"Contact 3\", number: \"333333\", address: \"House 3\" },\n ]);\n };\n\n useEffect(() => {\n someApiCall().then((data) => {\n console.log(data);\n\n setContactList(data);\n });\n }, []);\n\n return (\n <div>\n {contactList?.map((contact: any) => {\n return (\n <div\n onClick={() => {\n setContactInfo(contact);\n setPopupVisible(true);\n }}\n >\n {contact.name}\n </div>\n );\n })}\n\n {popupVisible && (\n <Popup\n contactInfo={contactInfo}\n setPopupVisible={setPopupVisible}\n ></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { contactInfo, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <p>Name: {contactInfo.name}</p>\n <p>Number: {contactInfo.number}</p>\n <p>Address: {contactInfo.address}</p>\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nexport default Summary;\n" }, { "answer_id": 74633927, "author": "Federico Madoery", "author_id": 9104437, "author_profile": "https://Stackoverflow.com/users/9104437", "pm_score": 1, "selected": false, "text": "const Summary = () => {\n const [expand, setExpand] = useState(false)\n const expendRef = useRef(null)\n\n return (\n <div>\n {expand && (\n <>\n <span>hello</span>\n <Popup show={expand} element={expendRef} />\n </>\n )}\n <div \n ref={expendRef} \n className=\"summary-table col-md-6\" \n onClick={() => setExpand(!expand)}\n >\n {'Reference element'}\n </div>\n </div>\n )\n}\n \nconst Popup = (props) => {\n return (\n <>\n <h1>Popup Element</h1>\n <div dangerouslySetInnerHTML={{ __html: props.element.current.outerHTML }} style={{ background: 'red' }} />\n {/* Background red is just to do it obvious, when its render */}\n </>\n )\n}\n\n .current.outerHTML" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5043301/" ]
74,628,459
<p>I have coordinates on an excel sheet that are expressed as follows:</p> <pre><code>Latitude Longitude 16,5037993382 -25,0139206899 </code></pre> <ul> <li>whole part are degrees,</li> <li>first two decimals are minutes,</li> <li>decimals 3 and 4 are seconds, the rest fraction of seconds.</li> </ul> <p>Example:</p> <pre><code>16,5037993382 shall be read 16º50'3799''N -25,0139206899 shall be read 025º01'3920''W </code></pre> <p>After I import the .csv to Google earth I have this: <img src="https://i.stack.imgur.com/c064k.jpg" alt="see image" /></p> <p>The point should be located near the red cross.</p> <p>I need to somehow be able to import this data to google earth, or a tool to convert it if possible.</p>
[ { "answer_id": 74628635, "author": "Amr Eraky", "author_id": 13346156, "author_profile": "https://Stackoverflow.com/users/13346156", "pm_score": 0, "selected": false, "text": "ref import React from \"react\";\n\nconst Summary = () => {\n\n const [expand, SetExpand] = useState<boolean>(false);\n\n const renderContent = () => (\n <div ref={expendRef} className='summary-table col-md-6' onClick={()=>SetExpand(!expand)>\n Reference element\n </div>\n )\n\n return (\n <div >\n {expand && <><span>hello</span>\n <Popup show={expand}>\n {renderContent()}\n </Popup></>}\n {renderContent()}\n </div> \n}\n\nexport default Summary;\n" }, { "answer_id": 74633512, "author": "Paulo Fernando", "author_id": 19223586, "author_profile": "https://Stackoverflow.com/users/19223586", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [element, setElement] = useState() as any;\n\n const showElementOnPopUp = (e: any) => {\n if (!popupVisible) setPopupVisible(true);\n const elementClone = e.currentTarget.cloneNode(true);\n elementClone.querySelector(\"div\").style.display = \"block\";\n setElement(elementClone);\n };\n\n return (\n <div>\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 1\n <div style={{ display: \"none\" }}>\n <p>Number: 111111</p>\n <p>Address: House 1</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 2\n <div style={{ display: \"none\" }}>\n <p>Number: 222222</p>\n <p>Address: House 2</p>\n </div>\n </div>\n\n <div className=\"summary-table col-md-6\" onClick={showElementOnPopUp}>\n Contact 3\n <div style={{ display: \"none\" }}>\n <p>Number: 333333</p>\n <p>Address: House 3</p>\n </div>\n </div>\n\n {popupVisible && (\n <Popup element={element} setPopupVisible={setPopupVisible}></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { element, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <DOMElementContainer element={element} />\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nconst DOMElementContainer = ({ element }: any) => {\n const ref = useRef() as any;\n\n useEffect(() => {\n if (!element) return;\n ref.current.innerHTML = \"\";\n ref.current.appendChild(element);\n }, [element]);\n\n return <div ref={ref}></div>;\n};\n\nexport default Summary;\n import React, { useEffect, useRef, useState } from \"react\";\n\nconst Summary = () => {\n const [popupVisible, setPopupVisible] = useState<boolean>(false);\n const [contactList, setContactList] = useState() as any;\n const [contactInfo, setContactInfo] = useState() as any;\n\n const someApiCall = () => {\n return Promise.resolve([\n { name: \"Contact 1\", number: \"11111\", address: \"House 1\" },\n { name: \"Contact 2\", number: \"222222\", address: \"House 2\" },\n { name: \"Contact 3\", number: \"333333\", address: \"House 3\" },\n ]);\n };\n\n useEffect(() => {\n someApiCall().then((data) => {\n console.log(data);\n\n setContactList(data);\n });\n }, []);\n\n return (\n <div>\n {contactList?.map((contact: any) => {\n return (\n <div\n onClick={() => {\n setContactInfo(contact);\n setPopupVisible(true);\n }}\n >\n {contact.name}\n </div>\n );\n })}\n\n {popupVisible && (\n <Popup\n contactInfo={contactInfo}\n setPopupVisible={setPopupVisible}\n ></Popup>\n )}\n </div>\n );\n};\n\nconst Popup = (props: any) => {\n const { contactInfo, setPopupVisible } = props;\n\n return (\n <>\n <h1>Popup Element</h1>\n <div>\n <p>Name: {contactInfo.name}</p>\n <p>Number: {contactInfo.number}</p>\n <p>Address: {contactInfo.address}</p>\n </div>\n <button\n onClick={() => {\n setPopupVisible(false);\n }}\n >\n Close Popup\n </button>\n </>\n );\n};\n\nexport default Summary;\n" }, { "answer_id": 74633927, "author": "Federico Madoery", "author_id": 9104437, "author_profile": "https://Stackoverflow.com/users/9104437", "pm_score": 1, "selected": false, "text": "const Summary = () => {\n const [expand, setExpand] = useState(false)\n const expendRef = useRef(null)\n\n return (\n <div>\n {expand && (\n <>\n <span>hello</span>\n <Popup show={expand} element={expendRef} />\n </>\n )}\n <div \n ref={expendRef} \n className=\"summary-table col-md-6\" \n onClick={() => setExpand(!expand)}\n >\n {'Reference element'}\n </div>\n </div>\n )\n}\n \nconst Popup = (props) => {\n return (\n <>\n <h1>Popup Element</h1>\n <div dangerouslySetInnerHTML={{ __html: props.element.current.outerHTML }} style={{ background: 'red' }} />\n {/* Background red is just to do it obvious, when its render */}\n </>\n )\n}\n\n .current.outerHTML" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645893/" ]
74,628,477
<p>I need to verify if a chrome extension is installed or not installed on remote computers. Extension id is unique value like that &quot;234aljksdfklja3idffklsasf&quot;. I need to search &quot;HKEY_CURRENT_USER\SOFTWARE\Google\Chrome\PreferenceMACs\Default\extensions.settings&quot; direction for extension id &quot;234aljksdfklja3idffklsasf&quot;</p> <p>How to do that? i think i will use code below but i need some help WMIC /NameSpace:\root\default Class StdRegProv ....</p>
[ { "answer_id": 74636904, "author": "Ben Personick", "author_id": 3985011, "author_profile": "https://Stackoverflow.com/users/3985011", "pm_score": 2, "selected": true, "text": "WMIC REG HKCU HKLM Reg SID (reg query \"HKCU\\SOFTWARE\\Google\\Chrome\\PreferenceMACs\\Default\\extensions.settings\" /s | FIND /I \"234aljksdfklja3idffklsasf\") && Echo.FOUND 234aljksdfklja3idffklsasf (reg query \\\\[Computer_Name_or_IP_Address]\\hklm\\SOFTWARE\\Google\\Chrome\\PreferenceMACs\\Default\\extensions.settings /s | FIND /I \"234aljksdfklja3idffklsasf\") && Echo.FOUND 234aljksdfklja3idffklsasf FOR %A IN (\n Computer_A\n 192.168.12.13\n 192.168.12.31\n Computer_C\n) DO (\n (\n reg query \\\\%~A\\hklm\\SOFTWARE\\Google\\Chrome\\PreferenceMACs\\Default\\extensions.settings /s | FIND /I \"234aljksdfklja3idffklsasf\"\n ) && Echo.%~A -- FOUND 234aljksdfklja3idffklsasf || ECHO.%~A -- Key Not Found!\n)\n reg query <KeyName> [{/v <ValueName> | /ve}] [/s] [/se <Separator>] [/f <Data>] [{/k | /d}] [/c] [/e] [/t <Type>] [/z]\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2853569/" ]
74,628,479
<p>How to send macros as parameters through a task?</p> <p>In the testbench:</p> <pre><code>`define CPU1 tb.top.dual_processor_db_wrapper_i.dual_processor_db_i.cpu1.inst `define CPU2 tb.top.dual_processor2_db_wrapper_i.dual_processor2_db_i.cpu2.inst initial begin fork cpu_init(`CPU1); cpu_init(`CPU2); join // Other stuff with `CPU1 and `CPU2 `CPU1.write_data(addr, 4, data, resp); // Works end task cpu_init(cpu); cpu.por_srstb_reset(1'b1); // Does not work // Other init stuff endtask </code></pre> <p>Error when compiling:</p> <blockquote> <p>ERROR: [VRFC 10-2991] 'por_srstb_reset' is not declared under prefix 'cpu'</p> </blockquote> <p>The type of the `CPUs is unknown (to me). Perhaps Xilinx has a type for it, since it references their MPSoC VIP?</p> <p>I assume <code>por_srstb_reset</code> and <code>write_data</code> are tasks or functions from Xilinx MPSoC VIP, but I'm not sure.</p> <p><a href="https://china.xilinx.com/content/dam/xilinx/support/documents/ip_documentation/zynq_ultra_ps_e_vip/v1_0/ds941-zynq-ultra-ps-e-vip.pdf" rel="nofollow noreferrer">Xilinx documentation is very sparse</a></p>
[ { "answer_id": 74628892, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 2, "selected": true, "text": "task task task task cpu_init (input logic cpu);\n cpu `define CPU1 1'b1\ncpu_init(`CPU1);\n" }, { "answer_id": 74633921, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 0, "selected": false, "text": "bind package pkg;\n interface class abstract_init;\n pure virtual task init; // prototype for each method you need\n endclass\n abstract_init lookup[string]; // database of concrete classes for each instance\nendpackage\n\nmodule bind_module #(string lookup_name);\n import pkg::*;\n class concrete_init implements abstract_init;\n function new;\n lookup[lookup_name] = this; // register this instance \n endfunction\n virtual task init;\n processor.reset(); // upwards reference\n endtask\n endclass\n concrete_init c = new; // each instance of this module gets registered in lookup\nendmodule\n \n\n\n`define cpu1 top.dut.cpu1\n`define cpu2 top.dut.cpu2\n// macro turns any argument into a quoted string\n`define Q(arg) `\"arg`\"\n \nmodule top;\n dut dut();\n bind `cpu1 bind_module #(.lookup_name(`Q(`cpu1))) b();\n bind `cpu2 bind_module #(.lookup_name(`Q(`cpu2))) b();\n initial fork\n pkg::lookup[`Q(`cpu1)].init;\n pkg::lookup[`Q(`cpu2)].init;\n join\n\nendmodule\n\nmodule dut;\n processor cpu1();\n processor cpu2();\nendmodule\n\nmodule processor;\n initial $display(\"Starting %m\");\n task reset;\n #1 $display(\"executing reset on %m\");\n endtask\nendmodule\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2971409/" ]
74,628,486
<p>I've created 2 entities in Spring with JPA annotations:</p> <p>Project:</p> <pre><code>package com.example.technologyradar.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Data @AllArgsConstructor @NoArgsConstructor public class Project { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = &quot;native&quot;) @GenericGenerator(name=&quot;native&quot;, strategy = &quot;native&quot;) private Long id; private String name; @ManyToMany(mappedBy = &quot;projects&quot;) private Set&lt;Technology&gt; assignedTechnologies = new HashSet&lt;Technology&gt;(); } </code></pre> <p>Technology:</p> <pre><code>package com.example.technologyradar.model; import com.example.technologyradar.dto.constant.TechnologyStatus; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Data @AllArgsConstructor @NoArgsConstructor public class Technology { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = &quot;native&quot;) @GenericGenerator(name=&quot;native&quot;, strategy = &quot;native&quot;) private Long id; private String name; @Enumerated(EnumType.STRING) private TechnologyStatus technologyStatus; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST, targetEntity = Category.class) @JoinColumn(name=&quot;category_id&quot;, referencedColumnName = &quot;id&quot;, nullable = false) private Category category; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST, targetEntity = Coordinate.class) @JoinColumn(name=&quot;coordinate_id&quot;, referencedColumnName = &quot;id&quot;, nullable = false) private Coordinate coordinate; @ManyToMany @JoinTable( name = &quot;projects_technologies&quot;, joinColumns = @JoinColumn(name=&quot;technology_id&quot;), inverseJoinColumns = @JoinColumn(name=&quot;project_id&quot;) ) private Set&lt;Project&gt; projects = new HashSet&lt;Project&gt;(); } </code></pre> <p>My goal is to get List of projects with technologies usage list with ignoring Coordinate and Category from Technology Entity. When I perform simply <code>findAll()</code>:</p> <pre><code>public List&lt;Project&gt; getProjectsWithTechnologyUsage() { return (List&lt;Project&gt;) projectRepository.findAll(); } </code></pre> <p>then I'm obtaining famous Infinite Recursion error:</p> <pre><code>Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]-&gt;com.example.technologyradar.model.Project[&quot;assignedTechnologies&quot;])] </code></pre> <p>I know that one of the solutions is to add <code>@JsonManagedReference</code> and <code>@JsonBackRerefence</code> annotations but I don't know how to do it correctly for my particular case. I would be grateful for any suggestions. Thanks!</p>
[ { "answer_id": 74628892, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 2, "selected": true, "text": "task task task task cpu_init (input logic cpu);\n cpu `define CPU1 1'b1\ncpu_init(`CPU1);\n" }, { "answer_id": 74633921, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 0, "selected": false, "text": "bind package pkg;\n interface class abstract_init;\n pure virtual task init; // prototype for each method you need\n endclass\n abstract_init lookup[string]; // database of concrete classes for each instance\nendpackage\n\nmodule bind_module #(string lookup_name);\n import pkg::*;\n class concrete_init implements abstract_init;\n function new;\n lookup[lookup_name] = this; // register this instance \n endfunction\n virtual task init;\n processor.reset(); // upwards reference\n endtask\n endclass\n concrete_init c = new; // each instance of this module gets registered in lookup\nendmodule\n \n\n\n`define cpu1 top.dut.cpu1\n`define cpu2 top.dut.cpu2\n// macro turns any argument into a quoted string\n`define Q(arg) `\"arg`\"\n \nmodule top;\n dut dut();\n bind `cpu1 bind_module #(.lookup_name(`Q(`cpu1))) b();\n bind `cpu2 bind_module #(.lookup_name(`Q(`cpu2))) b();\n initial fork\n pkg::lookup[`Q(`cpu1)].init;\n pkg::lookup[`Q(`cpu2)].init;\n join\n\nendmodule\n\nmodule dut;\n processor cpu1();\n processor cpu2();\nendmodule\n\nmodule processor;\n initial $display(\"Starting %m\");\n task reset;\n #1 $display(\"executing reset on %m\");\n endtask\nendmodule\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5244324/" ]
74,628,518
<p>I want to make a wordpress plugin, which displays my copyright at the top of the html code. so if anyone goes on my website and has a look on my website, i can display something like &quot;made with love by my name&quot;</p> <p>the text should be only visible in the code and not be shown in the front-end.</p> <p>i know it would be easier to just write the sentence in the html code, but i am trying to make a Wordpress plugin...</p> <p>and Tips how i could do it? i am a very beginner with php and wordpress.</p> <p>i created the basis of my plugin with this &quot;plugin-Template&quot;</p> <p><a href="https://github.com/hlashbrooke/WordPress-Plugin-Template" rel="nofollow noreferrer">https://github.com/hlashbrooke/WordPress-Plugin-Template</a></p> <p>would be nice if someone could tell me in which .php? file i have to put which code.</p> <p>i already tried displaying it with echo, but it didnt work...</p>
[ { "answer_id": 74628892, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 2, "selected": true, "text": "task task task task cpu_init (input logic cpu);\n cpu `define CPU1 1'b1\ncpu_init(`CPU1);\n" }, { "answer_id": 74633921, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 0, "selected": false, "text": "bind package pkg;\n interface class abstract_init;\n pure virtual task init; // prototype for each method you need\n endclass\n abstract_init lookup[string]; // database of concrete classes for each instance\nendpackage\n\nmodule bind_module #(string lookup_name);\n import pkg::*;\n class concrete_init implements abstract_init;\n function new;\n lookup[lookup_name] = this; // register this instance \n endfunction\n virtual task init;\n processor.reset(); // upwards reference\n endtask\n endclass\n concrete_init c = new; // each instance of this module gets registered in lookup\nendmodule\n \n\n\n`define cpu1 top.dut.cpu1\n`define cpu2 top.dut.cpu2\n// macro turns any argument into a quoted string\n`define Q(arg) `\"arg`\"\n \nmodule top;\n dut dut();\n bind `cpu1 bind_module #(.lookup_name(`Q(`cpu1))) b();\n bind `cpu2 bind_module #(.lookup_name(`Q(`cpu2))) b();\n initial fork\n pkg::lookup[`Q(`cpu1)].init;\n pkg::lookup[`Q(`cpu2)].init;\n join\n\nendmodule\n\nmodule dut;\n processor cpu1();\n processor cpu2();\nendmodule\n\nmodule processor;\n initial $display(\"Starting %m\");\n task reset;\n #1 $display(\"executing reset on %m\");\n endtask\nendmodule\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645919/" ]
74,628,524
<p>Ok so I am very new to python and I am supposed to make a code that gives me this output</p> <blockquote> <p><code>input= -5 </code> <code>output = (-5)+(-4)+(-3)+(-2)+(-1)=-15</code> but I just can't wrap my head around it</p> </blockquote> <p>I thought I could just somehow flip this</p> <pre><code>while True: output = &quot;&quot; num = int(input(&quot;enter a integer: &quot;)) if num == 0: exit() for i in range(1, num + 1): output += &quot;{}&quot;.format(i) if i != num: output += &quot;+&quot; output += &quot; = {}&quot;.format(sum(range(num + 1))) print(output) </code></pre> <p>but I could not figure it out. please help. If someone can show me how to get both of these in one code that would be helpfull.</p>
[ { "answer_id": 74628892, "author": "toolic", "author_id": 197758, "author_profile": "https://Stackoverflow.com/users/197758", "pm_score": 2, "selected": true, "text": "task task task task cpu_init (input logic cpu);\n cpu `define CPU1 1'b1\ncpu_init(`CPU1);\n" }, { "answer_id": 74633921, "author": "dave_59", "author_id": 2755607, "author_profile": "https://Stackoverflow.com/users/2755607", "pm_score": 0, "selected": false, "text": "bind package pkg;\n interface class abstract_init;\n pure virtual task init; // prototype for each method you need\n endclass\n abstract_init lookup[string]; // database of concrete classes for each instance\nendpackage\n\nmodule bind_module #(string lookup_name);\n import pkg::*;\n class concrete_init implements abstract_init;\n function new;\n lookup[lookup_name] = this; // register this instance \n endfunction\n virtual task init;\n processor.reset(); // upwards reference\n endtask\n endclass\n concrete_init c = new; // each instance of this module gets registered in lookup\nendmodule\n \n\n\n`define cpu1 top.dut.cpu1\n`define cpu2 top.dut.cpu2\n// macro turns any argument into a quoted string\n`define Q(arg) `\"arg`\"\n \nmodule top;\n dut dut();\n bind `cpu1 bind_module #(.lookup_name(`Q(`cpu1))) b();\n bind `cpu2 bind_module #(.lookup_name(`Q(`cpu2))) b();\n initial fork\n pkg::lookup[`Q(`cpu1)].init;\n pkg::lookup[`Q(`cpu2)].init;\n join\n\nendmodule\n\nmodule dut;\n processor cpu1();\n processor cpu2();\nendmodule\n\nmodule processor;\n initial $display(\"Starting %m\");\n task reset;\n #1 $display(\"executing reset on %m\");\n endtask\nendmodule\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645865/" ]
74,628,532
<p><strong>Story:</strong></p> <ol> <li>We have a lot of <code>microservices</code> and communication happens mostly through <code>Service Bus</code> by sending <code>serialized DTOs</code>.</li> <li>Some microservices <code>share the DB</code>, so entity <code>models</code>, for now, are <code>duplicated</code> in each microservice.</li> </ol> <p><strong>Problems:</strong></p> <ol> <li>Whenever we want to <code>modify DTO</code> which is used for communication between microservice we need to <code>modify it in each microservice</code>.</li> <li>Any <code>change in the shared DB</code> requires making <code>changes in all related microservices</code> and single DB field edit causes <code>multiple PRs</code>.</li> </ol> <p><strong>Possible solutions:</strong></p> <p>Move any shared code to other repositories (DTOs repo, Entity Models repo, etc.), and create solutions with <code>Class Library projects</code>.</p> <p>I have two approaches after this point:</p> <ul> <li>Create <code>NuGets</code> and add them to microservices.</li> <li>Add <code>bare Class Library projects</code> as a reference for all microservices and we'll get <code>Multi-repo solutions</code> with microservices.</li> </ul> <p><strong>Pros/Cons:</strong></p> <p>For <code>NuGets</code> I see mostly cons:</p> <ul> <li>It will require some <code>extra infrastructure</code> built around it to create artifacts.</li> <li><code>To test any change</code> it will be needed to modify Nuget Solution, trigger some CI pipeline and <code>wait to build the NuGet</code> itself, update the microservice with a test version of <code>NuGet</code>, and only after that we can test the microservice itself.</li> <li>If <code>any errors</code> occur - <code>repeat an entire process</code>.</li> </ul> <p>For <code>bare Class Library projects</code> I see mostly advantages:</p> <ul> <li><code>VS 2022</code> brought some nice <code>support for Multi-repo</code> solutions.</li> <li>It will be possible to make <code>changes in shared projects</code> and <code>immediately test</code> them with actual microservices.</li> </ul> <p><strong>Questions:</strong></p> <ul> <li>Could you add any pros/cons for my <code>possible solutions</code>?</li> <li>Could you recommend any other solutions for problems (with pros/cons)?</li> </ul>
[ { "answer_id": 74657813, "author": "Trionia", "author_id": 1517575, "author_profile": "https://Stackoverflow.com/users/1517575", "pm_score": 2, "selected": false, "text": "http-cache dotnet nuget locals --list http-cache NUGET_HTTP_CACHE_PATH" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10548234/" ]
74,628,539
<pre><code>class C(val string: String) { init { println(string) } } abstract class A { abstract var string: String val c = C(string) } class B : A() { override var string = &quot;string&quot; } fun main() { B() } </code></pre> <p><a href="https://pl.kotl.in/QhNaUgxyu" rel="nofollow noreferrer">kotlin playground for the problem</a></p> <p>This code crash in runtime due to string var not initialized, how to do it right?</p>
[ { "answer_id": 74628860, "author": "MoCoding", "author_id": 11617754, "author_profile": "https://Stackoverflow.com/users/11617754", "pm_score": 3, "selected": true, "text": "Accessing non-final property string in constructor A B val c = C(string) string NullPointerException string null lazy val c by lazy { C(string) }\n c B" }, { "answer_id": 74629061, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 1, "selected": false, "text": "A c abstract string abstract var string: String\nval c = C(string)\n B string A A c string c val c by lazy { C(string) }\n c string c val c get() = C(string)\n C c string" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/891814/" ]
74,628,570
<p>It says <a href="https://rpkgs.datanovia.com/rstatix/reference/anova_test.html" rel="nofollow noreferrer">here</a> that one can get one or the other or both. I have been able to get each one separately but not both together even when I set <code>effect.size = c(&quot;ges&quot;, &quot;pes&quot;)</code>. Instead, I only get &quot;pes&quot;. I have the same problem when I use my own data and when I use the <code>hangover</code> dataset from the <code>{WRS2}</code> package. For the hangover data, my code is:</p> <pre><code>anova_test(data = hangover, dv = symptoms, wid = id, between = group, within = time, effect.size = c(&quot;ges&quot;, &quot;pes&quot;)) </code></pre> <p>I would be very grateful for your help!</p>
[ { "answer_id": 74629187, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "add_anova_effect_size <- function(res.anova.summary, effect.size = \"ges\", observed = NULL){\n ss.exists <- \"SSn\" %in% colnames(res.anova.summary$ANOVA)\n if(!ss.exists){\n return(res.anova.summary)\n }\n if(\"pes\" %in% effect.size){\n res.anova.summary <- res.anova.summary %>%\n add_partial_eta_squared()\n }\n else {\n res.anova.summary <- res.anova.summary %>%\n add_generalized_eta_squared(observed)\n }\n res.anova.summary\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17508788/" ]
74,628,578
<p>Currently im trying to transform this python dict to a html unordered list:</p> <blockquote> <p>{'dataStreamId': 'raw:com.google.nutrition:NutritionSource', 'dataStreamName': 'NutritionSource', 'type': 'raw', 'dataType': {'name': 'com.google.nutrition', 'field': [{'name': 'nutrients', 'format': 'map'}, {'name': 'meal_type', 'format': 'integer', 'optional': True}, {'name': 'food_item', 'format': 'string', 'optional': True}]}, 'application': {'version': '1', 'detailsUrl': 'http://example.com', 'name': 'My Example App'}, 'dataQualityStandard': []}</p> </blockquote> <p>with this function:</p> <pre><code>def dict_to_html_ul(dd, level=4): import simplejson text = '&lt;ul&gt;' for k, v in dd.items(): text += '&lt;li&gt;&lt;b&gt;%s&lt;/b&gt;: %s&lt;/li&gt;' % (k, dict_to_html_ul(v, level+1) if isinstance(v, (dict)) else (simplejson.dumps(v) if isinstance(v, list) else v)) text += '&lt;/ul&gt;' return text </code></pre> <p>but I am getting this result:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;b&gt;dataStreamId&lt;/b&gt;: raw:com.google.nutrition:NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataStreamName&lt;/b&gt;: NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;type&lt;/b&gt;: raw&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataType&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: com.google.nutrition&lt;/li&gt; &lt;li&gt;&lt;b&gt;field&lt;/b&gt;: [{&quot;name&quot;: &quot;nutrients&quot;, &quot;format&quot;: &quot;map&quot;}, {&quot;name&quot;: &quot;meal_type&quot;, &quot;format&quot;: &quot;integer&quot;, &quot;optional&quot;: true}, {&quot;name&quot;: &quot;food_item&quot;, &quot;format&quot;: &quot;string&quot;, &quot;optional&quot;: true}]&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;b&gt;application&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;version&lt;/b&gt;: 1&lt;/li&gt; &lt;li&gt;&lt;b&gt;detailsUrl&lt;/b&gt;: http://example.com&lt;/li&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: My Example App&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;b&gt;dataQualityStandard&lt;/b&gt;: []&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And I am having issues trying to fix the result, basically I wanted to transform the rest of the result in the same way as the function was going.</p> <p>I tried to transform the text with some string replacing after the function:</p> <pre><code>text = text.replace('[','').replace(']', '') text= text.replace('{', '&lt;br&gt;' + '&amp;nbsp;' * level).replace('}', '') text = text.replace(',', '&lt;br&gt;' + '&amp;nbsp;' * (level-1)) </code></pre> <p>It came out with some extraspacing and I could not replace some parts like this:</p> <blockquote> <p>&quot;word&quot;: &quot;word&quot;</p> </blockquote> <p>So I tried to make a &quot;re.sub()&quot; but did not have success.</p> <p>Edit:</p> <p>Expected output:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;b&gt;dataStreamId&lt;/b&gt;: raw:com.google.nutrition:NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataStreamName&lt;/b&gt;: NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;type&lt;/b&gt;: raw&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataType&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: com.google.nutrition&lt;/li&gt; &lt;li&gt;&lt;b&gt;field&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: nutrients&lt;/li&gt; &lt;li&gt;&lt;b&gt;format&lt;/b&gt;: map&lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: meal_type&lt;/li&gt; &lt;li&gt;&lt;b&gt;format&lt;/b&gt;: integer&lt;/li&gt; &lt;li&gt;&lt;b&gt;optional&lt;/b&gt;: true&lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: food_item&lt;/li&gt; &lt;li&gt;&lt;b&gt;format&lt;/b&gt;: string&lt;/li&gt; &lt;li&gt;&lt;b&gt;optional&lt;/b&gt;: true&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;b&gt;application&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;version&lt;/b&gt;: 1&lt;/li&gt; &lt;li&gt;&lt;b&gt;detailsUrl&lt;/b&gt;: http://example.com&lt;/li&gt; &lt;li&gt;&lt;b&gt;name&lt;/b&gt;: My Example App&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;b&gt;dataQualityStandard&lt;/b&gt;: []&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Edit2: Thanks for the answer @AndrejKesely</p> <p>I actually got the proper html in the first specific dict, but I have another dict that didnt actually work with this function: –</p> <pre><code>a = {'minStartTimeNs': '1573159699023000000', 'maxEndTimeNs': '1573159699023999000', 'dataSourceId': 'raw:com.google.nutrition:NutritionSource', 'point': [{'startTimeNanos': '1573159699023000000', 'endTimeNanos': '1573159699023999000', 'dataTypeName': 'com.google.nutrition', 'value': [{'mapVal': [{'key': 'fat.total', 'value': {'fpVal': 0.4}}, {'key': 'sodium', 'value': {'fpVal': 1}}, {'key': 'fat.saturated', 'value': { 'fpVal': 0.1}}, {'key': 'protein', 'value': {'fpVal': 1.3}}, {'key': 'carbs.total', 'value': {'fpVal': 27}}, {'key': 'cholesterol', 'value': {'fpVal': 0}}, {'key': 'calories', 'value': {'fpVal': 105}}, {'key': 'sugar', 'value': {'fpVal': 14}}, {'key': 'dietary_fiber', 'value': {'fpVal': 3.1}}, {'key': 'potassium', 'value': {'fpVal': 422}}]}, {'intVal': 4, 'mapVal': []}, {'stringVal': 'apple', 'mapVal': []}]}]} </code></pre> <p>I was expecting a function that could work for both</p> <p>but the output with get_html() in the other dict outputs:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;b&gt;minStartTimeNs&lt;/b&gt;: 1573159699023000000&lt;/li&gt; &lt;li&gt;&lt;b&gt;maxEndTimeNs&lt;/b&gt;: 1573159699023999000&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataSourceId&lt;/b&gt;: raw:com.google.nutrition:NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;point&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;startTimeNanos&lt;/b&gt;: 1573159699023000000&lt;/li&gt; &lt;li&gt;&lt;b&gt;endTimeNanos&lt;/b&gt;: 1573159699023999000&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataTypeName&lt;/b&gt;: com.google.nutrition&lt;/li&gt; &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: [{'mapVal': [{'key': 'fat.total', 'value': {'fpVal': 0.4}}, {'key': 'sodium', 'value': {'fpVal': 1}}, {'key': 'fat.saturated', 'value': {'fpVal': 0.1}}, {'key': 'protein', 'value': {'fpVal': 1.3}}, {'key': 'carbs.total', 'value': {'fpVal': 27}}, {'key': 'cholesterol', 'value': {'fpVal': 0}}, {'key': 'calories', 'value': {'fpVal': 105}}, {'key': 'sugar', 'value': {'fpVal': 14}}, {'key': 'dietary_fiber', 'value': {'fpVal': 3.1}}, {'key': 'potassium', 'value': {'fpVal': 422}}]}, {'intVal': 4, 'mapVal': []}, {'stringVal': 'apple', 'mapVal': []}]&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And I was expecting:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;b&gt;minStartTimeNs&lt;/b&gt;: 1573159699023000000&lt;/li&gt; &lt;li&gt;&lt;b&gt;maxEndTimeNs&lt;/b&gt;: 1573159699023999000&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataSourceId&lt;/b&gt;: raw:com.google.nutrition:NutritionSource&lt;/li&gt; &lt;li&gt;&lt;b&gt;point&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;startTimeNanos&lt;/b&gt;: 1573159699023000000&lt;/li&gt; &lt;li&gt;&lt;b&gt;endTimeNanos&lt;/b&gt;: 1573159699023999000&lt;/li&gt; &lt;li&gt;&lt;b&gt;dataTypeName&lt;/b&gt;: com.google.nutrition&lt;/li&gt; &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;mapVal&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;: fat.total&lt;/li&gt; &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 0.4&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;: sodium&lt;/li&gt; &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'fat.saturated', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 0.4&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'protein', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 5.4&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'carbs.total', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 6.4&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'cholesterol', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 4.5&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'calories', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 3.4&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'sugar', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 5.5&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt;'dietary_fiber', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;key&lt;/b&gt;:&lt;/li&gt; 'potassium', &lt;li&gt;&lt;b&gt;value&lt;/b&gt;: &lt;ul&gt; &lt;li&gt;&lt;b&gt;fpVal&lt;/b&gt;: 2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;br&gt; &lt;/ul&gt; &lt;li&gt;&lt;b&gt;intVal&lt;/b&gt;: 4&lt;/li&gt; &lt;li&gt;&lt;b&gt;mapVal&lt;/b&gt;: []&lt;/li&gt; &lt;br&gt; &lt;li&gt;&lt;b&gt;stringVal&lt;/b&gt;: apple&lt;/li&gt; &lt;li&gt;&lt;b&gt;mapVal&lt;/b&gt;: []&lt;/li&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 74629187, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "add_anova_effect_size <- function(res.anova.summary, effect.size = \"ges\", observed = NULL){\n ss.exists <- \"SSn\" %in% colnames(res.anova.summary$ANOVA)\n if(!ss.exists){\n return(res.anova.summary)\n }\n if(\"pes\" %in% effect.size){\n res.anova.summary <- res.anova.summary %>%\n add_partial_eta_squared()\n }\n else {\n res.anova.summary <- res.anova.summary %>%\n add_generalized_eta_squared(observed)\n }\n res.anova.summary\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645767/" ]
74,628,603
<p>I have users table with <code>termination_date</code> column that is either <code>NULL</code> if the users are active or it has a <code>datetime</code> if the users are not active anymore.</p> <p>There is also a <code>termination_reason</code> column that describes why the user is not active anymore.</p> <p>So for active users, it's <code>NULL</code> and if they are not active, then it has a value:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>country</th> <th>city</th> <th>termination_date</th> <th>termination_reason</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sweden</td> <td>Stockholm</td> <td>2022-10-04</td> <td>self</td> </tr> <tr> <td>2</td> <td>Sweden</td> <td>Stockholm</td> <td>2020-03-20</td> <td>admin</td> </tr> <tr> <td>2</td> <td>Sweden</td> <td>Stockholm</td> <td>NULL</td> <td>NULL</td> </tr> <tr> <td>3</td> <td>Switzerland</td> <td>Bern</td> <td>NULL</td> <td>NULL</td> </tr> <tr> <td>4</td> <td>Switzerland</td> <td>Bern</td> <td>2021-12-08</td> <td>admin</td> </tr> <tr> <td>5</td> <td>Switzerland</td> <td>Bern</td> <td>NULL</td> <td>NULL</td> </tr> </tbody> </table> </div> <p>I want to display information about active and non-active users grouped by country, city and termination reason (and show active users grouped by country and city only because they don't have <code>termination_reason</code>). But list the non-active users only from the past 12 months (and active of all time), so the above table would result in:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>country</th> <th>city</th> <th>active</th> <th>not_active</th> <th>termination_reason</th> </tr> </thead> <tbody> <tr> <td>Sweden</td> <td>Stockholm</td> <td>1</td> <td>1</td> <td>self</td> </tr> <tr> <td>Sweden</td> <td>Stockholm</td> <td>1</td> <td>0</td> <td>admin</td> </tr> <tr> <td>Switzerland</td> <td>Bern</td> <td>2</td> <td>0</td> <td>self</td> </tr> <tr> <td>Switzerland</td> <td>Bern</td> <td>2</td> <td>1</td> <td>admin</td> </tr> </tbody> </table> </div> <p>(Because the user terminated from Sweden and Stockholm is over 12 months ago)</p> <p>I have tried the following query as suggested in the answer below, but it doesn't work, it doesn't count correctly (also there might be another approach without using <code>SUM</code>):</p> <pre><code>SELECT SUM(CASE WHEN termination_date IS NULL THEN 1 ELSE 0 END) AS active, SUM(CASE WHEN termination_date IS NOT NULL AND termination_date BETWEEN ? AND ? THEN 1 ELSE 0 END) AS not_active, country, city, termination_reason FROM user_data_table GROUP BY country, city, termination_reason HAVING termination_reason IS NOT NULL </code></pre> <p>I believe it also has something to do with the fact I'm summing a group with the <code>termination_reason</code> (because I want to group by it, however it affects the sum as well?)</p> <p>This is also the reason for the title of this question - because I think I need to <code>SUM</code> the active users without the <code>termination_reason</code> group, and only then group by it</p>
[ { "answer_id": 74628686, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "termination_reason country city termination_reason SELECT \n ( SELECT COUNT(*)\n FROM user_data_table\n WHERE country = U.country AND city = U.city AND end_date IS NULL\n ) AS active,\n SUM(CASE WHEN end_date IS NOT NULL AND end_date BETWEEN ? AND ? THEN 1 ELSE 0 END) AS not_active,\n country, city, termination_reason\nFROM user_data_table U\nWHERE termination_reason IS NOT NULL\nGROUP BY country, city, termination_reason\n U user_data_table" }, { "answer_id": 74631803, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 0, "selected": false, "text": "DECLARE @employees TABLE (ID INT, Country NVARCHAR(20), City NVARCHAR(20), TerminationDate DATE, TerminationReason NVARCHAR(20))\nINSERT INTO @employees (ID, Country, City, TerminationDate, TerminationReason) VALUES\n\n(1,'Sweden','Stockholm','2022-10-04','self'),\n(2,'Sweden','Stockholm','2020-03-20','admin'),\n(2,'Sweden','Stockholm',NULL,NULL),\n(3,'Switzerland','Bern',NULL,NULL),\n(4,'Switzerland','Bern','2021-12-08','admin'),\n(5,'Switzerland','Bern',NULL,NULL)\n SELECT DISTINCT Country, City, a.TerminationReason, \n SUM(Active) OVER (PARTITION BY Country, City) AS Active, \n SUM(Not_Active) OVER (PARTITION BY Country, City, TerminationReason) AS Not_Active\n FROM (\nSELECT Country, City, TerminationReason, \n CASE WHEN TerminationDate IS NULL THEN 1 ELSE 0 END AS Active, \n CASE WHEN TerminationDate IS NOT NULL THEN 1 ELSE 0 END AS Not_Active\n FROM @employees\n WHERE TerminationDate IS NULL\n OR TerminationDate > DATEADD(YEAR,-1,CURRENT_TIMESTAMP)\n ) a\n Country City TerminationReason Active Not_Active\n--------------------------------------------------------------\nSweden Stockholm NULL 1 0\nSweden Stockholm self 1 1\nSwitzerland Bern NULL 2 0\nSwitzerland Bern admin 2 1\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18178584/" ]
74,628,642
<p>I need to compute the mean of a 2D across one dimension. Here I keep all rows:</p> <pre><code>import numpy as np, time x = np.random.random((100000, 500)) t0 = time.time() y = x.mean(axis=0) # y.shape is (500,) as expected print(time.time() - t0) # 36 milliseconds </code></pre> <p>When I filter and select some rows, I notice it is 8 times slower. So I tried an easy test where <code>selected_rows</code> are in fact <em>all rows</em>. Still, it is 8 times slower:</p> <pre><code>selected_rows = np.arange(100000) t0 = time.time() y = x[selected_rows, :].mean(axis=0) # selecting all rows! print(time.time() - t0) # 280 milliseconds! (for the same result as above!) </code></pre> <p><strong>Is there a way to speed up the process of selecting certain rows (<code>selected_rows</code>), and computing <code>.mean(axis=0)</code> ?</strong></p> <p>In the specific case where <code>selected_rows</code> = all rows, it would be interesting to <em>not</em> have 8x slower execution.</p>
[ { "answer_id": 74628686, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "termination_reason country city termination_reason SELECT \n ( SELECT COUNT(*)\n FROM user_data_table\n WHERE country = U.country AND city = U.city AND end_date IS NULL\n ) AS active,\n SUM(CASE WHEN end_date IS NOT NULL AND end_date BETWEEN ? AND ? THEN 1 ELSE 0 END) AS not_active,\n country, city, termination_reason\nFROM user_data_table U\nWHERE termination_reason IS NOT NULL\nGROUP BY country, city, termination_reason\n U user_data_table" }, { "answer_id": 74631803, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 0, "selected": false, "text": "DECLARE @employees TABLE (ID INT, Country NVARCHAR(20), City NVARCHAR(20), TerminationDate DATE, TerminationReason NVARCHAR(20))\nINSERT INTO @employees (ID, Country, City, TerminationDate, TerminationReason) VALUES\n\n(1,'Sweden','Stockholm','2022-10-04','self'),\n(2,'Sweden','Stockholm','2020-03-20','admin'),\n(2,'Sweden','Stockholm',NULL,NULL),\n(3,'Switzerland','Bern',NULL,NULL),\n(4,'Switzerland','Bern','2021-12-08','admin'),\n(5,'Switzerland','Bern',NULL,NULL)\n SELECT DISTINCT Country, City, a.TerminationReason, \n SUM(Active) OVER (PARTITION BY Country, City) AS Active, \n SUM(Not_Active) OVER (PARTITION BY Country, City, TerminationReason) AS Not_Active\n FROM (\nSELECT Country, City, TerminationReason, \n CASE WHEN TerminationDate IS NULL THEN 1 ELSE 0 END AS Active, \n CASE WHEN TerminationDate IS NOT NULL THEN 1 ELSE 0 END AS Not_Active\n FROM @employees\n WHERE TerminationDate IS NULL\n OR TerminationDate > DATEADD(YEAR,-1,CURRENT_TIMESTAMP)\n ) a\n Country City TerminationReason Active Not_Active\n--------------------------------------------------------------\nSweden Stockholm NULL 1 0\nSweden Stockholm self 1 1\nSwitzerland Bern NULL 2 0\nSwitzerland Bern admin 2 1\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422096/" ]
74,628,707
<p>I need to replace 0 in a list of lists with dot &quot;.&quot;. I aslo need to replace 1 with &quot;o&quot; and 2 with &quot;*&quot; It should be something like chess board. So far I have this and I am stuck with the replacement. Thank you for your help! :)</p> <pre class="lang-py prettyprint-override"><code>chess =[ [&quot;0 1 0 1 0 1 0 1 &quot;], [&quot;1 0 1 0 1 0 1 0 &quot;], [&quot;0 1 0 1 0 1 0 1 &quot;], [&quot;0 0 0 0 0 0 0 0 &quot;], [&quot;0 0 0 0 0 0 0 0 &quot;], [&quot;2 0 2 0 2 0 2 0 &quot;], [&quot;0 2 0 2 0 2 0 2 &quot;], [&quot;2 0 2 0 2 0 2 0 &quot;]] def prt(n): for i in range(len(n)): for j in range(len(n[i])): if n[j] == &quot;0&quot;: n[j] = &quot;.&quot; print(n[i][j]) prt(chess) </code></pre> <p>Output should be something like this</p> <p><a href="https://i.stack.imgur.com/1QNos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1QNos.png" alt="Final product" /></a></p>
[ { "answer_id": 74628781, "author": "Jasmin Heifa", "author_id": 17974058, "author_profile": "https://Stackoverflow.com/users/17974058", "pm_score": 1, "selected": false, "text": "def print_chess(chess):\n for line_list in chess:\n line = line_list[0]\n line = line.replace(\"0\", \".\")\n line = line.replace(\"1\", \"o\")\n line = line.replace(\"2\", \"*\")\n print(line)\n" }, { "answer_id": 74628825, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 2, "selected": true, "text": "\"0 1 0 1 0 1 0 1 \" for i in range(len(n)): \n for j in range(len(n[i])): # len(n[i]) is always 1\n if n[j] == \"0\": # n[j]: \"0 1 0 1 0 1 0 1 \" equal \"0\" is False\n n[j]=\".\"\n split 0 split if \"1\" \"2\" chess = [\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\ndef prt(n):\n letters = \" abcdefgh\"\n # Initialize chessboard with letters\n board = [letters]\n # set enumerates start value to 1\n for i, line in enumerate(n, 1):\n numbers = line[0].split() # splits at whitespace\n line_list = []\n for num in numbers:\n if num == \"0\":\n line_list.append(\".\")\n elif num == \"1\":\n line_list.append(\"o\")\n elif num == \"2\":\n line_list.append(\"*\")\n else:\n line_list.append(num)\n # Concatenate current line index at beginning and end of line_list\n board.append([i] + line_list + [i])\n # Append letters as last line of board\n board.append(letters)\n # Print new chess board\n for line in board:\n for el in line:\n print(el, end=\" \")\n print()\n\nprt(chess)\n letters board enumerate start enumerate 1 a b c d e f g h \n1 . o . o . o . o 1 \n2 o . o . o . o . 2 \n3 . o . o . o . o 3 \n4 . . . . . . . . 4 \n5 . . . . . . . . 5 \n6 * . * . * . * . 6 \n7 . * . * . * . * 7 \n8 * . * . * . * . 8 \n a b c d e f g h \n" }, { "answer_id": 74628877, "author": "Muhammad Rizwan", "author_id": 11867299, "author_profile": "https://Stackoverflow.com/users/11867299", "pm_score": 2, "selected": false, "text": "replace chess =[\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\n\ndef prt (n):\n new_list = []\n for line in n:\n line = line[0]\n line = line.replace('0','.')\n line = line.replace('1', 'o')\n line = line.replace('2', '*')\n temp = []\n temp.append(line)\n new_list.append(temp)\n print(new_list)\n \nprt(chess)\n" }, { "answer_id": 74628933, "author": "user56700", "author_id": 11355926, "author_profile": "https://Stackoverflow.com/users/11355926", "pm_score": 2, "selected": false, "text": "from string import ascii_lowercase\n\nchess = [\n [\"0 1 0 1 0 1 0 1\"],\n [\"1 0 1 0 1 0 1 0\"],\n [\"0 1 0 1 0 1 0 1\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"2 0 2 0 2 0 2 0\"],\n [\"0 2 0 2 0 2 0 2\"],\n [\"2 0 2 0 2 0 2 0\"]\n]\n\ndef prt(chess):\n joined_chars = \"\".join(chess[0][0].split()) # joining the first list in chess to single string: 01010101\n letters = \" \".join([ascii_lowercase[i] for i in range(len(joined_chars))]) # Creating a list of letters that is the length of the joined_chars and joins it with spaces: a b c d e f g h\n print(f\" {letters}\") # prints the letters starting with two spaces\n for index, lst in enumerate(chess): # Using enumerate to get the index while running through chess\n printable = lst[0].replace(\"0\", \".\").replace(\"1\", \"o\").replace(\"2\", \"*\")\n print(f\"{index+1} {printable} {index+1}\") # prints the index (starts at 0) + 1 to get the correct values.\n print(f\" {letters}\") # prints the letters starting with two spaces\n\nprt(chess)\n a b c d e f g h\n1 . o . o . o . o 1\n2 o . o . o . o . 2\n3 . o . o . o . o 3\n4 . . . . . . . . 4\n5 . . . . . . . . 5\n6 * . * . * . * . 6\n7 . * . * . * . * 7\n8 * . * . * . * . 8\n a b c d e f g h\n" }, { "answer_id": 74641848, "author": "Jimmy", "author_id": 20347481, "author_profile": "https://Stackoverflow.com/users/20347481", "pm_score": 0, "selected": false, "text": " chess =[\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\nletters =[\"a b c d e f g h\"]\nnumbers =[\"1 2 3 4 5 6 7 8\"]\n\ndef prt(x):\n num_let(letters) \n for list in x:\n new = list[0]\n new = new.replace(\"0\", \".\")\n new = new.replace(\"1\", \"o\")\n new = new.replace(\"2\", \"*\")\n print(new)\n num_let(letters)\n \ndef num_let (y):\n print(y[0])\n\nprt(chess)\n a b c d e f g h\n. o . o . o . o \no . o . o . o .\n. o . o . o . o\n. . . . . . . .\n. . . . . . . .\n* . * . * . * .\n. * . * . * . *\n* . * . * . * .\na b c d e f g h\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20347481/" ]
74,628,719
<p>I am on Kubernetes v1.22.13. When i was trying to delete a namespace that's stuck in status <code>terminating</code>, i deleted api-service <code>v1.networking.k8s.io</code> by mistake with:</p> <pre><code>kubectl delete apiservices.apiregistration.k8s.io v1.networking.k8s.io </code></pre> <p>And now i don't have crds related to <code>v1.networking.k8s.io</code> such as <code>Ingress</code>. When i try to install ingress-controller it gives the error:</p> <blockquote> <p>error: resource mapping not found for name: &quot;nginx&quot; namespace: &quot;&quot; from &quot;https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.4.0/deploy/static/provider/cloud/deploy.yaml&quot;: no matches for kind &quot;IngressClass&quot; in version &quot;networking.k8s.io/v1&quot;</p> </blockquote> <p>How can i undo that operation? Or how can i bring back api-resource <code>v1.networking.k8s.io</code>?</p> <p>Tried to find a way to undo it and install it manually but i couldn't find the manifest related to that.</p>
[ { "answer_id": 74628781, "author": "Jasmin Heifa", "author_id": 17974058, "author_profile": "https://Stackoverflow.com/users/17974058", "pm_score": 1, "selected": false, "text": "def print_chess(chess):\n for line_list in chess:\n line = line_list[0]\n line = line.replace(\"0\", \".\")\n line = line.replace(\"1\", \"o\")\n line = line.replace(\"2\", \"*\")\n print(line)\n" }, { "answer_id": 74628825, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 2, "selected": true, "text": "\"0 1 0 1 0 1 0 1 \" for i in range(len(n)): \n for j in range(len(n[i])): # len(n[i]) is always 1\n if n[j] == \"0\": # n[j]: \"0 1 0 1 0 1 0 1 \" equal \"0\" is False\n n[j]=\".\"\n split 0 split if \"1\" \"2\" chess = [\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\ndef prt(n):\n letters = \" abcdefgh\"\n # Initialize chessboard with letters\n board = [letters]\n # set enumerates start value to 1\n for i, line in enumerate(n, 1):\n numbers = line[0].split() # splits at whitespace\n line_list = []\n for num in numbers:\n if num == \"0\":\n line_list.append(\".\")\n elif num == \"1\":\n line_list.append(\"o\")\n elif num == \"2\":\n line_list.append(\"*\")\n else:\n line_list.append(num)\n # Concatenate current line index at beginning and end of line_list\n board.append([i] + line_list + [i])\n # Append letters as last line of board\n board.append(letters)\n # Print new chess board\n for line in board:\n for el in line:\n print(el, end=\" \")\n print()\n\nprt(chess)\n letters board enumerate start enumerate 1 a b c d e f g h \n1 . o . o . o . o 1 \n2 o . o . o . o . 2 \n3 . o . o . o . o 3 \n4 . . . . . . . . 4 \n5 . . . . . . . . 5 \n6 * . * . * . * . 6 \n7 . * . * . * . * 7 \n8 * . * . * . * . 8 \n a b c d e f g h \n" }, { "answer_id": 74628877, "author": "Muhammad Rizwan", "author_id": 11867299, "author_profile": "https://Stackoverflow.com/users/11867299", "pm_score": 2, "selected": false, "text": "replace chess =[\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\n\ndef prt (n):\n new_list = []\n for line in n:\n line = line[0]\n line = line.replace('0','.')\n line = line.replace('1', 'o')\n line = line.replace('2', '*')\n temp = []\n temp.append(line)\n new_list.append(temp)\n print(new_list)\n \nprt(chess)\n" }, { "answer_id": 74628933, "author": "user56700", "author_id": 11355926, "author_profile": "https://Stackoverflow.com/users/11355926", "pm_score": 2, "selected": false, "text": "from string import ascii_lowercase\n\nchess = [\n [\"0 1 0 1 0 1 0 1\"],\n [\"1 0 1 0 1 0 1 0\"],\n [\"0 1 0 1 0 1 0 1\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"2 0 2 0 2 0 2 0\"],\n [\"0 2 0 2 0 2 0 2\"],\n [\"2 0 2 0 2 0 2 0\"]\n]\n\ndef prt(chess):\n joined_chars = \"\".join(chess[0][0].split()) # joining the first list in chess to single string: 01010101\n letters = \" \".join([ascii_lowercase[i] for i in range(len(joined_chars))]) # Creating a list of letters that is the length of the joined_chars and joins it with spaces: a b c d e f g h\n print(f\" {letters}\") # prints the letters starting with two spaces\n for index, lst in enumerate(chess): # Using enumerate to get the index while running through chess\n printable = lst[0].replace(\"0\", \".\").replace(\"1\", \"o\").replace(\"2\", \"*\")\n print(f\"{index+1} {printable} {index+1}\") # prints the index (starts at 0) + 1 to get the correct values.\n print(f\" {letters}\") # prints the letters starting with two spaces\n\nprt(chess)\n a b c d e f g h\n1 . o . o . o . o 1\n2 o . o . o . o . 2\n3 . o . o . o . o 3\n4 . . . . . . . . 4\n5 . . . . . . . . 5\n6 * . * . * . * . 6\n7 . * . * . * . * 7\n8 * . * . * . * . 8\n a b c d e f g h\n" }, { "answer_id": 74641848, "author": "Jimmy", "author_id": 20347481, "author_profile": "https://Stackoverflow.com/users/20347481", "pm_score": 0, "selected": false, "text": " chess =[\n [\"0 1 0 1 0 1 0 1 \"],\n [\"1 0 1 0 1 0 1 0 \"],\n [\"0 1 0 1 0 1 0 1 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"0 0 0 0 0 0 0 0 \"],\n [\"2 0 2 0 2 0 2 0 \"],\n [\"0 2 0 2 0 2 0 2 \"],\n [\"2 0 2 0 2 0 2 0 \"]]\n\nletters =[\"a b c d e f g h\"]\nnumbers =[\"1 2 3 4 5 6 7 8\"]\n\ndef prt(x):\n num_let(letters) \n for list in x:\n new = list[0]\n new = new.replace(\"0\", \".\")\n new = new.replace(\"1\", \"o\")\n new = new.replace(\"2\", \"*\")\n print(new)\n num_let(letters)\n \ndef num_let (y):\n print(y[0])\n\nprt(chess)\n a b c d e f g h\n. o . o . o . o \no . o . o . o .\n. o . o . o . o\n. . . . . . . .\n. . . . . . . .\n* . * . * . * .\n. * . * . * . *\n* . * . * . * .\na b c d e f g h\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8889711/" ]
74,628,727
<p><strong>What I need</strong></p> <p>I have a list of img src link. Here is an example:</p> <ul> <li><code>https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&amp;nocache=1</code></li> <li><code>https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg&amp;nocache=1</code></li> <li><code>https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png&amp;nocache=1</code></li> </ul> <p>I need get the following result:</p> <pre><code>studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png </code></pre> <p><strong>Problem</strong></p> <p>I use the following regex:</p> <pre><code>studiocake\.kiev\.ua.*(jpeg|png|jpg) </code></pre> <p>But it doesn't work the way I need. Instead of the result I need, I get link like:</p> <pre><code>studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg </code></pre> <p><strong>Question</strong></p> <p>How can I get the result I need with Python regex</p>
[ { "answer_id": 74629080, "author": "Yogesh Kumar Gupta", "author_id": 4749712, "author_profile": "https://Stackoverflow.com/users/4749712", "pm_score": 2, "selected": false, "text": "from urllib.parse import urlparse, parse_qs\n\n\ndef extractSrc(strUrl):\n # Parse original URL using urllib\n parsed_url = urlparse(strUrl)\n\n # Find the value of query parameter img\n src_value = parse_qs(parsed_url.query)['src'][0]\n \n # Again, using same library, parse img url which we got above.\n img_parsed_url = urlparse(src_value)\n\n # Remove the scheme in the img URL and return result.\n scheme = \"%s://\" % img_parsed_url.scheme\n return img_parsed_url.geturl().replace(scheme, '', 1)\n\n\n\nurls = '''https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&nocache=1\nhttps://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg&nocache=1\nhttps://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png&nocache=1'''\n\nfor u in urls.split('\\n'):\n print(extractSrc(u))\n studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg\nstudiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg\nstudiocake.kiev.ua/wp-content/uploads/tri-shokolada.png\n" }, { "answer_id": 74629171, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 3, "selected": true, "text": ".* import re\n\nmatches = re.findall(r\"(?i).*\\b(studiocake\\.kiev\\.ua\\S*\\b(?:jpeg|png|jpg))\\b\", s)\n \\S* \\b (?i)" }, { "answer_id": 74630107, "author": "Phyln", "author_id": 4032717, "author_profile": "https://Stackoverflow.com/users/4032717", "pm_score": 0, "selected": false, "text": "(https://)(studiocake\\.kiev\\.ua.*(php)\\?src=https://)(studiocake\\.kiev\\.ua.*(jpeg|png|jpg))(&nocache=1)\n $4" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19425041/" ]
74,628,746
<p>I have the input dataframe(df1) with Ids, subids and features, having the nans in the features columns,</p> <pre><code>df1 = pd.DataFrame({'Id': ['A1', 'A2', 'A3', 'B1', 'B2'], 'Subid':['A', 'A', 'A', 'B', 'B'], 'feature1':[2.6, 6.3, np.nan, np.nan, 3.3], 'feature2':[55, np.nan, np.nan, 44, 69], 'feature3':[np.nan, 0.5, 0.3, np.nan, np.nan], 'feature4':[22, np.nan, 46, np.nan, 33], 'feature5':[np.nan, np.nan, 52, np.nan, 53] }) </code></pre> <p>I have another input dataframe(df2) having subids and the features values to be filled in.</p> <pre><code>df2 = pd.DataFrame({'Subid': ['A', 'B'], 'feature1': [2.966666666666667, 1.65], 'feature2': [18.333333333333332, 56.5], 'feature3': [0.26666666666666666, 0.0], 'feature4': [22.666666666666668, 16.5], 'feature5': [17.333333333333332, 26.5]}) </code></pre> <p>I need to fill the nans in the df1 with the values present for each features in df2. I have tried lambda and apply function but unable to achieve the result</p> <pre><code>df1.loc[df1['feature1'].isna(), 'feature1'] = df2.groupby('Subid')['feature1'].apply(lambda x:x) </code></pre> <p>expected output:</p> <pre><code>outputdf = pd.DataFrame({'Id': ['A1', 'A2', 'A3', 'B1', 'B2'], 'Subid':['A', 'A', 'A', 'B', 'B'], 'feature1': [2.6, 6.3, 2.966667, 1.650000, 3.3], 'feature2': [55, 18.333333, 18.333333, 44, 69], 'feature3': [0.266667, 0.5, 0.3, 0.000000, 0.000000], 'feature4': [22, 22.666667, 46, 16.500000, 33], 'feature5': [17.333333, 17.333333, 52, 26.500000, 53] }) </code></pre> <p>Quick help is appreciated.</p>
[ { "answer_id": 74628798, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "merge fillna out = df1.fillna(df1[['Subid']].merge(df2, how='left'))\n Id Subid feature1 feature2 feature3 feature4 feature5\n0 A1 A 2.600000 55.000000 0.266667 22.000000 17.333333\n1 A2 A 6.300000 18.333333 0.500000 22.666667 17.333333\n2 A3 A 2.966667 18.333333 0.300000 46.000000 52.000000\n3 B1 B 1.650000 44.000000 0.000000 16.500000 26.500000\n4 B2 B 3.300000 69.000000 0.000000 33.000000 53.000000\n" }, { "answer_id": 74628948, "author": "Jan Z", "author_id": 20477576, "author_profile": "https://Stackoverflow.com/users/20477576", "pm_score": 0, "selected": false, "text": "for f in [f for f in df1.columns if f.startswith('feature')]:\n df1[f]=df1[f].mask(pd.isnull, df1[['Subid']].merge(df2[['Subid', f]])[f])\n Id Subid feature1 feature2 feature3 feature4 feature5\n0 A1 A 2.600000 55.000000 0.266667 22.000000 17.333333\n1 A2 A 6.300000 18.333333 0.500000 22.666667 17.333333\n2 A3 A 2.966667 18.333333 0.300000 46.000000 52.000000\n3 B1 B 1.650000 44.000000 0.000000 16.500000 26.500000\n4 B2 B 3.300000 69.000000 0.000000 33.000000 53.000000\n" }, { "answer_id": 74628969, "author": "docksdocks", "author_id": 20645767, "author_profile": "https://Stackoverflow.com/users/20645767", "pm_score": 1, "selected": false, "text": "result = df1.fillna(df1[['Subid']].merge(df2, on='Subid', how='left'))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19836382/" ]
74,628,772
<p>The date is sent from backend in this format:</p> <blockquote> <p>&quot;2022-01-01T00:00:00.00000&quot;</p> </blockquote> <p>How to display date without hours/minutes/seconds like this:</p> <blockquote> <p>2022-01-01?</p> </blockquote> <p>On my .tsx component I have InputDatepicker:</p> <pre><code> &lt;InputDatepicker label=&quot;Training date&quot; value={trainingData?.trainingDate || ''} /&gt; </code></pre>
[ { "answer_id": 74628799, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "var todayDate = new Date('2022-01-01T00:00:00.00000').toISOString().slice(0, 10);\nconsole.log(todayDate);" }, { "answer_id": 74628833, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 3, "selected": true, "text": "console.log(\"2022-01-01T00:00:00.00000\".split('T')[0]);" }, { "answer_id": 74628887, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 1, "selected": false, "text": "new Date('2022-01-01T00:00:00.00000').toLocaleDateString('en-CA');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13057627/" ]
74,628,779
<p><a href="https://i.stack.imgur.com/4c4kN.png" rel="nofollow noreferrer">enter image description here</a> I'm very new to this, I can't seem to figure out why cant I drag an image to my image folder and also I don't know how to resize my image to fit my website, can someone please help me? I am using vs code <a href="https://i.stack.imgur.com/fNaOl.png" rel="nofollow noreferrer">enter image description here</a><a href="https://i.stack.imgur.com/qZPuw.jpg" rel="nofollow noreferrer">enter image description here</a></p> <p>I checked on to find available fixes and on mdn however I am confused</p>
[ { "answer_id": 74628799, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "var todayDate = new Date('2022-01-01T00:00:00.00000').toISOString().slice(0, 10);\nconsole.log(todayDate);" }, { "answer_id": 74628833, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 3, "selected": true, "text": "console.log(\"2022-01-01T00:00:00.00000\".split('T')[0]);" }, { "answer_id": 74628887, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 1, "selected": false, "text": "new Date('2022-01-01T00:00:00.00000').toLocaleDateString('en-CA');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17215589/" ]
74,628,826
<p>I'm making a config in my Spring application and I want to define a map:</p> <pre class="lang-java prettyprint-override"><code>@Value(&quot;${ordering:#{{:}}&quot;) private Map&lt;String, List&lt;String&gt;&gt; ordering; </code></pre> <p>Here's what's in my config:</p> <pre><code>ordering = {'SOMEVALUE' : {'ONE', 'THREE', 'TWO'}, 'OTHERVALUE' : {'THREE', 'ONE', 'TWO'}} </code></pre> <p>But this always gets read as null (so I assume invalid SpEL).<br /> The name of the variable and config value aren't misspelled and other values are loaded from the same config, so those parts are set up properly.<br /> How should such a map be defined, what am I screwing up? Is there an online tool for parsing SpEL?</p> <p>I tried several things: adding and removing the single ticks, same for double ticks and wrapping the lists in an extra {}, but none of these helped and the value is still set to null.<br /> I also tried modifying the annotation, to no avail:</p> <pre><code>@Value(&quot;#{${ordering:#{{:}}}&quot;) </code></pre>
[ { "answer_id": 74628799, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "var todayDate = new Date('2022-01-01T00:00:00.00000').toISOString().slice(0, 10);\nconsole.log(todayDate);" }, { "answer_id": 74628833, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 3, "selected": true, "text": "console.log(\"2022-01-01T00:00:00.00000\".split('T')[0]);" }, { "answer_id": 74628887, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 1, "selected": false, "text": "new Date('2022-01-01T00:00:00.00000').toLocaleDateString('en-CA');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19460147/" ]
74,628,835
<p>html button</p> <pre><code>&lt;button id=&quot;styleButton&quot; class=&quot;ml-2 refreshButton&quot; (click)=&quot;removeAllFilters(appliedFilters)&quot; &gt; &lt;i class=&quot;fas fa-sync-alt&quot;&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p>ts function</p> <pre><code>removeAllFilters() { this.appliedFilters = []; this.searchStaffText = ''; this.status.map(item =&gt; { if (item.name !== StaffTypeStatus.ACTIVE) item.selected = false; }); this.locations.map(item =&gt; (item.selected = false)); this.roles.map(item =&gt; (item.selected = false)); } </code></pre> <p>I tried to apply remove all filters function, but doesn't seem to work at all.</p>
[ { "answer_id": 74628799, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "var todayDate = new Date('2022-01-01T00:00:00.00000').toISOString().slice(0, 10);\nconsole.log(todayDate);" }, { "answer_id": 74628833, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 3, "selected": true, "text": "console.log(\"2022-01-01T00:00:00.00000\".split('T')[0]);" }, { "answer_id": 74628887, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 1, "selected": false, "text": "new Date('2022-01-01T00:00:00.00000').toLocaleDateString('en-CA');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20302582/" ]
74,628,846
<p>do you know if it is possible to send responsive email through Outlook? For example to collapse some section if button are pressed? I don't find much on Internet on that. Thanks for the help</p> <p>I have tried to do some research but I don't find anything on internet.</p>
[ { "answer_id": 74628799, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "var todayDate = new Date('2022-01-01T00:00:00.00000').toISOString().slice(0, 10);\nconsole.log(todayDate);" }, { "answer_id": 74628833, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 3, "selected": true, "text": "console.log(\"2022-01-01T00:00:00.00000\".split('T')[0]);" }, { "answer_id": 74628887, "author": "Rahul Beniwal", "author_id": 7764935, "author_profile": "https://Stackoverflow.com/users/7764935", "pm_score": 1, "selected": false, "text": "new Date('2022-01-01T00:00:00.00000').toLocaleDateString('en-CA');\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646142/" ]
74,628,865
<p>getting an error as :</p> <p><code> TypeError: Cannot read properties of undefined (reading 'fetchPersonnelList')</code></p> <p>with my test spec.</p> <p>full code:</p> <pre><code> import { HttpClientModule } from '@angular/common/http'; import { Component } from '@angular/core'; import { async, ComponentFixture, fakeAsync, flush, TestBed, tick, } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ActivatedRoute, Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; import { SharedModule } from '../../../../../shared/shared.module'; import { PersonnelDataService } from '../services/personnel-data.service'; import { testHFSTaleSchema } from './hfs-table.schema'; import { ListPersonnelComponent } from './list-personnel.component'; const mockPersonnelDataService = { list$: of(testHFSTaleSchema.rows), fetchPersonnelList: function () { return { subscribe: () =&gt; this.list$ }; }, setPageSize: function () { return this.list$; }, fetchPaginatedList: () =&gt; {}, }; @Component({ selector: 'app-details-personnel', template: '', }) export class PersonnelDetailsComponent {} fdescribe('ListPersonnelComponent', () =&gt; { let component: ListPersonnelComponent; let fixture: ComponentFixture&lt;ListPersonnelComponent&gt;; let activatedRoute = { url: {} } as ActivatedRoute; let service: PersonnelDataService; let router; const routes = [ { path: 'personnel-details', component: PersonnelDetailsComponent, }, ]; beforeEach(async(() =&gt; { TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes(routes), SharedModule, BrowserAnimationsModule, HttpClientModule, ], declarations: [ListPersonnelComponent], providers: [ { provide: PersonnelDataService, useValue: mockPersonnelDataService, }, { provide: ActivatedRoute, useValue: activatedRoute }, ], }).compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(ListPersonnelComponent); component = fixture.componentInstance; router = TestBed.inject(Router); fixture.detectChanges(); }); it('should create', () =&gt; { expect(component).toBeTruthy(); }); it('should call fetchPersonnelList on page Oninit', fakeAsync(() =&gt; { component.ngOnInit(); tick(1000); expect(service.fetchPersonnelList).toHaveBeenCalled();//error flush(); })); }); </code></pre> <p><strong>UPDATE</strong></p> <p>as per <code>forestG</code> suggession i update the code by injecting service. when mock service existing, still i am getting an error as :</p> <p><code>Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.</code> when mock service added, why i am getting this error?</p> <p><strong>suggestion update</strong></p> <p>I have updated my code like:</p> <pre><code>it('should call fetchPersonnelList on page Oninit', fakeAsync(() =&gt; { const fetchPersonnelListSpy = spyOn( service, 'fetchPersonnelList' ).and.returnValue(of([])); component.ngOnInit(); tick(1000); expect(fetchPersonnelListSpy).toHaveBeenCalled(); flush(); })); </code></pre> <p>it works. but what is the benefit of my mock service? how can I expect my mock data. I can put my data directly in the <code>retunValue</code> part right? any one help me please?</p>
[ { "answer_id": 74628918, "author": "ForestG", "author_id": 3486691, "author_profile": "https://Stackoverflow.com/users/3486691", "pm_score": 0, "selected": false, "text": " beforeEach(() => {\n fixture = TestBed.createComponent(ListPersonnelComponent);\n component = fixture.componentInstance;\n router = TestBed.inject(Router);\n service = TestBed.inject(PersonnelDataService); // add this\n fixture.detectChanges();\n });\n" }, { "answer_id": 74631103, "author": "Mr. Stash", "author_id": 13625800, "author_profile": "https://Stackoverflow.com/users/13625800", "pm_score": 2, "selected": true, "text": "spyOn(component.service, 'fetchPersonnelList') .callThrough() .returnValue(of([])); it('should call fetchPersonnelList on page Oninit', () => {\n const fetchPersonnelListSpy = spyOn(component.service, 'fetchPersonnelList').and.callThrough();\n component.ngOnInit();\n expect(fetchPersonnelListSpy).toHaveBeenCalled();\n});\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/218349/" ]
74,628,879
<p>I have to realize a project between Python and C. One of the instructions is to use <code>ctypes</code>, so I need to call my C function from Python. The latter needs me to send it two integer variables and a structure array. But I can't get the declaration to work. I don't know how to make the declaration.</p> <p>C:</p> <pre class="lang-c prettyprint-override"><code>typedef struct //Defini une structure qui a été envoyée par le code Python et qui contient uniquement les élements utiles { int UID; float prix; float poids; int quantite; int nb_commande; } reference; int sac_dos_brute(int nb_produit, reference *tab, float masse) // Recupere le nombre de produits et un tableau de structures pour pouvoir gérrer l'expedition { tri(tab, nb_produit); remplir_camion(tab,nb_produit,masse); return tab; } </code></pre> <p>Python:</p> <pre class="lang-py prettyprint-override"><code>from ctypes import * dll = CDLL('C:/..../workplease.dll') class reference (Structure): _fields_ = [ ('UID',c_int), ('prix',c_float), ('poids',c_float), ('quantite',c_int), ('nb_commande',c_int), ] '''dll.sac_dos_brute.argtypes = [c_int, c_int, POINTER(reference)] dll.sac_dos_brute(nb_produits, nb_camion, tab)''' nb_produit=2 dll.sac_dos_brute.argtypes=[POINTER(reference)] tab = [reference()]*2 tab[0].UID = 234 tab[0].prix= 12 tab[0].poids= 234 tab[0].quantite= 3 tab[0].nb_commande=1 tab[1].UID = 237 tab[1].prix= 15 tab[1].poids= 256 tab[1].quantite= 6 tab[1].nb_commande=2 dll.sac_dos_brute.argtype(c_int,c_int,c_, ) t = dll.sac_dos_brute(nb_produit, byref(tab)) </code></pre>
[ { "answer_id": 74629789, "author": "CreepyRaccoon", "author_id": 18342123, "author_profile": "https://Stackoverflow.com/users/18342123", "pm_score": 1, "selected": false, "text": "list[reference] Array[reference] tab = (reference * 2)() import ctypes as c\n\ndef sac_dos_brute(nb_produit: int, reference: c.Array[reference], masse: float) -> None:\n dll = c.cdll.LoadLibrary('C:/..../workplease.dll')\n dll.sac_dos_brute(c.c_int(nb_produit), c.byref(reference), c.c_float(masse))\n\nnb_produit: int = 2\ntab = (reference * 2)()\ntab[0].UID = 234\ntab[0].nom = b'Iphone'\ntab[0].prix = 12.0\ntab[0].poids = 234.0\ntab[0].categorie = b'Telephone'\ntab[0].marque = b'Apple'\ntab[0].annee = 2020\ntab[0].quantite = 3\ntab[0].nb_commande = 1\ntab[0].avis = 5\ntab[1].UID = 237\ntab[1].nom = b'Ipad'\ntab[1].prix = 15.0\ntab[1].poids = 256.0\ntab[1].categorie = b'Tablette'\ntab[1].marque = b'Apple'\ntab[1].annee = 2022\ntab[1].quantite = 6\ntab[1].nb_commande = 2\ntab[1].avis = 4\nmasse: float = 0.0\n\nsac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631034, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 0, "selected": false, "text": "int sac_dos_brute(int nb_produit, reference *tab, float masse) ;\n dll.sac_dos_brute.argtypes = [c_int, POINTER(reference), c_float]\n [reference()]*2\n reference() reference tab = (reference * 2)()\n byref byref dll.sac_dos_brute(nb_produit, tab, masse)\n from ctypes import *\n\ndll = CDLL('C:/..../workplease.dll')\n\nclass reference (Structure):\n _fields_ =[\n ('UID',c_int),\n ('prix',c_float),\n ('poids',c_float),\n ('quantite',c_int),\n ('nb_commande',c_int),\n ]\n\ndll.sac_dos_brute.argtypes=[c_int, POINTER(reference), c_float]\n\n\nnb_produit=2\ntab = (reference*nb_produit)()\n\ntab[0].UID = 234\ntab[0].prix= 12\ntab[0].poids= 234\ntab[0].quantite= 3\ntab[0].nb_commande=1\n\ntab[1].UID = 237\ntab[1].prix= 15\ntab[1].poids= 256\ntab[1].quantite= 6\ntab[1].nb_commande=2\n\nmasse=3.14 # Just something I've chosen to fill the holes\n \nt = dll.sac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631539, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 0, "selected": false, "text": ".argtypes .restype ctypes (type * size)(item, item, ...) #include <stdio.h>\n\n#ifdef _WIN32\n# define API __declspec(dllexport)\n#else\n# define API\n#endif\n\ntypedef struct {\n int UID;\n float prix;\n float poids;\n int quantite;\n int nb_commande;\n} reference;\n\nAPI int sac_dos_brute(int nb_produit, reference *tab, float masse) {\n printf(\"masse = %f\\n\", masse);\n for(int i = 0; i < nb_produit; ++i)\n printf(\"tab[%d] = %d, %f ,%f, %d, %d\\n\",\n i, tab[i].UID, tab[i].prix, tab[i].poids, tab[i].quantite, tab[i].nb_commande);\n return 123;\n}\n import ctypes as ct\n\nclass Reference(ct.Structure):\n\n _fields_ = (('UID', ct.c_int),\n ('prix', ct.c_float),\n ('poids', ct.c_float),\n ('quantite', ct.c_int),\n ('nb_commande', ct.c_int))\n\n # Tell class how to display itself\n def __repr__(self):\n return (f'Reference(UID={self.UID}, prix={self.prix}, poids={self.poids}, '\n f'quantite={self.quantite}, nb_commande={self.nb_commande})')\n\ndll = ct.CDLL('./test')\n# Make sure argument types and restype match the C function in type and order\ndll.sac_dos_brute.argtypes = ct.c_int, ct.POINTER(Reference), ct.c_float\ndll.sac_dos_brute.restype = ct.c_int\n\n# Efficient way to create an array of two Reference types.\ntab = (Reference * 2)(Reference(234, 12, 234, 3, 1),\n Reference(237, 15, 256, 6, 2))\n\n# Test __repr__\nfor t in tab:\n print(t)\n\n# Test the function\nprint(dll.sac_dos_brute(len(tab), tab, 1.25))\n Reference(UID=234, prix=12.0, poids=234.0, quantite=3, nb_commande=1)\nReference(UID=237, prix=15.0, poids=256.0, quantite=6, nb_commande=2)\nmasse = 1.250000\ntab[0] = 234, 12.000000 ,234.000000, 3, 1\ntab[1] = 237, 15.000000 ,256.000000, 6, 2\n123\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646183/" ]
74,628,883
<p>Im trying to get the id of the logged in user. When the user is clicking on the button his id need to get send to the data base, But I get an error: 1048 Column 'user_id' cannot be null.</p> <p>This is my controller function:</p> <pre><code> public function LendBook(Request $request) { $user_id = $request-&gt;session()-&gt;get('User_id'); $book_id = $request-&gt;book_id; $q = new lend; $q-&gt;user_id = $user_id; $q-&gt;book_id = $book_id; $q-&gt;save(); return 'test'; } } </code></pre>
[ { "answer_id": 74629789, "author": "CreepyRaccoon", "author_id": 18342123, "author_profile": "https://Stackoverflow.com/users/18342123", "pm_score": 1, "selected": false, "text": "list[reference] Array[reference] tab = (reference * 2)() import ctypes as c\n\ndef sac_dos_brute(nb_produit: int, reference: c.Array[reference], masse: float) -> None:\n dll = c.cdll.LoadLibrary('C:/..../workplease.dll')\n dll.sac_dos_brute(c.c_int(nb_produit), c.byref(reference), c.c_float(masse))\n\nnb_produit: int = 2\ntab = (reference * 2)()\ntab[0].UID = 234\ntab[0].nom = b'Iphone'\ntab[0].prix = 12.0\ntab[0].poids = 234.0\ntab[0].categorie = b'Telephone'\ntab[0].marque = b'Apple'\ntab[0].annee = 2020\ntab[0].quantite = 3\ntab[0].nb_commande = 1\ntab[0].avis = 5\ntab[1].UID = 237\ntab[1].nom = b'Ipad'\ntab[1].prix = 15.0\ntab[1].poids = 256.0\ntab[1].categorie = b'Tablette'\ntab[1].marque = b'Apple'\ntab[1].annee = 2022\ntab[1].quantite = 6\ntab[1].nb_commande = 2\ntab[1].avis = 4\nmasse: float = 0.0\n\nsac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631034, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 0, "selected": false, "text": "int sac_dos_brute(int nb_produit, reference *tab, float masse) ;\n dll.sac_dos_brute.argtypes = [c_int, POINTER(reference), c_float]\n [reference()]*2\n reference() reference tab = (reference * 2)()\n byref byref dll.sac_dos_brute(nb_produit, tab, masse)\n from ctypes import *\n\ndll = CDLL('C:/..../workplease.dll')\n\nclass reference (Structure):\n _fields_ =[\n ('UID',c_int),\n ('prix',c_float),\n ('poids',c_float),\n ('quantite',c_int),\n ('nb_commande',c_int),\n ]\n\ndll.sac_dos_brute.argtypes=[c_int, POINTER(reference), c_float]\n\n\nnb_produit=2\ntab = (reference*nb_produit)()\n\ntab[0].UID = 234\ntab[0].prix= 12\ntab[0].poids= 234\ntab[0].quantite= 3\ntab[0].nb_commande=1\n\ntab[1].UID = 237\ntab[1].prix= 15\ntab[1].poids= 256\ntab[1].quantite= 6\ntab[1].nb_commande=2\n\nmasse=3.14 # Just something I've chosen to fill the holes\n \nt = dll.sac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631539, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 0, "selected": false, "text": ".argtypes .restype ctypes (type * size)(item, item, ...) #include <stdio.h>\n\n#ifdef _WIN32\n# define API __declspec(dllexport)\n#else\n# define API\n#endif\n\ntypedef struct {\n int UID;\n float prix;\n float poids;\n int quantite;\n int nb_commande;\n} reference;\n\nAPI int sac_dos_brute(int nb_produit, reference *tab, float masse) {\n printf(\"masse = %f\\n\", masse);\n for(int i = 0; i < nb_produit; ++i)\n printf(\"tab[%d] = %d, %f ,%f, %d, %d\\n\",\n i, tab[i].UID, tab[i].prix, tab[i].poids, tab[i].quantite, tab[i].nb_commande);\n return 123;\n}\n import ctypes as ct\n\nclass Reference(ct.Structure):\n\n _fields_ = (('UID', ct.c_int),\n ('prix', ct.c_float),\n ('poids', ct.c_float),\n ('quantite', ct.c_int),\n ('nb_commande', ct.c_int))\n\n # Tell class how to display itself\n def __repr__(self):\n return (f'Reference(UID={self.UID}, prix={self.prix}, poids={self.poids}, '\n f'quantite={self.quantite}, nb_commande={self.nb_commande})')\n\ndll = ct.CDLL('./test')\n# Make sure argument types and restype match the C function in type and order\ndll.sac_dos_brute.argtypes = ct.c_int, ct.POINTER(Reference), ct.c_float\ndll.sac_dos_brute.restype = ct.c_int\n\n# Efficient way to create an array of two Reference types.\ntab = (Reference * 2)(Reference(234, 12, 234, 3, 1),\n Reference(237, 15, 256, 6, 2))\n\n# Test __repr__\nfor t in tab:\n print(t)\n\n# Test the function\nprint(dll.sac_dos_brute(len(tab), tab, 1.25))\n Reference(UID=234, prix=12.0, poids=234.0, quantite=3, nb_commande=1)\nReference(UID=237, prix=15.0, poids=256.0, quantite=6, nb_commande=2)\nmasse = 1.250000\ntab[0] = 234, 12.000000 ,234.000000, 3, 1\ntab[1] = 237, 15.000000 ,256.000000, 6, 2\n123\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19197073/" ]
74,628,939
<p>I want to create new agents after the cutting (delay Block). I tried to use the exit and enter Block. I get this Error: The method take(Agent) is undefined for the type Main._enter_Population</p> <p>My Agents have no parameters in the Population, is this the problem? I write the code in the Enterblock and nothing in the Exitblock.</p> <p>This is the code:</p> <pre><code>Agent Ober=add_materials(); enter.take(Ober); </code></pre>
[ { "answer_id": 74629789, "author": "CreepyRaccoon", "author_id": 18342123, "author_profile": "https://Stackoverflow.com/users/18342123", "pm_score": 1, "selected": false, "text": "list[reference] Array[reference] tab = (reference * 2)() import ctypes as c\n\ndef sac_dos_brute(nb_produit: int, reference: c.Array[reference], masse: float) -> None:\n dll = c.cdll.LoadLibrary('C:/..../workplease.dll')\n dll.sac_dos_brute(c.c_int(nb_produit), c.byref(reference), c.c_float(masse))\n\nnb_produit: int = 2\ntab = (reference * 2)()\ntab[0].UID = 234\ntab[0].nom = b'Iphone'\ntab[0].prix = 12.0\ntab[0].poids = 234.0\ntab[0].categorie = b'Telephone'\ntab[0].marque = b'Apple'\ntab[0].annee = 2020\ntab[0].quantite = 3\ntab[0].nb_commande = 1\ntab[0].avis = 5\ntab[1].UID = 237\ntab[1].nom = b'Ipad'\ntab[1].prix = 15.0\ntab[1].poids = 256.0\ntab[1].categorie = b'Tablette'\ntab[1].marque = b'Apple'\ntab[1].annee = 2022\ntab[1].quantite = 6\ntab[1].nb_commande = 2\ntab[1].avis = 4\nmasse: float = 0.0\n\nsac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631034, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 0, "selected": false, "text": "int sac_dos_brute(int nb_produit, reference *tab, float masse) ;\n dll.sac_dos_brute.argtypes = [c_int, POINTER(reference), c_float]\n [reference()]*2\n reference() reference tab = (reference * 2)()\n byref byref dll.sac_dos_brute(nb_produit, tab, masse)\n from ctypes import *\n\ndll = CDLL('C:/..../workplease.dll')\n\nclass reference (Structure):\n _fields_ =[\n ('UID',c_int),\n ('prix',c_float),\n ('poids',c_float),\n ('quantite',c_int),\n ('nb_commande',c_int),\n ]\n\ndll.sac_dos_brute.argtypes=[c_int, POINTER(reference), c_float]\n\n\nnb_produit=2\ntab = (reference*nb_produit)()\n\ntab[0].UID = 234\ntab[0].prix= 12\ntab[0].poids= 234\ntab[0].quantite= 3\ntab[0].nb_commande=1\n\ntab[1].UID = 237\ntab[1].prix= 15\ntab[1].poids= 256\ntab[1].quantite= 6\ntab[1].nb_commande=2\n\nmasse=3.14 # Just something I've chosen to fill the holes\n \nt = dll.sac_dos_brute(nb_produit, tab, masse)\n" }, { "answer_id": 74631539, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 0, "selected": false, "text": ".argtypes .restype ctypes (type * size)(item, item, ...) #include <stdio.h>\n\n#ifdef _WIN32\n# define API __declspec(dllexport)\n#else\n# define API\n#endif\n\ntypedef struct {\n int UID;\n float prix;\n float poids;\n int quantite;\n int nb_commande;\n} reference;\n\nAPI int sac_dos_brute(int nb_produit, reference *tab, float masse) {\n printf(\"masse = %f\\n\", masse);\n for(int i = 0; i < nb_produit; ++i)\n printf(\"tab[%d] = %d, %f ,%f, %d, %d\\n\",\n i, tab[i].UID, tab[i].prix, tab[i].poids, tab[i].quantite, tab[i].nb_commande);\n return 123;\n}\n import ctypes as ct\n\nclass Reference(ct.Structure):\n\n _fields_ = (('UID', ct.c_int),\n ('prix', ct.c_float),\n ('poids', ct.c_float),\n ('quantite', ct.c_int),\n ('nb_commande', ct.c_int))\n\n # Tell class how to display itself\n def __repr__(self):\n return (f'Reference(UID={self.UID}, prix={self.prix}, poids={self.poids}, '\n f'quantite={self.quantite}, nb_commande={self.nb_commande})')\n\ndll = ct.CDLL('./test')\n# Make sure argument types and restype match the C function in type and order\ndll.sac_dos_brute.argtypes = ct.c_int, ct.POINTER(Reference), ct.c_float\ndll.sac_dos_brute.restype = ct.c_int\n\n# Efficient way to create an array of two Reference types.\ntab = (Reference * 2)(Reference(234, 12, 234, 3, 1),\n Reference(237, 15, 256, 6, 2))\n\n# Test __repr__\nfor t in tab:\n print(t)\n\n# Test the function\nprint(dll.sac_dos_brute(len(tab), tab, 1.25))\n Reference(UID=234, prix=12.0, poids=234.0, quantite=3, nb_commande=1)\nReference(UID=237, prix=15.0, poids=256.0, quantite=6, nb_commande=2)\nmasse = 1.250000\ntab[0] = 234, 12.000000 ,234.000000, 3, 1\ntab[1] = 237, 15.000000 ,256.000000, 6, 2\n123\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20632788/" ]
74,628,965
<p>I am trying to run terra::extract to sum population (from a .tif) to global regions (from a .shp). Below is a reproducible example of the code that I run. In the case below, the memory use before (A) and after (B) the extract function and after memory clearup (C) is almost similar. However, running the exact same code but with a larger .tif and .shp leads to a very large spike of memory use, where memory use is (A: 142Mb, B: 14882Mb, C: 143.3MB ). I can imagine a difference because the datasets are larger and there is more computational effort, but this seems rather excessive. Is this normal, and if not, is there a way cleaning memory on the fly during terra::extract? I am also trying to run it on a stack of rasters, but after hours of running it unsurprisingly gives an out of memory error.</p> <pre><code>library(terra) myfun &lt;- function(x){as.integer(sum(x,na.rm=T))} f &lt;- system.file(&quot;ex/lux.shp&quot;, package=&quot;terra&quot;) v &lt;- vect(f) rf &lt;- system.file(&quot;ex/elev.tif&quot;, package=&quot;terra&quot;) x &lt;- rast(rf) paste0(&quot;A: &quot;,memory.size(),&quot; MB.&quot;) a &lt;-terra::extract(x, v, myfun, bind=TRUE) paste0(&quot;B: &quot;,memory.size(),&quot; MB.&quot;) gc() paste0(&quot;C: &quot;,memory.size(),&quot; MB.&quot;) </code></pre>
[ { "answer_id": 74630991, "author": "nukubiho", "author_id": 11868027, "author_profile": "https://Stackoverflow.com/users/11868027", "pm_score": 1, "selected": false, "text": "library(sf)\nlibrary(terra)\nlibrary(exactextractr)\n\nf <- system.file(\"ex/lux.shp\", package=\"terra\")\nv <- read_sf(f) # or st_as_sf(vect(f))\nrf <- system.file(\"ex/elev.tif\", package=\"terra\")\nx <- rast(rf)\n\na <- exact_extract(x, v, 'sum')\na <- as.integer(a)\n" }, { "answer_id": 74639488, "author": "Robert Hijmans", "author_id": 635245, "author_profile": "https://Stackoverflow.com/users/635245", "pm_score": 0, "selected": false, "text": "zonal library(terra)\nv <- vect(system.file(\"ex/lux.shp\", package=\"terra\"))\nx <- rast(system.file(\"ex/elev.tif\", package=\"terra\"))\n#a <- terra::extract(x, v, myfun)\n\nv$ID <- 1:nrow(v)\nz <- rasterize(v, x, \"ID\")\nb <- zonal(x, z, sum, na.rm=TRUE)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400636/" ]
74,628,978
<p>This is the part of code where I try to open the file f1.txt, it is complete path is C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt</p> <p><code>ifstream fichier(&quot;C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt&quot;, ios::in);</code></p> <p>The file cannot be opened and I don't know why?!</p> <p>NSGA2-CDS is the folder that contain the visual studio solution</p>
[ { "answer_id": 74630991, "author": "nukubiho", "author_id": 11868027, "author_profile": "https://Stackoverflow.com/users/11868027", "pm_score": 1, "selected": false, "text": "library(sf)\nlibrary(terra)\nlibrary(exactextractr)\n\nf <- system.file(\"ex/lux.shp\", package=\"terra\")\nv <- read_sf(f) # or st_as_sf(vect(f))\nrf <- system.file(\"ex/elev.tif\", package=\"terra\")\nx <- rast(rf)\n\na <- exact_extract(x, v, 'sum')\na <- as.integer(a)\n" }, { "answer_id": 74639488, "author": "Robert Hijmans", "author_id": 635245, "author_profile": "https://Stackoverflow.com/users/635245", "pm_score": 0, "selected": false, "text": "zonal library(terra)\nv <- vect(system.file(\"ex/lux.shp\", package=\"terra\"))\nx <- rast(system.file(\"ex/elev.tif\", package=\"terra\"))\n#a <- terra::extract(x, v, myfun)\n\nv$ID <- 1:nrow(v)\nz <- rasterize(v, x, \"ID\")\nb <- zonal(x, z, sum, na.rm=TRUE)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646120/" ]
74,628,987
<p>I have an Outlook VSTO add-in. I want to respond to incoming emails. This works quite well with the declaration</p> <pre><code>Public WithEvents items As Outlook.Items </code></pre> <p>And the definition for the items that are observed. (I'm afraid that's why only &quot;Inbox&quot; is watched):</p> <pre><code>inbox = objOutlook.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) items = inbox.Items </code></pre> <p>and the eventhandler</p> <pre><code>Private Sub Items_ItemAdd(ByVal item As Object) Handles items.ItemAdd </code></pre> <p>Even if Outlook is closed, an event is triggered for each new email when Outlook is started.</p> <p>I've now noticed that some users of the add-in have created a rule that moves incoming emails to a subfolder of &quot;Inbox&quot;. In this case, the <strong>Items_ItemAdd</strong> event <strong>is not fired</strong> when a new email arrives.</p> <p>How can I also capture these new emails that are moved via a rule?</p>
[ { "answer_id": 74630991, "author": "nukubiho", "author_id": 11868027, "author_profile": "https://Stackoverflow.com/users/11868027", "pm_score": 1, "selected": false, "text": "library(sf)\nlibrary(terra)\nlibrary(exactextractr)\n\nf <- system.file(\"ex/lux.shp\", package=\"terra\")\nv <- read_sf(f) # or st_as_sf(vect(f))\nrf <- system.file(\"ex/elev.tif\", package=\"terra\")\nx <- rast(rf)\n\na <- exact_extract(x, v, 'sum')\na <- as.integer(a)\n" }, { "answer_id": 74639488, "author": "Robert Hijmans", "author_id": 635245, "author_profile": "https://Stackoverflow.com/users/635245", "pm_score": 0, "selected": false, "text": "zonal library(terra)\nv <- vect(system.file(\"ex/lux.shp\", package=\"terra\"))\nx <- rast(system.file(\"ex/elev.tif\", package=\"terra\"))\n#a <- terra::extract(x, v, myfun)\n\nv$ID <- 1:nrow(v)\nz <- rasterize(v, x, \"ID\")\nb <- zonal(x, z, sum, na.rm=TRUE)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74628987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470372/" ]
74,629,000
<p>I have a StatelessWidget defined as:</p> <pre class="lang-dart prettyprint-override"><code>class FlexElement extends StatelessWidget { final List&lt;Widget&gt; widgets; final bool isVisible; const FlexElement({ Key? key, required this.widgets, required this.isVisible, }) : super(key: key); @override Widget build(BuildContext context) { return Visibility( visible: isVisible, child: Container( child: Row( children: &lt;Widget&gt;[...widgets], ), ), ); } } </code></pre> <p>I would like to wrap each widget with a Flexible, so it doesn't overflow. (Row(children: Flexible([...widgets])). But since it is a list of widgets, I can only assign to multiple children and not to a single child. How would I solve this?</p> <p>This is the result i would like:</p> <pre class="lang-dart prettyprint-override"><code>Row( children: [ Flexible( child: Widget1(), // &lt;-- Wrapped in Flexible. ), Flexible( child: Widget2(), // &lt;-- Wrapped in Flexible. ), ... ], ) </code></pre>
[ { "answer_id": 74629293, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": true, "text": "children: <Widget>[...widgets.map((w)=>Flexible(child:w))],\n children:widgets.map((w)=>Flexible(child:w)).toList(),\n" }, { "answer_id": 74629416, "author": "Roslan Amir", "author_id": 3365667, "author_profile": "https://Stackoverflow.com/users/3365667", "pm_score": 0, "selected": false, "text": "Row(\n children: [\n Flexible(\n flex: 20,\n fit: FlexFit.tight,\n child: Widget1(), // <-- Wrapped in Flexible.\n ),\n Flexible(\n flex: 30,\n fit: FlexFit.tight,\n child: Widget2(), // <-- Wrapped in Flexible.\n ),\n ...\n ],\n)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15438511/" ]
74,629,030
<p>I know that this probably is not the best way to do this. I read the question with the same title here, but it not solve my problem.</p> <p>The question is: I have a server that only will achieve a result that I wanna if I run a command line in the server. So I wanna write a test to check the state of one page before and after I run that command. How I do that?</p> <p>I tried to use the simple-ssh package, but I keep getting this error while trying to read the ssh key file:</p> <p><code>fs.readFileSync is not a function</code></p> <p>Actually my code looks like this:</p> <pre class="lang-js prettyprint-override"><code>import * as fs from 'fs'; let sshConfig = Cypress.config('ssh') sshConfig.key = fs.readFileSync('path/to/key/file') let SSH = require('simple-ssh'); Cypress.Commands.add('teste', () =&gt; { let ssh = new SSH(sshConfig) ssh.exec('echo', { args: ['$PATH'], out: function(stdout) { console.log(stdout); } }).start(); }) </code></pre> <p>Other possibility's are welcome.</p>
[ { "answer_id": 74634760, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 1, "selected": false, "text": "cy.readFile() const SSH = require('simple-ssh');\n\nCypress.Commands.add('testSSH', () => {\n\n cy.readFile('path/to/key/file').then(key\n const sshConfig = Cypress.config('ssh')\n sshConfig.key = key\n\n const ssh = new SSH(sshConfig)\n ssh.exec('echo', {\n args: ['$PATH'],\n out: function(stdout) {\n console.log(stdout);\n }\n }).start()\n })\n})\n fs simple-ssh" }, { "answer_id": 74634960, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 3, "selected": true, "text": "simple-ssh console.log() const { defineConfig } = require('cypress')\nconst fs = require('fs')\nconst SSH = require('simple-ssh');\n\nmodule.exports = defineConfig({\n e2e: {\n setupNodeEvents(on, config) {\n on('task', {\n ssh() {\n const sshConfig = config.ssh\n sshConfig.key = fs.readFileSync('path/to/key/file')\n \n const ssh = new SSH(sshConfig) \n ssh.exec('echo', {\n args: ['$PATH'],\n out: function(stdout) {\n console.log(stdout);\n }\n }).start();\n\n return null\n },\n })\n }\n }\n})\n Cypress.Commands.add('ssh', () => {\n cy.task('ssh')\n})\n\ncy.ssh()\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11531064/" ]
74,629,035
<p>The interpreter gives me a syntax error when it reaches elif in the code below. Why?</p> <pre><code>while walls: rand_wall = walls[int(random.random()*len(walls))-1] if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1: if maze[rand_wall[0][rand_wall[1]-1] == &quot;u&quot; and maze[rand_wall[0][rand_wall[1]+1] == &quot;c&quot;: print(&quot;no&quot;) elif maze[rand_wall[0][rand_wall[1]-1] == &quot;c&quot; and maze[rand_wall[0][rand_wall[1]+1] == &quot;u&quot;: print(&quot;no&quot;) </code></pre> <p>If the first condition is true, I want to check a second condition and its mirror condition and run some code (replaced with print(&quot;no&quot;) for debugging) if either condition is true.</p>
[ { "answer_id": 74634760, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 1, "selected": false, "text": "cy.readFile() const SSH = require('simple-ssh');\n\nCypress.Commands.add('testSSH', () => {\n\n cy.readFile('path/to/key/file').then(key\n const sshConfig = Cypress.config('ssh')\n sshConfig.key = key\n\n const ssh = new SSH(sshConfig)\n ssh.exec('echo', {\n args: ['$PATH'],\n out: function(stdout) {\n console.log(stdout);\n }\n }).start()\n })\n})\n fs simple-ssh" }, { "answer_id": 74634960, "author": "Paolo", "author_id": 16791505, "author_profile": "https://Stackoverflow.com/users/16791505", "pm_score": 3, "selected": true, "text": "simple-ssh console.log() const { defineConfig } = require('cypress')\nconst fs = require('fs')\nconst SSH = require('simple-ssh');\n\nmodule.exports = defineConfig({\n e2e: {\n setupNodeEvents(on, config) {\n on('task', {\n ssh() {\n const sshConfig = config.ssh\n sshConfig.key = fs.readFileSync('path/to/key/file')\n \n const ssh = new SSH(sshConfig) \n ssh.exec('echo', {\n args: ['$PATH'],\n out: function(stdout) {\n console.log(stdout);\n }\n }).start();\n\n return null\n },\n })\n }\n }\n})\n Cypress.Commands.add('ssh', () => {\n cy.task('ssh')\n})\n\ncy.ssh()\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646296/" ]
74,629,049
<p>I'm trying to do a front of an HTML website by using vue.js, but I wasn't able to center an image using css.</p> <p>I wrote all of my code in the App.vue file :</p> <pre><code>&lt;template&gt; &lt;div id=&quot;container3&quot;&gt; &lt;img id=&quot;teamBackground&quot; src=&quot;./assets/bourg_palette_rounded.png&quot; alt=&quot;Bourg palette in background&quot; width=&quot;360&quot; height=&quot;170&quot;/&gt; &lt;/div&gt; &lt;/template&gt; &lt;style&gt; &lt;!-- team --&gt; #container3 img{ display:block; margin:0 auto; } &lt;/style&gt; </code></pre> <p>I tried the <code>text-align</code> and the <code>display-block</code> + <code>margin: 0 auto</code> properties but it didn't change neither the placement of the image or the placement of other elements</p>
[ { "answer_id": 74629270, "author": "Can Ozdemir", "author_id": 18617885, "author_profile": "https://Stackoverflow.com/users/18617885", "pm_score": 0, "selected": false, "text": "#container3 {\n display: flex;\n flex-direction: column;\n justify-content: center;\n}" }, { "answer_id": 74656459, "author": "Nilesh Yadav", "author_id": 16333958, "author_profile": "https://Stackoverflow.com/users/16333958", "pm_score": 0, "selected": false, "text": "#container3 {\n display: flex;\n width:100%;\n height:500px; \n justify-content: center;\n align-items: center;\n}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14507864/" ]
74,629,067
<p>I have a uniprot document with a protein sequence as well as some metadata. I need to use perl to match the sequence and print it out but for some reason the last line always comes out two times. The code I wrote is here</p> <pre><code>#!usr/bin/perl open (IN,'P30988.txt'); while (&lt;IN&gt;) { if($_=~m /^\s+(\D+)/) { #this is the pattern I used to match the sequence in the document $seq=$1; $seq=~s/\s//g;} #removing the spaces from the sequence print $seq; } </code></pre> <p>I instead tried <code> $seq.=$1;</code> but it printed out the sequence 4.5 times. Im sure i have made a mistake here but not sure what. Here is the input file <a href="https://www.uniprot.org/uniprot/P30988.txt" rel="nofollow noreferrer">https://www.uniprot.org/uniprot/P30988.txt</a></p>
[ { "answer_id": 74629461, "author": "pmqs", "author_id": 2030808, "author_profile": "https://Stackoverflow.com/users/2030808", "pm_score": 3, "selected": true, "text": "#!usr/bin/perl\nopen (IN,'P30988.txt');\nwhile (<IN>) {\n\n if ($_ =~ m /^\\s+(\\D+)/) { \n $seq = $1;\n $seq =~ s/\\s//g;\n } \n\n print $seq; \n}\n print $seq #!usr/bin/perl\nopen (IN,'P30988.txt');\nwhile (<IN>) {\n\n if ($_ =~ m /^\\s+(\\D+)/) { \n $seq = $1;\n $seq =~ s/\\s//g;\n\n # only print $seq for lines that match with /^\\s+(\\D+)/\n # Also - added a newline to make it easier to debug\n\n print $seq . \"\\n\";\n } \n}\n MRFTFTSRCLALFLLLNHPTPILPAFSNQTYPTIEPKPFLYVVGRKKMMDAQYKCYDRMQ \nQLPAYQGEGPYCNRTWDGWLCWDDTPAGVLSYQFCPDYFPDFDPSEKVTKYCDEKGVWFK \nHPENNRTWSNYTMCNAFTPEKLKNAYVLYYLAIVGHSLSIFTLVISLGIFVFFRSLGCQR \nVTLHKNMFLTYILNSMIIIIHLVEVVPNGELVRRDPVSCKILHFFHQYMMACNYFWMLCE \nGIYLHTLIVVAVFTEKQRLRWYYLLGWGFPLVPTTIHAITRAVYFNDNCWLSVETHLLYI \nIHGPVMAALVVNFFFLLNIVRVLVTKMRETHEAESHMYLKAVKATMILVPLLGIQFVVFP \nWRPSNKMLGKIYDYVMHSLIHFQGFFVATIYCFCNNEVQTTVKRQWAQFKIQWNQRWGRR \nPSNRSARAAAAAAEAGDIPIYICHQELRNEPANNQGEESAEIIPLNIIEQESSA \n" }, { "answer_id": 74631594, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 2, "selected": false, "text": "while (<IN>) {\n next unless m/^\\s/;\n s/\\s+//g;\n print;\n }\n next if $1 if print $_ if" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20141877/" ]
74,629,078
<p>I want to store 2D matrices in a another list or container.</p> <p>I have 5 different 2d matrices. Each matrix has a size <code>36 X 36</code>. I want my output as below,</p> <pre><code>big_matrix = [ [36 X 36], [36 X 36], [36 X 36], [36 X 36], [36 X 36]] </code></pre> <p>Kindly guide me.</p>
[ { "answer_id": 74629286, "author": "Jasmin Heifa", "author_id": 17974058, "author_profile": "https://Stackoverflow.com/users/17974058", "pm_score": 1, "selected": false, "text": "import numpy as np\n\n2d_matrix = np.ones((36, 36), dtype=int)\n" }, { "answer_id": 74629368, "author": "Yazar", "author_id": 14965819, "author_profile": "https://Stackoverflow.com/users/14965819", "pm_score": 0, "selected": false, "text": "matrix1 = [[1,2,3],[4,5,6]]\nmatrix2 = [[7,8,9],[10,11,12]]\nmatrix3 = [[13,14,15][16,17,18]]\n big_matrix = []\nbig_matrix.append(matrix1)\nbig_matrix.append(matrix2)\nbig_matrix.append(matrix3)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17289097/" ]
74,629,104
<p>I want to filter paths matching only some values ( &quot;chr1&quot; &quot;chr11&quot; &quot;chr16&quot; &quot;chr17&quot; &quot;chr2&quot; &quot;chr5&quot; &quot;chr6&quot; &quot;chr7&quot;) in a list of paths. However my results includes additional chr#</p> <p>This is the items i want to filter</p> <pre><code>&gt; sort(chrm_to_filter$chr) &quot;chr1&quot; &quot;chr11&quot; &quot;chr16&quot; &quot;chr17&quot; &quot;chr2&quot; &quot;chr5&quot; &quot;chr6&quot; &quot;chr7&quot; </code></pre> <p>My data looks something like this</p> <pre><code>print(path_per_chr_tabix) &quot;/path_to_file/merged_modified_per_base_calling.chr1.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr10.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr11.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr12.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr13.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr14.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr15.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr16.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr17.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr18.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr19.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr2.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr3.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr4.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr5.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr6.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr7.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr8.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chr9.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chrm.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chrX.bgz&quot; &quot;/path_to_file/merged_modified_per_base_calling.chrY.bgz&quot; </code></pre> <p>#find which data to load to save memory</p> <pre><code>subset_tabix_paths_to_load &lt;- path_per_chr_tabix[ grep( paste0(sort(chrm_to_filter$chr), collapse=&quot;|&quot;), path_per_chr_tabix) ] message(&quot;these are the files we will be workign with for now- &quot;) print(subset_tabix_paths_to_load) &quot;/paths/merged_modified_per_base_calling.chr1.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr10.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr11.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr12.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr13.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr14.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr15.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr16.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr17.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr18.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr19.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr2.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr5.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr6.bgz&quot; &quot;/paths/merged_modified_per_base_calling.chr7.bgz&quot; </code></pre>
[ { "answer_id": 74629318, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "sub which > filter_chr <- c(\"chr1\", \"chr11\", \"chr16\", \"chr17\", \"chr2\", \"chr5\", \"chr6\", \"chr7\") \n> string[which(sub(\".*\\\\.(chr\\\\d+)\\\\..*$\", \"\\\\1\", string) %in% filter_chr)]\n[1] \"/path_to_file/merged_modified_per_base_calling.chr1.bgz\" \n[2] \"/path_to_file/merged_modified_per_base_calling.chr11.bgz\"\n[3] \"/path_to_file/merged_modified_per_base_calling.chr16.bgz\"\n[4] \"/path_to_file/merged_modified_per_base_calling.chr17.bgz\"\n[5] \"/path_to_file/merged_modified_per_base_calling.chr2.bgz\" \n[6] \"/path_to_file/merged_modified_per_base_calling.chr5.bgz\" \n[7] \"/path_to_file/merged_modified_per_base_calling.chr6.bgz\" \n[8] \"/path_to_file/merged_modified_per_base_calling.chr7.bgz\" \n string c(\"/path_to_file/merged_modified_per_base_calling.chr1.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr10.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr11.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr12.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr13.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr14.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr15.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr16.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr17.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr18.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr19.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr2.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr3.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr4.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr5.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr6.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr7.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chr8.bgz\", \"/path_to_file/merged_modified_per_base_calling.chr9.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chrm.bgz\", \"/path_to_file/merged_modified_per_base_calling.chrX.bgz\", \n\"/path_to_file/merged_modified_per_base_calling.chrY.bgz\")\n" }, { "answer_id": 74629437, "author": "Abdur Rohman", "author_id": 14812170, "author_profile": "https://Stackoverflow.com/users/14812170", "pm_score": 1, "selected": false, "text": "lapply(sort(chrm_to_filter$chr), \n function(chr) {\n path_per_chr_tabix[grep(paste0(chr,\".\"),\n path_per_chr_tabix, \n fixed = TRUE)]\n })|> \n unlist()\n\n#[1] \"/path_to_file/merged_modified_per_base_calling.chr1.bgz\" \n#[2] \"/path_to_file/merged_modified_per_base_calling.chr11.bgz\"\n#[3] \"/path_to_file/merged_modified_per_base_calling.chr16.bgz\"\n#[4] \"/path_to_file/merged_modified_per_base_calling.chr17.bgz\"\n#[5] \"/path_to_file/merged_modified_per_base_calling.chr2.bgz\" \n#[6] \"/path_to_file/merged_modified_per_base_calling.chr5.bgz\" \n#[7] \"/path_to_file/merged_modified_per_base_calling.chr6.bgz\" \n#[8] \"/path_to_file/merged_modified_per_base_calling.chr7.bgz\" \n\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7846884/" ]
74,629,179
<p>I have two lists of dictionaries:</p> <pre class="lang-py prettyprint-override"><code>timing = [ {&quot;day_name&quot;: &quot;sunday&quot;}, {&quot;day_name&quot;: &quot;monday&quot;}, {&quot;day_name&quot;: &quot;tuesday&quot;}, {&quot;day_name&quot;: &quot;wednesday&quot;}, {&quot;day_name&quot;: &quot;thursday&quot;}, {&quot;day_name&quot;: &quot;friday&quot;}, {&quot;day_name&quot;: &quot;saturday&quot;}, ] hours_detail = [ {&quot;day_name&quot;: &quot;sunday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;monday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;tuesday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;wednesday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;thursday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;friday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;saturday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;saturday&quot;, &quot;peak_hour&quot;: True}, {&quot;day_name&quot;: &quot;friday&quot;, &quot;peak_hour&quot;: True}, {&quot;day_name&quot;: &quot;thursday&quot;, &quot;peak_hour&quot;: True}, ] </code></pre> <p>I want to create another list of dictionaries that looks like the one below. I'm basically combining these two lists and also rearranging according to the day name.</p> <pre class="lang-py prettyprint-override"><code>final_data_object = [ { &quot;timing&quot;: {&quot;day_name&quot;: &quot;saturday&quot;}, &quot;hour_detail&quot;: [ {&quot;day_name&quot;: &quot;saturday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;saturday&quot;, &quot;peak_hour&quot;: True}, ] }, { &quot;timing&quot;: {&quot;day_name&quot;: &quot;friday&quot;}, &quot;hour_detail&quot;: [ {&quot;day_name&quot;: &quot;friday&quot;, &quot;peak_hour&quot;: False}, {&quot;day_name&quot;: &quot;friday&quot;, &quot;peak_hour&quot;: True}, ] }, soon on... ] </code></pre> <p>I have tried this but it didn't work:</p> <pre class="lang-py prettyprint-override"><code>data = [] for time_instance in timing: obj = { &quot;timing&quot;: time_instance } for hour_instance in hour_detail: if time_instance[&quot;day_name&quot;] == hour_instance[&quot;day_name&quot;]: obj[&quot;hour_detail&quot;] = hour_instance data.append(obj) return data </code></pre>
[ { "answer_id": 74629333, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 0, "selected": false, "text": "...\ndata = []\nfor time_instance in timing:\n obj = {\"timing\": time_instance}\n # use a list to store all your pricing\n obj[\"hour_detail\"] = []\n for pricing_instance in pricing:\n if time_instance[\"day_name\"] == pricing_instance[\"day_name\"]:\n obj[\"hour_detail\"].append(pricing_instance)\n # add 'obj' after the loop\n data.append(obj)\nprint(data)\n" }, { "answer_id": 74629555, "author": "Da sil", "author_id": 20635585, "author_profile": "https://Stackoverflow.com/users/20635585", "pm_score": 1, "selected": false, "text": "pricing = hour_detail obj[\"pricing\"] for time_instance in timing: time_instance[\"day_name\"] == pricing_instance[\"day_name\"] data = []\n\nfor time_instance in timing:\n current_hour_detail = []\n for line in hours_detail:\n if line[\"day_name\"] == time_instance[\"day_name\"]:\n current_hour_detail.append(line)\n \n data.append({\n \"timing\": time_instance,\n \"pricing\": current_hour_detail\n })\n data = []\n\nfor time_instance in timing:\n current_hour_detail = [line for line in hours_detail if line[\"day_name\"] == time_instance[\"day_name\"]]\n data.append({\n \"timing\": time_instance,\n \"pricing\": current_hour_detail\n })\n hours_detail" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20286415/" ]
74,629,233
<p>if I do a POST request on Postman with my local API server it works:</p> <p><a href="https://i.stack.imgur.com/5Nfvr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Nfvr.png" alt="enter image description here" /></a></p> <p>But if I try in python with this syntax it doesn't work: <code>requests.post('http://127.0.0.1:5001/api/v0/add', data={'path': 'test'}).text</code></p> <p>it returns: <code>&quot;file argument 'path' is required\n&quot;</code></p> <p>Can you please explain me why it doesn't work?</p>
[ { "answer_id": 74629333, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 0, "selected": false, "text": "...\ndata = []\nfor time_instance in timing:\n obj = {\"timing\": time_instance}\n # use a list to store all your pricing\n obj[\"hour_detail\"] = []\n for pricing_instance in pricing:\n if time_instance[\"day_name\"] == pricing_instance[\"day_name\"]:\n obj[\"hour_detail\"].append(pricing_instance)\n # add 'obj' after the loop\n data.append(obj)\nprint(data)\n" }, { "answer_id": 74629555, "author": "Da sil", "author_id": 20635585, "author_profile": "https://Stackoverflow.com/users/20635585", "pm_score": 1, "selected": false, "text": "pricing = hour_detail obj[\"pricing\"] for time_instance in timing: time_instance[\"day_name\"] == pricing_instance[\"day_name\"] data = []\n\nfor time_instance in timing:\n current_hour_detail = []\n for line in hours_detail:\n if line[\"day_name\"] == time_instance[\"day_name\"]:\n current_hour_detail.append(line)\n \n data.append({\n \"timing\": time_instance,\n \"pricing\": current_hour_detail\n })\n data = []\n\nfor time_instance in timing:\n current_hour_detail = [line for line in hours_detail if line[\"day_name\"] == time_instance[\"day_name\"]]\n data.append({\n \"timing\": time_instance,\n \"pricing\": current_hour_detail\n })\n hours_detail" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15106435/" ]
74,629,244
<p>I am working on an API project that provides endpoints to front-end. There is a new field must added to related model that is &quot;organization&quot;.</p> <p>Firstly, this field must added to &quot;File&quot; model as a foreign key and other related files like populator, renderer and validator.</p> <p>Secondly, 'organizationId&quot; filter must added to /files/ endpoint.</p> <p>Here are my codes:</p> <p><strong>files/models.py</strong></p> <pre><code># Django from django.db.models import( CharField, ForeignKey, PROTECT, ) # Authic - Common from authic.common.models import Model # Authic - Organization from authic.organizations.models import Organization ALLOWED_EXTENSIONS = [ 'avif', 'gif', 'jpeg', 'jpg', 'mp4', 'png', 'svg', 'webm', 'webp' ] class File(Model): cloudinary_public_id = CharField( blank=True, null=True, default=None, max_length=64 ) extension = CharField( blank=True, null=True, default=None, max_length=4 ) organization = ForeignKey( Organization, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None, ) class Meta: db_table = 'files' </code></pre> <p><strong>organizations/models.py</strong></p> <pre><code># Django from django.db.models import ( BooleanField, CharField, ForeignKey, PROTECT, TextField ) # Authic - Common from authic.common.models import Model # Authic - Files from authic.files.models import File class Organization(Model): name = CharField( blank=False, null=False, default=None, max_length=256 ) url = CharField( blank=False, null=False, default=None, max_length=2048 ) theme_color = CharField( max_length=7, blank=False, null=False, default=None ) logo = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) html_title = CharField( blank=False, null=False, default=None, max_length=256 ) meta_image = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) meta_description = TextField( blank=False, null=False, default=None ) has_header_links = BooleanField( blank=False, null=False, default=None ) has_footer_links = BooleanField( blank=False, null=False, default=None ) has_footer_logo = BooleanField( blank=False, null=False, default=None ) has_filters = BooleanField( blank=False, null=False, default=None ) has_sorting = BooleanField( blank=False, null=False, default=None ) has_search = BooleanField( blank=False, null=False, default=None ) has_random_minting = BooleanField( blank=False, null=False, default=None ) random_minting_preview_name = CharField( blank=True, null=True, default=None, max_length=64 ) random_minting_preview_image_url = CharField( blank=True, null=True, default=None, max_length=2048 ) token_id_strategy = CharField( blank=True, null=True, default=None, max_length=64 ) twitter_handle = CharField( blank=False, null=False, default=None, max_length=64 ) custom_css = TextField( blank=True, null=True, default=None ) has_custom_marketplace_header = BooleanField( blank=False, null=False, default=None ) class Meta: db_table = 'organizations' </code></pre> <p><strong>collections/models.py</strong></p> <pre><code># Django from django.db.models import ( BooleanField, CharField, ForeignKey, PROTECT, TextField ) # Authic - Common from authic.common.models import Model, QuerySet # Authic - Files from authic.files.models import File # Authic - Users from authic.users.models import User # Authic - Organization from authic.organizations.models import Organization COLLECTION_CATEGORIES = ['art', 'photography', 'video'] class Collection(Model): address = CharField( blank=True, null=True, default=None, max_length=42 ) hash = CharField( blank=True, null=True, default=None, max_length=66 ) name = CharField( blank=False, null=False, default=None, max_length=64 ) symbol = CharField( blank=False, null=False, default=None, max_length=6 ) slug = CharField( blank=False, null=False, default=None, max_length=16 ) slug_lower = CharField( blank=True, null=True, default=None, max_length=16 ) description = TextField( blank=True, null=True, default=None ) url = CharField( blank=True, null=True, default=None, max_length=2048 ) discord_username = CharField( blank=True, null=True, default=None, max_length=64 ) instagram_username = CharField( blank=True, null=True, default=None, max_length=64 ) telegram_username = CharField( blank=True, null=True, default=None, max_length=64 ) # from authic.organizations.models import Organization # from B.models import X # fk = models.ForeignKey(X) # fk = models.ForeignKey(&quot;B.X&quot;) organization = ForeignKey( to='organizations.Organization', on_delete=PROTECT, related_name='+', blank=True, null=True, default=None, ) logo = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) banner = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) category = CharField( blank=False, null=False, default=None, max_length=64 ) is_public = BooleanField( blank=False, null=False, default=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.tags = QuerySet() @property def is_deletable(self): if self.address is not None: return False if self.nfts.count() &gt; 0: return False return True class Meta: db_table = 'collections' unique_together = [ ['creator', 'slug_lower'] ] </code></pre> <p><strong>Circular import error:</strong></p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\manage.py&quot;, line 12, in &lt;module&gt; main() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\manage.py&quot;, line 8, in main execute_from_command_line(sys.argv) File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\core\management\__init__.py&quot;, line 446, in execute_from_command_line utility.execute() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\core\management\__init__.py&quot;, line 420, in execute django.setup() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\__init__.py&quot;, line 24, in setup apps.populate(settings.INSTALLED_APPS) File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\apps\registry.py&quot;, line 116, in populate app_config.import_models() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\apps\config.py&quot;, line 269, in import_models self.models_module = import_module(models_module_name) File &quot;C:\Python39\lib\importlib\__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1030, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1007, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 986, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 680, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 855, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 228, in _call_with_frames_removed from authic.files.models import File File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\files\models.py&quot;, line 12, in &lt;module&gt; from authic.organizations.models import Organization File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\organizations\models.py&quot;, line 14, in &lt;module&gt; from authic.files.models import File ImportError: cannot import name 'File' from partially initialized module 'authic.files.models' (most likely due to a circular import) (C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\files\models.py) (env) PS C:\Users\eba\Desktop\AUTHIC\projects\authic-api&gt; py manage.py makemigrations Traceback (most recent call last): File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\manage.py&quot;, line 12, in &lt;module&gt; main() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\manage.py&quot;, line 8, in main execute_from_command_line(sys.argv) File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\core\management\__init__.py&quot;, line 446, in execute_from_command_line utility.execute() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\core\management\__init__.py&quot;, line 420, in execute django.setup() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\__init__.py&quot;, line 24, in setup apps.populate(settings.INSTALLED_APPS) File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\apps\registry.py&quot;, line 116, in populate app_config.import_models() File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\env\lib\site-packages\django\apps\config.py&quot;, line 269, in import_models self.models_module = import_module(models_module_name) File &quot;C:\Python39\lib\importlib\__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1030, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1007, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 986, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 680, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 855, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 228, in _call_with_frames_removed File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\collections\models.py&quot;, line 14, in &lt;module&gt; from authic.files.models import File File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\files\models.py&quot;, line 12, in &lt;module&gt; from authic.organizations.models import Organization File &quot;C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\organizations\models.py&quot;, line 14, in &lt;module&gt; from authic.files.models import File ImportError: cannot import name 'File' from partially initialized module 'authic.files.models' (most likely due to a circular import) (C:\Users\eba\Desktop\AUTHIC\projects\authic-api\authic\files\models.py) </code></pre> <p>Please considering me as a junior software developer :D Thank you from now!</p> <p>I have implemented organization field to much more files except &quot;files&quot;. I get circular import error even I tried work around methods like to=&quot;organizations.Organization&quot; etc.</p>
[ { "answer_id": 74629560, "author": "matagus", "author_id": 3219121, "author_profile": "https://Stackoverflow.com/users/3219121", "pm_score": 1, "selected": false, "text": "class MyModel(models.Model):\n foreign_key = models.ForeignKey(\n '<app name>.<model name>',\n on_delete=models.CASCADE,\n )\n logo = ForeignKey(\n \"files.File\",\n on_delete=PROTECT,\n related_name='+',\n blank=True,\n null=True,\n default=None\n )\n files File files.File" }, { "answer_id": 74639390, "author": "e.berke aydin", "author_id": 10673650, "author_profile": "https://Stackoverflow.com/users/10673650", "pm_score": 0, "selected": false, "text": "# Django\nfrom django.db.models import(\n CharField,\n ForeignKey,\n PROTECT,\n ) \n\n# Authic - Common\nfrom authic.common.models import Model\n\n# Authic - Organization\n#from authic.organizations.models import Organization --> unnecessary import\n\n\nALLOWED_EXTENSIONS = [\n 'avif', 'gif', 'jpeg', 'jpg', 'mp4', 'png', 'svg', 'webm', 'webp'\n]\n\n\nclass File(Model):\n\n cloudinary_public_id = CharField(\n blank=True,\n null=True,\n default=None,\n max_length=64\n )\n\n extension = CharField(\n blank=True,\n null=True,\n default=None,\n max_length=4\n )\n \n organization = ForeignKey(\n to=\"organizations.Organization\", # work around method(dot notation)\n on_delete=PROTECT,\n related_name='+',\n blank=True,\n null=True,\n default=None,\n )\n\n class Meta:\n db_table = 'files'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10673650/" ]
74,629,296
<p>I have a dataframe that looks like this:</p> <pre><code> plot sp value sum 1 A 1a 1 3 2 A 1b 1 3 3 A 1a 1 3 4 B 1a 2 4 5 B 1a 2 4 6 C 1b 3 9 7 C 1b 3 9 8 C 1b 3 9 </code></pre> <p>I calculated then the share of <code>sum</code> for each line and got this:</p> <pre><code> plot sp value sum share 1 A 1a 1 3 0.3 2 A 1b 1 3 0.3 3 A 1a 1 3 0.3 4 B 1a 2 4 0.5 5 B 1a 2 4 0.5 6 C 1b 3 9 0.3 7 C 1b 3 9 0.3 8 C 1b 3 9 0.3 </code></pre> <p>I want to know now what is the most common <code>sp</code> for each <code>plot</code> based on the <code>share</code>. In the case of this example I would like it to look like this:</p> <pre><code> plot sp value sum share dom.sp 1 A 1a 1 3 0.3 1a 2 A 1b 1 3 0.3 1a 3 A 1a 1 3 0.3 1a 4 B 1a 2 4 0.5 1a 5 B 1a 2 4 0.5 1a 6 C 1b 3 9 0.3 1b 7 C 1b 3 9 0.3 1b 8 C 1b 3 9 0.3 1b </code></pre>
[ { "answer_id": 74629560, "author": "matagus", "author_id": 3219121, "author_profile": "https://Stackoverflow.com/users/3219121", "pm_score": 1, "selected": false, "text": "class MyModel(models.Model):\n foreign_key = models.ForeignKey(\n '<app name>.<model name>',\n on_delete=models.CASCADE,\n )\n logo = ForeignKey(\n \"files.File\",\n on_delete=PROTECT,\n related_name='+',\n blank=True,\n null=True,\n default=None\n )\n files File files.File" }, { "answer_id": 74639390, "author": "e.berke aydin", "author_id": 10673650, "author_profile": "https://Stackoverflow.com/users/10673650", "pm_score": 0, "selected": false, "text": "# Django\nfrom django.db.models import(\n CharField,\n ForeignKey,\n PROTECT,\n ) \n\n# Authic - Common\nfrom authic.common.models import Model\n\n# Authic - Organization\n#from authic.organizations.models import Organization --> unnecessary import\n\n\nALLOWED_EXTENSIONS = [\n 'avif', 'gif', 'jpeg', 'jpg', 'mp4', 'png', 'svg', 'webm', 'webp'\n]\n\n\nclass File(Model):\n\n cloudinary_public_id = CharField(\n blank=True,\n null=True,\n default=None,\n max_length=64\n )\n\n extension = CharField(\n blank=True,\n null=True,\n default=None,\n max_length=4\n )\n \n organization = ForeignKey(\n to=\"organizations.Organization\", # work around method(dot notation)\n on_delete=PROTECT,\n related_name='+',\n blank=True,\n null=True,\n default=None,\n )\n\n class Meta:\n db_table = 'files'\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165603/" ]
74,629,297
<pre><code>&lt;span onClick={'event example 1'}&gt; content example 1 &lt;button onClick={'event example 1'}&gt; content example 2 &lt;/button&gt; &lt;/span&gt; </code></pre> <p>How can I press the button without also involving the span event? It's possible?</p>
[ { "answer_id": 74629406, "author": "Anatoliy Kostyuk", "author_id": 16215031, "author_profile": "https://Stackoverflow.com/users/16215031", "pm_score": 1, "selected": false, "text": "onClick(function(event){\n event.stopPropagation();\n console.log('button element');\n});\n" }, { "answer_id": 74629766, "author": "Roma Roma", "author_id": 17233399, "author_profile": "https://Stackoverflow.com/users/17233399", "pm_score": -1, "selected": false, "text": "// Dont forget to pass event (e).\nif (e.tagName.toLowerCase() === 'button') {\n conosole.log('CLICK');\n}" }, { "answer_id": 74631312, "author": "Nishant", "author_id": 4632239, "author_profile": "https://Stackoverflow.com/users/4632239", "pm_score": 3, "selected": true, "text": "function spanFunction(e) {\n console.log('spanFunction')\n}\n\nfunction buttonFunction(event) {\n event.stopPropagation()\n console.log('buttonFunction')\n} <span onClick=\"spanFunction(event)\">\n content example 1\n <button onClick=\"buttonFunction(event)\">\n content example 2\n </button> \n</span>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20232762/" ]
74,629,299
<p>My URL contain a number that is assigned to a particular item so it might be 1, 2, ..., 999 and so on.</p> <p>An example: <a href="https://www.test.com/items.889218.html" rel="nofollow noreferrer">https://www.test.com/items.889218.html</a></p> <p>I want to make assertion like this:</p> <pre><code>cy.url().should('contain', '/items.').and('have', 'number') </code></pre> <p>I tried e.g.:</p> <pre><code>cy.url().invoke('text').should('match', /^[0-9]*$/) </code></pre> <p>or</p> <pre><code>cy.location().should((loc) =&gt; { expect(loc.pathname).to.contain(/^[0-9]*$/); }); </code></pre> <p>also to provide this kind of path:</p> <pre><code>&quot;/items\.+[0-9]+.html/&quot; </code></pre> <p>But both examples do not work. Any idea how to handle this kind of case?</p>
[ { "answer_id": 74629418, "author": "Rohan Büchner", "author_id": 1105314, "author_profile": "https://Stackoverflow.com/users/1105314", "pm_score": 0, "selected": false, "text": "cy.location().should((loc) => {\n expect(loc).to.match(/https:\\/\\/www\\.test\\.com\\/items\\/(\\d+).html/)\n})\n\n// or\n\ncy.url().should('match', /https:\\/\\/www\\.test\\.com\\/items\\/(\\d+).html/)\n $ .html .html $ https://www.test.com/items/[number].html\n\n ^^^^\n (https:\\/\\/www\\.test\\.com\\/items\\/)(\\d)+\n $ /https:\\/\\/www\\.test\\.com\\/items\\/([0-9]+)/\n . items.number (\\/|\\.)+ \\ . cy.url().should('match', /https:\\/\\/www\\.test\\.com\\/items(\\/|\\.)+[0-9]+.html/)\n https://www.test.com/items.8655.html\nhttps://www.test.com/items/8655.html\nhttps://www.test.com/items/.8655.html\n" }, { "answer_id": 74629723, "author": "agoff", "author_id": 11625850, "author_profile": "https://Stackoverflow.com/users/11625850", "pm_score": -1, "selected": false, "text": "cy.url cy.url().should('match', /https:\\/\\/www\\.test\\.com\\/items\\/(\\d*)\\.html/)\n" }, { "answer_id": 74647396, "author": "Ine Wilmann", "author_id": 20659725, "author_profile": "https://Stackoverflow.com/users/20659725", "pm_score": 2, "selected": false, "text": "https://www.test.com/items.889218.html cy.url().should('match', /https:\\/\\/www\\.test\\.com\\/items.[0-9]+\\.html/)\n cy.url()\n .should('satisfy', (url) => url.startsWith('https://www.test.com/items.'))\n .and('satisfy', (url) => url.endsWith('.html'))\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19777975/" ]
74,629,301
<p>In vscode, I have a python linter setup which helps me identify if there are any errors in my code, by underlining the error prone section with red swiggly lines. I can see the error message, if I hover over that section. Is there a keyboard shortcut which can show the error message, without actually requiring me to hover.</p> <p>Attaching a screenshot for reference.</p> <p><a href="https://i.stack.imgur.com/lGVbt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lGVbt.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74629492, "author": "myf", "author_id": 540955, "author_profile": "https://Stackoverflow.com/users/540955", "pm_score": 2, "selected": true, "text": "editor.action.showHover Ctrl K Ctrl I" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547986/" ]
74,629,308
<p>I'm new to programming and hope you can help me out with this little number comparison game that I'm trying to build.</p> <p>I have two functions. The first function creates the playing field in HTML via a button press. One of the elements created on the playing field is an input field where the player can enter their guess. In the second function I compare two numbers - the one that was generated randomly and the one that was input by the player. Unfortunately I can't access the number which was entered by the player.</p> <p>Maybe someone has got an idea. Thank you very much.</p> <p>This is what the functions look like:</p> <pre><code>function startGame(){ (...) const inputField = document.createElement(&quot;input&quot;); inputField.setAttribute(&quot;type&quot;, &quot;number&quot;); inputField.setAttribute(&quot;id&quot;, &quot;guess&quot;); document.getElementById(&quot;guess&quot;).appendChild(inputField); } </code></pre> <pre><code>function compareInput(){ let inputValue = document.getElementById(&quot;guess&quot;).value; (...) } </code></pre>
[ { "answer_id": 74629492, "author": "myf", "author_id": 540955, "author_profile": "https://Stackoverflow.com/users/540955", "pm_score": 2, "selected": true, "text": "editor.action.showHover Ctrl K Ctrl I" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20643670/" ]
74,629,310
<p>I would like hide and show elements in different breakpoints. For example I could use v-if=&quot;$vuetify.breakpoint.md&quot; in the <a href="https://vuetifyjs.com/en/" rel="nofollow noreferrer">vuetify</a>. How i can do this in the <a href="https://element-plus.org/en-US/" rel="nofollow noreferrer">element-plus</a>?</p> <p>I can use classes but is there any other solution?</p> <blockquote> <p>hidden-xs-only - hide when on extra small viewports only</p> </blockquote>
[ { "answer_id": 74629492, "author": "myf", "author_id": 540955, "author_profile": "https://Stackoverflow.com/users/540955", "pm_score": 2, "selected": true, "text": "editor.action.showHover Ctrl K Ctrl I" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6711997/" ]
74,629,382
<p>I want to mock a resttemplate.exchange() method but it is not getting mocked . It is throwing <code>NoClassDefFoundError</code></p> <p>Here's the class I want to mock:</p> <pre><code>public class userHelper { /* */ public getUserResponse(userPayload){ String url = &quot;abc/def&quot;; HttpHeaders headers = new HttpHeaders(); headers.setAccept(...); ... ... HttpEntity&lt;userPayload&gt; httpEntity = new HttpEntity&lt;~&gt;(userpayload,headers); RestTtemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add(testInterceptor.Builder.of().setHttpRequestContext(false).setPrintResponseBody(false).build()); ResponseEntity&lt;userPayload&gt; response = restTemplate.exchange(url,HttpMethod.POST,httpEntity,UserPayload.class); ... ... ... } } </code></pre> <p>In my test class i have mocked the resttemplate but it is not working Test class:</p> <pre><code>@ExtendWIth(MockitoExtension.class) public class userHelperTest(){ @Mock RestTemplate restTemplate; @Test getUserResponseTest(){ ... ... when(restTemplate.exchange(ArgumentMatchers.anyString(), ArgumentMatchers.eq(HttpMethod.POST, ArgumentMatchers,any(HttpEntity.class), ArgumentMatchers.eq(UserPayload.class))).thenReturn(response); }} </code></pre> <p>Please suggest how to resolve this. Thanks in advance!</p>
[ { "answer_id": 74629592, "author": "grekier", "author_id": 1540177, "author_profile": "https://Stackoverflow.com/users/1540177", "pm_score": 1, "selected": false, "text": "RestTemplate @SpringBootApplication\npublic class YourAppName {\n @Bean\n public RestTemplate restTemplate() {\n return new RestTemplate\n }\n...\n}\n\n @Service\npublic class UserHelper {\n private RestTemplate restTemplate;\n\n public UserHelper(RestTemplate restTemplate) {\n this.restTemplate = restTemplate\n }\n...\n// your methods but remove RetTemplate from them\n}\n @SpringBootTest\npublic class UserHelperTest{\n @Mock\n RestTemplate restTemplate;\n\n @Autowired // or create it in a @BeforeEach method\n UserHelper instanceToTest;\n\n // your test with mocking should now work here \n}\n" }, { "answer_id": 74629914, "author": "ga__ts", "author_id": 11726419, "author_profile": "https://Stackoverflow.com/users/11726419", "pm_score": 0, "selected": false, "text": "public class userHelper {\n\n @Autowired\n RestTemplate restTemplate;\n\n ...\n\n RestTemplate restTemplate = new RestTemplate();\n\n ...\n @ExtendWIth(MockitoExtension.class)\npublic class userHelperTest(){\n\n @Mock\n RestTemplate restTemplate;\n\n @InjectMocks\n UserHelper userHelper = new UserHelper();\n\n @Test \n getUserResponseTest(){\n\n ...\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11031894/" ]
74,629,401
<p>list of stowwords:</p> <p>stop_w = [&quot;in&quot;, &quot;&amp;&quot;, &quot;the&quot;, &quot;|&quot;, &quot;and&quot;, &quot;is&quot;, &quot;of&quot;, &quot;a&quot;, &quot;an&quot;, &quot;as&quot;, &quot;for&quot;, &quot;was&quot;]</p> <p>df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>words</th> <th>frequency</th> </tr> </thead> <tbody> <tr> <td>the company</td> <td>10</td> </tr> <tr> <td>green energy</td> <td>9</td> </tr> <tr> <td>founded in</td> <td>8</td> </tr> <tr> <td>gases for</td> <td>8</td> </tr> <tr> <td>electricity</td> <td>5</td> </tr> </tbody> </table> </div> <p>I would like to remove entire row if it contains ANY of given stopwords, in this example output should be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>words</th> <th>frequency</th> </tr> </thead> <tbody> <tr> <td>green energy</td> <td>9</td> </tr> <tr> <td>electricity</td> <td>5</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17277677/" ]
74,629,447
<p>I'm using Django and after committing new edits I need to restart my server to see them. But every time after restart with <code>python manage.py runserver</code> my server is not loading I need to use another port to see my website</p> <p>I`m using Pycharm and Debian terminal</p> <p>I tried to reboot my pc and it helped but only for 1 time, I mean I can start my server by a default port but can't restart him again with the same port</p>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646427/" ]
74,629,458
<p>l recently learned to make a navigation menu so I ventured on my own to make a dropdown. I did this all on my own and it seems I am weak in targeting the style properties. So I need some help.</p> <p><a href="https://i.stack.imgur.com/24rn5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/24rn5.png" alt="enter image description here" /></a></p> <p>Here's the code</p> <blockquote> <pre><code>&lt;style&gt; body { margin: 0; } .menu { width: fit-content; float: left; } .under { width: 100px; float: left; background-color: #242a38; position: absolute; z-index: 1; } nav ul { list-style-type: none; margin: 0; padding: 0; } nav ul li.border { text-align: center; border-bottom: 1px solid white; margin: 5px 5px; } nav ul li a { color: #ffffff; text-decoration: none; font-family: Candara; font-size: 14px; display: block; padding: 10px; margin: 5px 0px; z-index: 10; } nav ul li a:hover { background-color: #4e596f; transition: 1s; } .hello { float: left; } .text { position: absolute; left: 700px; top: 145px; font-family: segoe script; color: #ffffffc4; text-decoration: #1eacc5 underline; font-size: 50px; transform: rotate(1.5deg) } #full-span { width: 100%; height: 100%; position: fixed; } .stretch { width: 100%; height: 100%; } nav ul ul{ width: 100%; background: #242a38; display: none; position: absolute; left: 100%; top: 0; z-index: 999; } ul li:hover &gt; ul{ display: block; } ul ul li { display: block; } nav ul ul a{ padding: 10px 5px; margin: 5px 5px 11px 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;menu&quot;&gt; &lt;div class=&quot;under&quot;&gt; &lt;nav&gt; &lt;ul&gt; &lt;li class=&quot;border&quot;&gt;&lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;border&quot;&gt;&lt;a href=&quot;#&quot;&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;border&quot;&gt;&lt;a href=&quot;#&quot;&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;border&quot;&gt;&lt;a href=&quot;#&quot;&gt;Contact&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Local 1&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Okkk&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Not Ok&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Yes Ok&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Local&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Local&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Okkk&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Not Ok&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Yes Ok&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class=&quot;border&quot;&gt;&lt;a href=&quot;#&quot;&gt;Sign in&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> </blockquote> <p>I want the dropdown to appear next to the tile I am hovering over but it goes to the top.</p> <p>At first the dropdown expanded right below overlapping the original menu so I tried:</p> <p><code>position: absolute;</code><br /> <code>left: 100%;</code><br /> <code>top: 0;</code></p> <p>Now it doesn't overlap but instead sticks to the top</p>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20433010/" ]
74,629,460
<p>I have an Access DB which contains this Fields:</p> <ul> <li>ID (autonumber)</li> <li>IDArr (numeric)</li> <li>Importo (Decimal)</li> <li>Pv (numeric)</li> <li>Closed (boolean)</li> </ul> <p>I want to set the <code>Closed</code> field to true if sum of Importo is = 0 grouping by <code>IDArr</code> field and I have tried with this query:</p> <pre><code>UPDATE ln SET closed = true WHERE Val(idarr) = EXISTS (SELECT idarr FROM ln WHERE Val(pv) &gt; 0 AND chiuso = false GROUP BY idarrivo HAVING SUM(importo) = 0 ORDER BY idarr) </code></pre> <p>Result is 0 fields. However, if I run this query separately like this:</p> <pre><code>SELECT idarr FROM ln WHERE Val(pv) &gt; 0 AND chiuso = false GROUP BY idarrivo HAVING SUM(importo) = 0 ORDER BY idarr </code></pre> <p>I obtain a correct result showing a set of record. Who can help me? Thanks in advance.</p>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5132058/" ]
74,629,505
<p>I have files that are uploaded into an onprem folder daily, from there I have a pipeline pulling it to a blob storage container (input), from there I have another pipeline from blob (input) to blob (output), here is were the dataflow is, between those two blobs. Finally, I have output linked to sql. However, I want the blob to blob pipeline to pull only the file that was uploaded that day and run through the dataflow. The way I have it setup, every time the pipeline runs, it doubles my files. I've attached images below</p> <p>[![Blob to Blob Pipeline][1]][1]</p> <p>Please let me know if there is anything else that would make this more clear [1]: <a href="https://i.stack.imgur.com/24Uky.png" rel="nofollow noreferrer">https://i.stack.imgur.com/24Uky.png</a></p>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20053349/" ]
74,629,510
<p><em>Write a program that fills an array of 10 elements with random numbers from 1 to 10, and then swaps the first element with the second, the third with the fourth, and so on. Display the original and transformed array</em></p> <p>Here is my solution, but Python doesn't want to sort the array and it stays the same:</p> <pre><code>from random import randint numbers = [] for i in range(10): numbers.append(randint(1, 10)) print(numbers) a = 0 for a in range(10): numbers[-1], numbers[i] = numbers[i], numbers[-1] a = a + 2 print(numbers) </code></pre> <p>I have tried replacing elements with a loop by <code>numbers[a] = numbers[a+1]</code> , But I kept getting the error:</p> <pre><code>IndexError: list index out of range </code></pre>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20645812/" ]
74,629,566
<p>Hi I'm making a website but I'm having two problems</p> <ol> <li>My HTML file doesn't see my CSS file. My Html file is Website/html/index.html and my CSS file is Website/css/index.css</li> <li>Even though i do <code>text-align: center;</code>(CSS file line:22) my list doesn't become straight line</li> </ol> <pre><code>My Html code </code></pre> <pre><code>&lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;KK Kiralama&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;/css/index.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;header class=&quot;kk-header&quot;&gt; &lt;div class=&quot;kk-container&quot;&gt; &lt;nav class=&quot;kk_nav&quot;&gt; &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Ana Sayfa&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;Hakkimizda.html&quot;&gt;Hakkımızda&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;Araclarımız.html&quot;&gt;Araçlarımız&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;Iletisim.html&quot;&gt;İletişim&lt;/a&gt;&lt;/li&gt; &lt;li style=&quot;float:right&quot;&gt;&lt;a href=&quot;Giris.html&quot;&gt;Giriş&lt;/a&gt;&lt;/li&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/header&gt; </code></pre> <pre><code>My Css code </code></pre> <pre><code>@import url('https://fonts.googleapis.com/css2?family=Montserrat&amp;display=swap'); *{font-family: 'Montserrat', sans-serif; margin: 0; padding: 0; box-sizing: border-box;} html{ font-size: 60%; } .kk-header{ width: 100%; background-color:#191970; } .kk-nav{ overflow: hidden; background-color: #191970; } .kk-nav a{ float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; } </code></pre> <pre><code> Thanks for any help! Also, I'm open to any advice on making this code more smooth. </code></pre>
[ { "answer_id": 74629508, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 2, "selected": true, "text": "| or \\ stop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", \"for\", \"was\"]\ndf.loc[~df['words'].str.contains('|'.join(stop_w))]\n words frequency\n1 green energy 9\n4 electricity 5\n" }, { "answer_id": 74629534, "author": "Paweł Pietraszko", "author_id": 19391219, "author_profile": "https://Stackoverflow.com/users/19391219", "pm_score": 0, "selected": false, "text": "sub_df = df[df.words.str not in stop_w]\n idx = df[df.words.str in stop_w].index\ndf.drop(idx)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14880159/" ]
74,629,567
<p>I have a dictionary.</p> <pre><code>prices = {'n': 99, 'a': 99, 'c': 147} </code></pre> <p>using map () I need to receive new dictionary :</p> <pre><code>def formula(value): value = value -value * 0.05 return value </code></pre> <pre><code>new_prices = dict(map(formula, prices.values())) </code></pre> <p>but it doesn't work</p> <pre><code>TypeError: cannot convert dictionary update sequence element #0 to a sequence </code></pre> <p>solving my code using <code>map()</code>:</p> <pre><code>new_prices = {'n': 94.05, 'a': 94.05, 'c': 139.65} </code></pre>
[ { "answer_id": 74629622, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "map() lambda new_prices = dict(map(lambda item: (item[0], formula(item[1])), prices.items()))\n {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" }, { "answer_id": 74629633, "author": "Timur Shtatland", "author_id": 967621, "author_profile": "https://Stackoverflow.com/users/967621", "pm_score": 2, "selected": false, "text": "new_prices = {k: formula(prices[k]) for k in prices}\nprint(new_prices)\n# {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" }, { "answer_id": 74629666, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 3, "selected": false, "text": "zip map new_prices = dict(zip(prices, map(formula, prices.values())))\n" }, { "answer_id": 74629672, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": -1, "selected": false, "text": "map map def print_results(map_object):\n for i in map_object:\n print(i)\n\ndef formula(value):\n return value * 0.95 # one-liner\n\nm = map(formula, prices.values())\n\nprint_results(m)\n\n# output\n94.05\n94.05\n139.65\n" }, { "answer_id": 74629875, "author": "Stroehli", "author_id": 3635024, "author_profile": "https://Stackoverflow.com/users/3635024", "pm_score": 0, "selected": false, "text": " prices = {'n': 99, 'a': 99, 'c': 147}\n \n \n def formula(value):\n value = value -value * 0.05\n return value\n\n #Using a dict comprehension and .items() [giving you key value tuples] instead of map()\n new_prices = {k: formula(v) for k, v in prices.items()}\n \n print(new_prices)\n # {'n': 94.05, 'a': 94.05, 'c': 139.65}\n #Define the formula with a key value pair (tuple) as input and return value\n def f_items(items):\n value = items[1] - items[1] * 0.05\n return items[0], value\n \n \n new_prices = dict(map(f_items, prices.items()))\n \n print(new_prices)\n # {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646670/" ]
74,629,602
<p>I want to build a button, when I click it for the first time it shows for example an Ad, when clicked again it doesn't show the ad but the content. Here is what I tried:</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>const btn = document.querySelector('.btn'); const ad = document.querySelector('.ad'); const cnt = document.querySelector('.cnt'); let ads = false; btn.addEventListener('click', () =&gt; { ads = true ad.style.display = 'block' if (ads) { ad.style.display = 'none'; cnt.style.display = 'block'; })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;button class="btn"&gt;Click Me&lt;/button&gt; &lt;h1 style="display: none" class="ad"&gt;Ad&lt;/h1&gt; &lt;h1 style="display: none" class="cnt"&gt;Content&lt;/h1&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74629622, "author": "JayPeerachai", "author_id": 12135518, "author_profile": "https://Stackoverflow.com/users/12135518", "pm_score": 1, "selected": false, "text": "map() lambda new_prices = dict(map(lambda item: (item[0], formula(item[1])), prices.items()))\n {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" }, { "answer_id": 74629633, "author": "Timur Shtatland", "author_id": 967621, "author_profile": "https://Stackoverflow.com/users/967621", "pm_score": 2, "selected": false, "text": "new_prices = {k: formula(prices[k]) for k in prices}\nprint(new_prices)\n# {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" }, { "answer_id": 74629666, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 3, "selected": false, "text": "zip map new_prices = dict(zip(prices, map(formula, prices.values())))\n" }, { "answer_id": 74629672, "author": "Vini", "author_id": 6927944, "author_profile": "https://Stackoverflow.com/users/6927944", "pm_score": -1, "selected": false, "text": "map map def print_results(map_object):\n for i in map_object:\n print(i)\n\ndef formula(value):\n return value * 0.95 # one-liner\n\nm = map(formula, prices.values())\n\nprint_results(m)\n\n# output\n94.05\n94.05\n139.65\n" }, { "answer_id": 74629875, "author": "Stroehli", "author_id": 3635024, "author_profile": "https://Stackoverflow.com/users/3635024", "pm_score": 0, "selected": false, "text": " prices = {'n': 99, 'a': 99, 'c': 147}\n \n \n def formula(value):\n value = value -value * 0.05\n return value\n\n #Using a dict comprehension and .items() [giving you key value tuples] instead of map()\n new_prices = {k: formula(v) for k, v in prices.items()}\n \n print(new_prices)\n # {'n': 94.05, 'a': 94.05, 'c': 139.65}\n #Define the formula with a key value pair (tuple) as input and return value\n def f_items(items):\n value = items[1] - items[1] * 0.05\n return items[0], value\n \n \n new_prices = dict(map(f_items, prices.items()))\n \n print(new_prices)\n # {'n': 94.05, 'a': 94.05, 'c': 139.65}\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19241748/" ]
74,629,609
<p>I am using a custom hook from 3rd party library in my React project:</p> <pre><code>import { useProductData } from '@third/prod-data-component'; const ProductRow: React.FC&lt;MyProduct&gt; = ({ product }) =&gt; { // using the custom hook here const productData = useProductData(); }) </code></pre> <p>The signature of that hook function is:</p> <pre><code>export declare const useProductData: () =&gt; string | undefined; </code></pre> <p>In my jest test, I would like to mock the returned value of the hook, I tried:</p> <pre><code>it('should show correct product data', ()=&gt;{ jest.mock('@third/prod-data-component', () =&gt; { return { useProductData: jest.fn(()=&gt;'foo')} }); ... ... }) </code></pre> <p>When I run test, the above mock doesn't take any effect.</p> <p>How to mock the return value of custom hook that is from a 3rd party library?</p> <p>==== UPDATE ====</p> <p>I also tried this:</p> <pre><code>jest.mock('@third/prod-data-component', () =&gt; { const lib = jest.requireActual('@third/prod-data-component'); return {...lib, useProductData: () =&gt; 'foo'} }); </code></pre> <p>But does't work either.</p>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842225/" ]
74,629,613
<p>Can you help me identifying what type of wildcard I need to use to find a certain email address in my properties field?</p> <p>I know that the email I'm looking for is in the slot number 2 How can I find the email address without knowing the slot number? can I use a [*] instead of a [2]?</p> <p>Here's my query:</p> <pre><code>resources | where type == 'microsoft.insights/actiongroups' | where properties[&quot;enabled&quot;] in~ ('true') | where properties['emailReceivers'][2]['emailAddress'] == &quot;DevSecOps@pato.com&quot; | project id,name,resourceGroup,subscriptionId,properties,location | order by tolower(tostring(name)) asc </code></pre> <p>I have the following data in my properties field:</p> <pre><code>{ &quot;enabled&quot;: true, &quot;automationRunbookReceivers&quot;: [], &quot;azureFunctionReceivers&quot;: [], &quot;azureAppPushReceivers&quot;: [], &quot;logicAppReceivers&quot;: [], &quot;eventHubReceivers&quot;: [], &quot;webhookReceivers&quot;: [], &quot;armRoleReceivers&quot;: [], &quot;emailReceivers&quot;: [ { &quot;name&quot;: &quot;TED&quot;, &quot;status&quot;: &quot;Enabled&quot;, &quot;useCommonAlertSchema&quot;: true, &quot;emailAddress&quot;: &quot;tedtechnicalengineeringdesign@pato.com&quot; }, { &quot;name&quot;: &quot;SevenOfNine&quot;, &quot;status&quot;: &quot;Enabled&quot;, &quot;useCommonAlertSchema&quot;: true, &quot;emailAddress&quot;: &quot;sevenofnine@pato.com&quot; }, { &quot;name&quot;: &quot;PEAT&quot;, &quot;status&quot;: &quot;Enabled&quot;, &quot;useCommonAlertSchema&quot;: true, &quot;emailAddress&quot;: &quot;DevSecOps@pato.com&quot; } ], &quot;voiceReceivers&quot;: [], &quot;groupShortName&quot;: &quot;eng-mon&quot;, &quot;itsmReceivers&quot;: [], &quot;smsReceivers&quot;: [] } </code></pre> <p>I've tried using [*] instead of [2] but it didn't work.</p>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16595335/" ]
74,629,624
<p>i've been trying to create a way to generate config files for a help tool that i've been making. i would like to have the code create a config file in a specific default location that is dependant on the current user on which the code is ran.</p> <p>this is my basic setup for the code i've been trying to find a way to have username be the variable system_user however when trying this i get a unicode error</p> <pre><code>import configparser import os system_user = os.getlogin() file_path_input = input('filepath input ') strength = input('strenght score ') dexterity = input('dexterity score ') constitution = input('constitution score ') intelligence = input('intelligence score ') wisdom = input('wisdom score ') charisma = input('charisma score ') testconfig = configparser.ConfigParser() testconfig.add_section('stats') testconfig.set('stats', 'strength', strength) testconfig.set('stats', 'dexterity', dexterity) testconfig.set('stats', 'constitution', constitution) testconfig.set('stats', 'intelligence', intelligence) testconfig.set('stats', 'wisdom', wisdom) testconfig.set('stats', 'charisma', charisma) with open(C:\Users\username\Documents\5e_helper\character cofig, 'w') as configfile: testconfig.write(configfile) </code></pre> <p>i've been trying to find a way to have username be the variable system_user however when trying</p> <pre><code>with open(r'C:\Users\' + system_user + '\Documents\5e_helper\character cofig', 'w') as configfile: testconfig.write(configfile) </code></pre> <p>i get a syntax error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-2: malformed \N character escape</p>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646731/" ]
74,629,638
<p>I want to subtract serial dates that are associated with the same value in another column. I am trying to find the time between order dates for each customer. Say, I have a dataframe:</p> <pre><code>customerid &lt;- c(&quot;A1&quot;, &quot;A1&quot;, &quot;A2&quot;, &quot;A2&quot;, &quot;A3&quot;, &quot;A3&quot;, &quot;A3&quot;, &quot;A4&quot;) orderdate &lt;- c(&quot;2018-09-14&quot;, &quot;2020-08-20&quot;, &quot;2018-09-15&quot;, &quot;2019-08-25&quot;, &quot;2018-09-16&quot;, &quot;2020-08-21&quot;,&quot;2017-09-12&quot;, &quot;2018-08-10&quot;) df &lt;- data.frame(customerid, orderdate) </code></pre> <p>My desired output is creation of a new column called time_lapse:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>customerid</th> <th>orderdate</th> <th>time_lapse</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>2018-09-14</td> <td>706</td> </tr> <tr> <td>A1</td> <td>2020-08-20</td> <td></td> </tr> <tr> <td>A2</td> <td>2018-09-15</td> <td>1</td> </tr> <tr> <td>A2</td> <td>2018-09-16</td> <td></td> </tr> <tr> <td>A3</td> <td>2017-09-12</td> <td>712</td> </tr> <tr> <td>A3</td> <td>2019-08-25</td> <td>362</td> </tr> <tr> <td>A3</td> <td>2020-08-21</td> <td></td> </tr> <tr> <td>A4</td> <td>2018-08-10</td> <td></td> </tr> </tbody> </table> </div> <p>So far, I have this code but I am having trouble with how to proceed from here. Would a loop be reasonable here? But I also have a large dataset &gt;50,000 customer ids. Thanks!</p> <pre><code> time_lapse &lt;- df[df$customerid %in% df$customerid[duplicated(df$customerid)],] #Subset of only customerids that have &gt;1 occurrence time_lapse &lt;- time_lapse %&gt;% group_by(customerid) %&gt;% mutate(number_occurrences = 1:n()) #counts no. times a customerid repeats </code></pre>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5901298/" ]
74,629,674
<p>The issue I'm facing is that the sound is not running in a loop, the whole sound is executed once, it does not repeat.</p> <p>So basically, I have used this method:</p> <pre><code>#include &lt;Windows.h&gt; #include &lt;thread&gt; #include &lt;iostream&gt; void play_music() { PlaySoundA(&quot;sound.wav&quot;, NULL, SND_FILENAME | SND_LOOP); } int main(){ std::thread t(play_music); //code t.join(); } </code></pre>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17162747/" ]
74,629,684
<p>Using PowerShell, can I obtain the DNS hostname of a virtual machine if I only have access to the Hyper-V host running the VM?</p> <p>I know I can get the IP of the VM and perform a reverse DNS lookup but I do not have access to the network/DNS servers that service this VM.</p> <p>I also do not have credentials for the VMs</p> <p>I feel like this information is accessible via integration services but have failed to find anything useful.</p>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10041179/" ]
74,629,703
<p>I have table that looks like this</p> <pre><code> WO | PS | C ---------------- 12 | 1 | a 12 | 2 | b 12 | 2 | b 12 | 2 | c 13 | 1 | a </code></pre> <p>I want to find values from WO column where PS has value 1 and C value a AND PS has value 2 and C has value b. So on one column I need to have multiple conditions and I need to find it within WO column. If there is no value that matches two four conditions I don't want to have column WO included.</p> <p>I tried using condition:</p> <pre><code>WHERE PS = 1 AND C = a AND PS = 2 AND C = b </code></pre> <p>but it does not work and does not have connection to WO column as mentioned above.</p> <p>Edit:</p> <p>I need to find WO which has (PS = 1 AND C = a) and at the same time it also has rows where (PS = 2 and C = b).</p> <p>The result should be:</p> <pre><code> WO | PS | C ---------------- 12 | 1 | a 12 | 2 | b 12 | 2 | b </code></pre> <p>If either of rows: (PS = 1 and C = a) or (PS = 2 and C = b) does not exist then nothing should be returned.</p>
[ { "answer_id": 74629753, "author": "vashykator", "author_id": 8979230, "author_profile": "https://Stackoverflow.com/users/8979230", "pm_score": 0, "selected": false, "text": "import moduleMock from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n moduleMock.useProductData.mockReturnValue(...)\n })\n})\n jest.mocked import prod_data_component_module from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component')\n\ndescribe('Your test case scenario', () => {\n const mock = jest.mocked(prod_data_component_module, { shallow: true })\n\n it('Your test here', async () => {\n mock.useProductData.mockReturnValue('...')\n\n // test logic here\n })\n})\n mock jest.MockedFn<T>" }, { "answer_id": 74631645, "author": "SAHIL", "author_id": 16209302, "author_profile": "https://Stackoverflow.com/users/16209302", "pm_score": 2, "selected": true, "text": "import {useProductData} from '@third/prod-data-component'\n\njest.mock('@third/prod-data-component');\n\n(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})\n\ndescribe('test scenario', () => {\n it('should show correct product data', () => {\n // your assertions\n })\n})\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9650071/" ]
74,629,709
<p>Due to the <code>html markup</code> I had to use <code>flex-basis</code> to improve style, so that <code>p</code> element start from the same column as the <code>title/headline</code>, and problem was fixed using <code>flex-basis</code>. <br> But as you can see in the screenshot, the image takes too much height and width.<br> I tried to fix it applying <code>max-height</code> and <code>max-width</code>, but it breaks my style.<br> And my goal is to remove that space so that i can control the space between the <code>content</code> and <code>button</code>.</p> <p><strong>Note</strong>: I can't use <code>css grid</code>. I know, it would be easier, but there are problems on ios using <code>css grid</code>.</p> <p><a href="https://i.stack.imgur.com/aZF19.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aZF19.png" alt="enter image description here" /></a></p> <p>Here is <a href="https://codesandbox.io/s/affectionate-dirac-3vwsnm?file=/style.css:0-693" rel="nofollow noreferrer">the sandbox link</a> and code snippet below</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: flex; flex-wrap: wrap; background-color: grey; column-gap: 15px; padding: 20px; } .content { display: flex; flex-direction: column; flex-wrap: wrap; } .logo-image { flex-basis: 100%; object-fit: contain; object-position: top; padding-top: 10px; order: 1; align-self: flex-start; } .headline { color: white; order: 2; padding-left: 10px; } .text { color: white; font-size: 16px; margin-bottom: 20px; order: 3; } .btn { display: flex; width: 100%; } button { align-items: center; background-color: black; color: white; flex: 0 0 90%; justify-content: center; margin: 0; } body { margin: 0; padding: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="content"&gt; &lt;h4 class="headline"&gt; Block Title &lt;/h4&gt; &lt;img src="https://i.stack.imgur.com/Pm2og.png" width="50px" class="logo-image" alt="img" /&gt; &lt;p class="text"&gt; Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente aliquid sit, cupiditate &lt;/p&gt; &lt;/div&gt; &lt;div class="btn"&gt; &lt;button&gt;link&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>]<a href="https://codesandbox.io/s/affectionate-dirac-3vwsnm?file=/style.css" rel="nofollow noreferrer">3</a> and code</p>
[ { "answer_id": 74629982, "author": "Kameron", "author_id": 16496357, "author_profile": "https://Stackoverflow.com/users/16496357", "pm_score": 1, "selected": false, "text": "flex-basis .logo-image h4.headline img .wrapper display: flex; img { max-width: 100%;) .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n column-gap: 15px;\n padding: 20px;\n}\n\n.content {\n display: flex;\n}\n\n.logo-image {\n object-fit: contain;\n object-position: top;\n padding-top: 10px;\n align-self: flex-start;\n}\n\n.headline {\n color: white;\n padding-left: 10px;\n}\n\n.text {\n color: white;\n font-size: 16px;\n padding-left: 10px;\n}\n\n.btn {\n display: flex;\n width: 100%;\n}\n\nbutton {\n align-items: center;\n background-color: black;\n color: white;\n flex: 0 0 90%;\n justify-content: center;\n margin: 0;\n}\n\nbody {\n margin: 0;\n padding: 0;\n}\n\n.wrapper {\n display: flex;\n flex-direction: column;\n}\n\nimg {\n max-width: 100%;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" />\n <link rel=\"stylesheet\" href=\"style.css\" />\n <title>Static Template</title>\n</head>\n\n<body>\n <div class=\"container\">\n <div class=\"content\">\n <img src=\"https://i.stack.imgur.com/Pm2og.png\" width=\"50px\" class=\"logo-image\" alt=\"img\" />\n <div class=\"wrapper\">\n <h4 class=\"headline\">\n Block Title\n </h4>\n <div>\n <p class=\"text\">\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente aliquid sit, cupiditate\n </p>\n </div>\n </div>\n </div>\n <div class=\"btn\">\n <button>link</button>\n </div>\n </div>\n</body>\n\n</html>" }, { "answer_id": 74630071, "author": "Abhinav Gunishetty", "author_id": 12177406, "author_profile": "https://Stackoverflow.com/users/12177406", "pm_score": 1, "selected": true, "text": "position:absolute flex-box .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n column-gap: 15px;\n padding: 20px;\n}\n\n.content {\n position: relative;\n padding-left: 4rem;\n}\n\n.logo-image {\n position: absolute;\n left: 0;\n top: 0;\n}\n\n.headline {\n color: white;\n order: 2;\n margin:0 0 0.5rem;\n}\n\n.text {\n color: white;\n font-size: 16px;\n margin:0 0 10px;\n order: 3;\n}\n\n.btn {\n display: flex;\n width: 100%;\n}\n\nbutton {\n align-items: center;\n background-color: black;\n color: white;\n flex: 0 0 90%;\n justify-content: center;\n margin: 0;\n}\n\nbody {\n margin: 0;\n padding: 0;\n} <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" />\n <link rel=\"stylesheet\" href=\"style.css\" />\n <title>Static Template</title>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"content\">\n <h4 class=\"headline\">\n Block Title\n </h4>\n <img src=\"https://i.stack.imgur.com/Pm2og.png\" width=\"50px\" class=\"logo-image\" alt=\"img\" />\n <p class=\"text\">\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente\n aliquid sit, cupiditate\n </p>\n </div>\n <div class=\"btn\">\n <button>link</button>\n </div>\n </div>\n </body>\n</html>" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12971921/" ]
74,629,721
<p>I have JSON object like this</p> <pre><code>{ &quot;codemap&quot;:{ &quot;codeOfItem1&quot;:&quot;titleOfItem1&quot;, &quot;codeOfItem2&quot;:&quot;titleOfItem2&quot;, &quot;codeOfItem3&quot;:&quot;titleOfItem3&quot;, &quot;codeOfItem4&quot;:&quot;titleOfItem4&quot; }, &quot;items&quot;:{ &quot;titleOfItem1&quot;:{ &quot;attribute1&quot;:&quot;value1&quot;, &quot;atttribute2&quot;:{ &quot;subattr1&quot;:&quot;value1_of_subattr1_for_item1&quot;, &quot;subattr2&quot;:&quot;value1_of_subattr2_for_item1&quot; } }, &quot;titleOfItem2&quot;:{ &quot;attribute1&quot;:&quot;value2&quot;, &quot;atttribute2&quot;:{ &quot;subattr1&quot;:&quot;value1_of_subattr1_for_item2&quot;, &quot;subattr2&quot;:&quot;value1_of_subattr2_for_item2&quot; } }, &quot;titleOfItem3&quot;:{ &quot;attribute1&quot;:&quot;value2&quot;, &quot;atttribute2&quot;:{ &quot;subattr1&quot;:&quot;value1_of_subattr1_for_item3&quot;, &quot;subattr2&quot;:&quot;value1_of_subattr2_for_item3&quot; } }, &quot;titleOfItem4&quot;:{ &quot;attribute1&quot;:&quot;value2&quot;, &quot;atttribute2&quot;:{ &quot;subattr1&quot;:&quot;value1_of_subattr1_for_item4&quot;, &quot;subattr2&quot;:&quot;value1_of_subattr2_for_item4&quot; } } } } </code></pre> <p>How to parse it using GSON in Kotlin ? (Problem is that strings like <code>titleOfItemXXX</code> is both values in <code>codemap</code> map and key names in <code>items</code> map</p> <p>I don't really like idea to go fully manual way like in <a href="https://stackoverflow.com/questions/46804969/how-to-parse-this-json-with-no-object-name">How to parse this Json with no object name</a></p> <p>Update: I don't want to get scheme like this (this is from Kotlin-to-JSON Android Studio Plugin)</p> <pre><code>import com.google.gson.annotations.SerializedName data class x1( @SerializedName(&quot;codemap&quot;) val codemap: Codemap, @SerializedName(&quot;items&quot;) val items: Items ) { data class Codemap( @SerializedName(&quot;codeOfItem1&quot;) val codeOfItem1: String, // titleOfItem1 @SerializedName(&quot;codeOfItem2&quot;) val codeOfItem2: String, // titleOfItem2 @SerializedName(&quot;codeOfItem3&quot;) val codeOfItem3: String, // titleOfItem3 @SerializedName(&quot;codeOfItem4&quot;) val codeOfItem4: String // titleOfItem4 ) data class Items( @SerializedName(&quot;titleOfItem1&quot;) val titleOfItem1: TitleOfItem1, @SerializedName(&quot;titleOfItem2&quot;) val titleOfItem2: TitleOfItem2, @SerializedName(&quot;titleOfItem3&quot;) val titleOfItem3: TitleOfItem3, @SerializedName(&quot;titleOfItem4&quot;) val titleOfItem4: TitleOfItem4 ) { data class TitleOfItem1( @SerializedName(&quot;attribute1&quot;) val attribute1: String, // value1 @SerializedName(&quot;atttribute2&quot;) val atttribute2: Atttribute2 ) { data class Atttribute2( @SerializedName(&quot;subattr1&quot;) val subattr1: String, // value1_of_subattr1_for_item1 @SerializedName(&quot;subattr2&quot;) val subattr2: String // value1_of_subattr2_for_item1 ) } data class TitleOfItem2( @SerializedName(&quot;attribute1&quot;) val attribute1: String, // value2 @SerializedName(&quot;atttribute2&quot;) val atttribute2: Atttribute2 ) { data class Atttribute2( @SerializedName(&quot;subattr1&quot;) val subattr1: String, // value1_of_subattr1_for_item2 @SerializedName(&quot;subattr2&quot;) val subattr2: String // value1_of_subattr2_for_item2 ) } data class TitleOfItem3( @SerializedName(&quot;attribute1&quot;) val attribute1: String, // value2 @SerializedName(&quot;atttribute2&quot;) val atttribute2: Atttribute2 ) { data class Atttribute2( @SerializedName(&quot;subattr1&quot;) val subattr1: String, // value1_of_subattr1_for_item3 @SerializedName(&quot;subattr2&quot;) val subattr2: String // value1_of_subattr2_for_item3 ) } data class TitleOfItem4( @SerializedName(&quot;attribute1&quot;) val attribute1: String, // value2 @SerializedName(&quot;atttribute2&quot;) val atttribute2: Atttribute2 ) { data class Atttribute2( @SerializedName(&quot;subattr1&quot;) val subattr1: String, // value1_of_subattr1_for_item4 @SerializedName(&quot;subattr2&quot;) val subattr2: String // value1_of_subattr2_for_item4 ) } } } </code></pre> <p>because I don't really known how much items I will have and which names they will use in production.</p>
[ { "answer_id": 74635181, "author": "James Lan", "author_id": 1988349, "author_profile": "https://Stackoverflow.com/users/1988349", "pm_score": 1, "selected": false, "text": "Map data class Schema(val codemap: Map<String, String>, val items: Map<String, Item>) {\n data class Item(val attribute1: String, val atttribute2: Attr2) {\n data class Attr2(val subattr1: String, val subattr2: String)\n }\n}\n\nfun gsonDemo() {\n val json = \"\"\"\n {\n \"codemap\":{\n \"codeOfItem1\":\"titleOfItem1\",\n \"codeOfItem2\":\"titleOfItem2\",\n \"codeOfItem3\":\"titleOfItem3\",\n \"codeOfItem4\":\"titleOfItem4\"\n },\n \"items\":{\n \"titleOfItem1\":{\n \"attribute1\":\"value1\",\n \"atttribute2\":{\n \"subattr1\":\"value1_of_subattr1_for_item1\",\n \"subattr2\":\"value1_of_subattr2_for_item1\"\n }\n },\n \"titleOfItem2\":{\n \"attribute1\":\"value2\",\n \"atttribute2\":{\n \"subattr1\":\"value1_of_subattr1_for_item2\",\n \"subattr2\":\"value1_of_subattr2_for_item2\"\n }\n },\n \"titleOfItem3\":{\n \"attribute1\":\"value2\",\n \"atttribute2\":{\n \"subattr1\":\"value1_of_subattr1_for_item3\",\n \"subattr2\":\"value1_of_subattr2_for_item3\"\n }\n },\n \"titleOfItem4\":{\n \"attribute1\":\"value2\",\n \"atttribute2\":{\n \"subattr1\":\"value1_of_subattr1_for_item4\",\n \"subattr2\":\"value1_of_subattr2_for_item4\"\n }\n }\n }\n }\n \"\"\".trimIndent()\n\n val obj = Gson().fromJson(json, Schema::class.java)\n println(obj.items[obj.codemap[\"codeOfItem3\"]]?.atttribute2?.subattr1) // print value1_of_subattr1_for_item3\n}\n null" }, { "answer_id": 74652846, "author": "Tauri", "author_id": 1063214, "author_profile": "https://Stackoverflow.com/users/1063214", "pm_score": 0, "selected": false, "text": "data class TopLevel (\n @SerializedName(\"codemap\")\n val codemap: Map<String, String>,\n @SerializedName(\"items\")\n val items: Map<String, Item>\n)\n\ndata class Item (\n @SerializedName(\"attribute1\")\n val attribute1: Attribute1,\n @SerializedName(\"attribute2\")\n val attribute2: Attribute2\n)\n\ndata class Attribute2 (\n @SerializedName(\"subattr1\")\n val subattr1: String,\n @SerializedName(\"subattr2\")\n val subattr1: String\n)\n\nenum class Attribute1 {\n @SerializedName(\"DarkSide\")\n DarkSide,\n @SerializedName(\"LightSide\")\n LightSide\n}\n\n\nvar gson: Gson = Gson()\n\nval str=... //string with source JSON\nval result = gson.fromJson(str, TopLeve::class.java)\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063214/" ]
74,629,724
<p>I'm trying to set a Generic type that will accept 2 parameters and return a function.<br /> First parameter - The type of the single parameter of the returned function<br /> Second Parameter - need to get true if dev wants the returned function parameter to be required.</p> <p>Somehow it's just not working The Val is inferred to string but it still thinks it's not a string</p> <p>Any help will be appreciated</p> <p><a href="https://www.typescriptlang.org/play?#code/PTAEFkEMDsBNIC4HsBOBPUBeUCUFcBTUAM1VBQIEc8BLC2UAB0hUgFsCECUBnAKAIAPRqgQ40jIgDVIAGxrwENJNABieaAGMlKgDwAVLKA0BraEgDu0ADSgAkjyhxEqDNlPmrAPix9QumVkjBydFV1AhLjgeHHwiAH5QQwAuJNAAH2M4AmIaaAJYLwAKADc5VMCASiwfXEIM0B5cPIBzAG4%20Ts0VJpwCJoq5BURlNQ1tUd0mlFbbOoIfbFK5aswfAG8-ck48FGhQMtkOgF8Ovi4mooByESRGK8rOkAhINAAjIgQACyJuilAkMQcD9QDQeDx6m88GILAQ6LBZBgaGJIJpNARGAgYjAMAgJERAUwWOxONx7FdZEFmOCcEhQQhOhcEEUAKxsx5MorzDn9ZnQPCUnmXdbHR5AA" rel="nofollow noreferrer">Link to playground</a></p> <pre><code>// Mandatory = true for required parameters export type ValidationFunction&lt;T = unknown, IsMandatory = unknown&gt; = &lt;Val = IsMandatory extends true ? T : T | undefined&gt;(val: Val) =&gt; true | string; const test: ValidationFunction&lt;string, true&gt; = (val) =&gt; { // error! // ~~~~ // Type 'Val' is not assignable to type 'string | true'. return val; }; test('poop') // Maybe the core of the issue but weirdly it accepts // any type of parameter I'll pass to it test(555) test(true) test(null) test({}) </code></pre>
[ { "answer_id": 74629984, "author": "AbsoluteZero", "author_id": 20539156, "author_profile": "https://Stackoverflow.com/users/20539156", "pm_score": 0, "selected": false, "text": "ValidationFunction string | true export type ValidationFunction<T = unknown, IsMandatory = unknown> =\n <Val = IsMandatory extends true ? T : T | undefined>(val: Val) => T;\n test('poop') // no warnings\n\n\ntest(555) // warning \ntest(true) // warning\ntest(null) // warning\ntest({}) // warning\ntest([]) // warning\n // Mandatory = true for required parameters\nexport type ValidationFunction<T = unknown, IsMandatory = unknown> =\n (val: IsMandatory extends true ? T : T | undefined) => true | string;\n\n\nconst test: ValidationFunction<string, true> = (val) => {\n return val;\n};\n\ntest('poop')\n\n// Maybe the core of the issue but weirdly it accepts any type of parameter I'll pass to it\n\ntest(555)\ntest(true)\ntest(null)\ntest({})\n\n" }, { "answer_id": 74630597, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 2, "selected": true, "text": "ValidationFunction<T, M> Val IsMandatory extends true ? T : T | undefined Val test Val string export type ValidationFunction<T = unknown, IsMandatory = unknown> =\n <Val extends IsMandatory extends true ? T : T | undefined>(val: Val) => true | string;\n// ^^^^^^^ <-- constraint, not default\n\nconst test: ValidationFunction<string, true> = (val) => {\n return val;\n}; // okay\n\ntest('') // okay\ntest(555) // error\ntest(true) // error\ntest(null) // error\ntest({}) // error\n Val export type ValidationFunction<T = unknown, IsMandatory = unknown> =\n (val: IsMandatory extends true ? T : T | undefined) => true | string;\n\n\nconst test: ValidationFunction<string, true> = (val) => {\n return val;\n}; // okay\n\ntest('') // okay\ntest(555) // error\ntest(true) // error\ntest(null) // error\ntest({}) // error\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19528122/" ]
74,629,746
<p>command I ran was <code>nodetool tablehistograms &lt;keyspace&gt; &lt;table&gt;</code> The bug was No SSTables exists, unable to calculate 'Partition Size' and 'Cell Count' percentiles</p> <p>I tried to calculate partition size for better selections on partition keys, but nodetool command did not work fine as the partition size is not provided with this error</p> <p>SSTables are immutable as far as concerned, and I do not know if I should (and how to) create SSTables based on existed ones?</p> <p>Experts, please come solve this problem, really appreciate it.</p> <p>Best</p>
[ { "answer_id": 74633823, "author": "Paul", "author_id": 10914049, "author_profile": "https://Stackoverflow.com/users/10914049", "pm_score": 1, "selected": false, "text": "dsbulk count --stats.modes partitions --stats.numPartitions <n> -k myKeyspace -t myTable\n" }, { "answer_id": 74651839, "author": "Erick Ramirez", "author_id": 4269535, "author_profile": "https://Stackoverflow.com/users/4269535", "pm_score": 0, "selected": false, "text": "nodetool tablehistograms data/ cassandra" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20088868/" ]
74,629,748
<p>I'm trying to create a form with a submit button, but the code i created, keeps returning an error.</p> <p>I tried this code: `</p> <pre><code>function SubmitCard() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var crdSht = spreadsheet.getSheetByName(&quot;Cards&quot;); var data [[ crdSht.getRange(&quot;A2&quot;).getValue(), crdSht.getRange(&quot;B2&quot;).getValue(), crdSht.getRange(&quot;C2&quot;).getValue(), crdSht.getRange(&quot;D2&quot;).getValue(), crdSht.getRange(&quot;E2&quot;).getValue(), crdSht.getRange(&quot;F2&quot;).getValue() ]]; crdSht.getRange(crdSht.getLastRow()+1,1,1,6).setValues(data); } </code></pre> <p>` I was expecting the code to insert my data values in the row under the last row with data.</p>
[ { "answer_id": 74633823, "author": "Paul", "author_id": 10914049, "author_profile": "https://Stackoverflow.com/users/10914049", "pm_score": 1, "selected": false, "text": "dsbulk count --stats.modes partitions --stats.numPartitions <n> -k myKeyspace -t myTable\n" }, { "answer_id": 74651839, "author": "Erick Ramirez", "author_id": 4269535, "author_profile": "https://Stackoverflow.com/users/4269535", "pm_score": 0, "selected": false, "text": "nodetool tablehistograms data/ cassandra" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12287618/" ]
74,629,752
<p>Im in the process of trying to recreate a piece of python code for a simple calculator in C++,</p> <p>in python i have the following piece of code thats located in a while loop</p> <pre><code>func = str(input(&quot;which function: add, sub, div, mult&quot;)) if func in (&quot;add&quot;, &quot;sub&quot;, &quot;div&quot;, &quot;mult&quot;): #secondery if statment else: print(&quot;error&quot;) </code></pre> <p>how would i go about writing if func in (&quot;add&quot;, &quot;sub&quot;, &quot;div&quot;, &quot;mult&quot;): in C++?</p> <p>i have tried</p> <pre><code>if (func in {&quot;add&quot;, &quot;sub&quot;, &quot;div&quot;, &quot;mult&quot;}){ //secondery if statment else: std::cout &lt;&lt; &quot;error \n&quot;; } </code></pre> <p>but this doesn't work.</p>
[ { "answer_id": 74629897, "author": "Marek R", "author_id": 1387438, "author_profile": "https://Stackoverflow.com/users/1387438", "pm_score": 2, "selected": false, "text": "template<typename T, typename... Args>\n[[nodiscard]] constexpr bool isAnyOf(T&& a, Args&&... args) noexcept\n{\n return ((a == args) || ...);\n}\n char * std::any_of" }, { "answer_id": 74629961, "author": "R1D3R175", "author_id": 14508616, "author_profile": "https://Stackoverflow.com/users/14508616", "pm_score": 1, "selected": true, "text": "#include <iostream> // std::cout, std::cin\n#include <string>\n#include <array> // one of the many STL containers\n#include <algorithm> // std::find\n\nint main() {\n const std::array<std::string, 4> functions = { \n \"add\",\n \"sub\",\n \"div\",\n \"mult\"\n };\n\n std::string user_input;\n std::cout << \"which function: add, sub, div, mult? \";\n std::cin >> user_input;\n\n if (std::find(functions.begin(), functions.end(), user_input) != functions.end()) {\n std::cout << \"found\" << std::endl;\n } else {\n std::cout << \"not found\" << std::endl;\n }\n}\n in std::find()" }, { "answer_id": 74634263, "author": "Ammar Tamimi", "author_id": 20498352, "author_profile": "https://Stackoverflow.com/users/20498352", "pm_score": 0, "selected": false, "text": "std::string str;\nstd::cin >> str; \nif(str == \"add\" || str == \"sub\" || str == \"mult\" || str == \"sub\")\n{\n std::cout << \" do good stuff ..\";\n} else std::cout << \"error\";\n" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20349653/" ]
74,629,837
<p>as mentioned in nebula documentation here :</p> <p><a href="https://docs.nebula-graph.io/1.2.0/manual-EN/2.query-language/1.data-types/data-types/" rel="nofollow noreferrer">https://docs.nebula-graph.io/1.2.0/manual-EN/2.query-language/1.data-types/data-types/</a></p> <p><a href="https://i.stack.imgur.com/2DES6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2DES6.png" alt="nebula documentation create vertex datetime timestamp record in graph database" /></a></p> <p>nebula&gt; INSERT VERTEX school(name, create_time) VALUES hash(&quot;new&quot;):(&quot;new&quot;, &quot;1985-10-01 08:00:00&quot;)</p> <p>error is:</p> <blockquote> <p>-1005:Storage Error: The data type does not meet the requirements. Use the correct type of data.</p> </blockquote> <p>and this:</p> <blockquote> <p>-1005:Wrong vertex id type: hash(&quot;new&quot;)</p> </blockquote>
[ { "answer_id": 74629985, "author": "saber tabatabaee yazdi", "author_id": 308578, "author_profile": "https://Stackoverflow.com/users/308578", "pm_score": 0, "selected": false, "text": "match (v:school) return v,now() limit 10;\n" }, { "answer_id": 74638584, "author": "Wey Gu", "author_id": 1402404, "author_profile": "https://Stackoverflow.com/users/1402404", "pm_score": 2, "selected": true, "text": "CREATE SPACE [IF NOT EXISTS] <graph_space_name> (\n [partition_num = <partition_number>,]\n [replica_factor = <replica_number>,]\n vid_type = {FIXED_STRING(<N>) | INT[64]}\n )\n [COMMENT = '<comment>'];\n CREATE SPACE IF NOT EXISTS my_space_2 (partition_num=15, replica_factor=1, vid_type=FIXED_STRING(30));\n \"new\"" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308578/" ]
74,629,850
<p>I have classic bill of material table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>PartId</th> <th>SubPartId</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>2</td> </tr> <tr> <td>1</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>5</td> <td>8</td> </tr> <tr> <td>2</td> <td>8</td> <td>13</td> </tr> </tbody> </table> </div> <p>When given <code>PartId</code>, I want only those <code>SubPartId</code> that are not Parts (<code>SubPartId</code> is not present in <code>PartId</code> column), they are materials, so they are lowest in hierarchy. If given <code>PartId</code> = 1, I want query to return 3, 5, 8, because those parts don't have any subparts, not sure how to do it.</p> <p>Tryed simple recursion:</p> <pre><code>with BOM as ( SELECT parts.PartId, parts.SubPartId FROM Parts parts WHERE parts.PartId = 1 UNION ALL SELECT components.PartId, components.SubPartId FROM Parts components JOIN BOM B on B.SubPartId = components.SubPartId ) </code></pre> <p>From this query I get 2, 3, 5, 8, but I don't want 2 because it is not material.</p>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19977678/" ]
74,629,870
<p>I'm struggling to find a way to create a dictionary with 2 columns as key identifier. I can't use just one cause it wouldnt be unique. The nameRng and operRng of a row would be unique.</p> <p>Here's some code</p> <pre><code> Dim LstRw As Long, Rng As Range, cell As Range, cell2 As Range Dim Dict As Object Set nameRng = Range(Range(&quot;A2&quot;), Range(&quot;A2&quot;).End(xlDown)) Set operRng = Range(Range(&quot;B2&quot;), Range(&quot;B2&quot;).End(xlDown)) Set saisieRng = Range(Range(&quot;C2&quot;), Range(&quot;C2&quot;).End(xlDown)) Set Dict = CreateObject(&quot;Scripting.Dictionary&quot;) LstRw = Cells(Rows.Count, &quot;A&quot;).End(xlUp).Row For Each cell In nameRng For Each cell2 In operRng Dict.Add cell.Value, cell2.Value Next Next </code></pre> <p>Running this, I get an error &quot;Key already exist&quot; but I don't understand why.</p> <p>Thanks in advance !</p>
[ { "answer_id": 74630233, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 2, "selected": false, "text": "DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT)\nINSERT INTO @parts (PartID, SubPartID, Quantity) VALUES\n(1, 2, 2), (1, 3, 4),\n(1, 5, 8), (2, 8, 13)\n SELECT p.SubPartID\n FROM @parts p\n LEFT OUTER JOIN @parts p2\n ON p.SubPartID = p2.PartID\n WHERE p2.PartID IS NULL\n SubPartID\n---------\n3\n5\n8\n DECLARE @parts TABLE (PartID INT, SubPartID INT, Quantity INT, Name NVARCHAR(20))\nINSERT INTO @parts (PartID, SubPartID, Quantity, name) VALUES\n(1, NULL, 1, 'Bicyle'), (2, 1, 1, 'Wheel'), (5, 2, 1, 'Rim'), (6, 2, 1, 'Tyre'), (7, 5, 1, 'Spoke'),\n(8, 6, 1, 'Rubber'), (9, 6, 1, 'Valve'), (10, NULL, 1, 'Cake'), (11, 10, 3, 'Flour'), (12, 10, 1, 'Milk'),\n(13, 10, 2, 'Egg'),(14, 13, 1, 'Yoke'), (15, 13, 1, 'White'),(16, 10, 3, 'Sugar'), (17, 10, 1, 'Berries'),\n(18, 17, 1, 'Raspberry'),(19, 17, 1, 'Strawberry'), (20, 17, 1, 'Blueberry')\n ;WITH cte AS (\nSELECT PartID AS GlobalParentPartID, PartID, SubPartID, Quantity, Name\n FROM @parts\n UNION ALL\nSELECT GlobalParentPartID, r.PartID, r.SubPartID, r.Quantity, r.Name\n FROM cte a\n INNER JOIN @parts r\n ON a.PartID = r.SubPartID\n)\n\nSELECT i.GlobalParentPartID, i.Name, p.Name, p.SubPartID, p.Quantity\n FROM cte i\n INNER JOIN @parts p\n ON i.GlobalParentPartID = p.PartID\n AND i.PartID <> p.PartID\n LEFT OUTER JOIN @parts p2\n ON i.PartID = p2.SubPartID\n WHERE p2.PartID IS NULL\n ORDER BY i.GlobalParentPartID\n \nGlobalParentPartID Name Name SubPartID Quantity\n------------------------------------------------------------\n1 Rubber Bicyle NULL 1\n1 Valve Bicyle NULL 1\n1 Spoke Bicyle NULL 1\n2 Rubber Wheel 1 1\n2 Valve Wheel 1 1\n2 Spoke Wheel 1 1\n5 Spoke Rim 2 1\n6 Rubber Tyre 2 1\n6 Valve Tyre 2 1\n10 Flour Cake NULL 1\n10 Milk Cake NULL 1\n10 Sugar Cake NULL 1\n10 Raspberry Cake NULL 1\n10 Strawberry Cake NULL 1\n10 Blueberry Cake NULL 1\n10 Yoke Cake NULL 1\n10 White Cake NULL 1\n13 Yoke Egg 10 2\n13 White Egg 10 2\n17 Raspberry Berries 10 1\n17 Strawberry Berries 10 1\n17 Blueberry Berries 10 1\n" }, { "answer_id": 74631934, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 0, "selected": false, "text": "not exists select *\nfrom @parts as child\nwhere not exists (\n select PartID\n from @parts as parent\n where parent.PartID = child.SubPartID\n);\n group by distinct" } ]
2022/11/30
[ "https://Stackoverflow.com/questions/74629870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15424097/" ]