qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,286,429
<p>I'm testing when stack smashing is detected, and I noticed I don't get stack smashing is detected when I write a null character after a char buffer.</p> <p>In this example, I write characters into a char buffer, and then write the null character at the end (with f-stack-protector):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char buf[8]; char c; printf(&quot;Enter a string: &quot;); int i; for (i = 0; (c = getchar()) != '\n'; i++) buf[i] = c; buf[i] = '\0'; printf(&quot;string = [%s]\n&quot;, buf); return 0; } </code></pre> <p>I noticed that writing 9 characters will give me <code>*** stack smashing detected ***: terminated</code> as expected, but writing 8 characters does not. If I input 8 characters in this example, wouldn't the null character be written after the buffer and smash the stack?</p> <p>I tried replacing the null character to writing some other character like 'A' and I will also get stack smashing detected. Is the null character special in this regard, or is this behaviour unexpected?</p>
[ { "answer_id": 74287087, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "getchar()" }, { "answer_id": 74289395, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 2, "selected": true, "text": "-fstack-protector" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15551501/" ]
74,286,430
<p>As there is constant update with firebase plugins I run into cocopod errors, what exactly is this error and how do I resolve this ? I have had one before and resolved it but with newer packages and older plugins this error keeps popping up.</p> <pre><code>Analyzing dependencies Pre-downloading: `GeoFire` from `https://github.com/jesussmile/geofire-objc.git` firebase_auth: Using Firebase SDK version '10.0.0' defined in 'firebase_core' firebase_core: Using Firebase SDK version '10.0.0' defined in 'firebase_core' firebase_database: Using Firebase SDK version '10.0.0' defined in 'firebase_core' firebase_messaging: Using Firebase SDK version '10.0.0' defined in 'firebase_core' firebase_storage: Using Firebase SDK version '10.0.0' defined in 'firebase_core' [!] CocoaPods could not find compatible versions for pod &quot;Firebase/Database&quot;: In Podfile: GeoFire (from `https://github.com/jesussmile/geofire-objc.git`) was resolved to 4.3.0, which depends on GeoFire/Database (= 4.3.0) was resolved to 4.3.0, which depends on Firebase/Database (= 9.3.0) firebase_database (from `.symlinks/plugins/firebase_database/ios`) was resolved to 10.0.3, which depends on Firebase/Database (= 10.0.0) </code></pre>
[ { "answer_id": 74287087, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "getchar()" }, { "answer_id": 74289395, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 2, "selected": true, "text": "-fstack-protector" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17523373/" ]
74,286,462
<p>I just need to generate the numbers and store in the column C in the blank spaces</p> <p>Data</p> <pre><code> A B C 12525 1FWE23 14654 14654 24798 24798 38945 38945 46456 46485 8 AD545 45346 9 A5D66 A5D66 10 </code></pre> <p>Expected</p> <pre><code> A B C 12525 1FWE23 0 14654 14654 1 24798 24798 2 38945 38945 3 46456 46485 8 AD545 45346 9 A5D66 A5D66 10 </code></pre>
[ { "answer_id": 74286542, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "range" }, { "answer_id": 74287018, "author": "Jahirul islam", "author_id": 7386944, "author_profile": "https://Stackoverflow.com/users/7386944", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndata = {\n \"A\": [12525, 14654, 24798, 24798, 13231],\n \"B\": [12525, 24798, 24798, 24798, 21231],\n \"C\": ['', '', 2, '', 4]\n}\ndf = pd.DataFrame(data)\ndef null_check(row):\n if row['C'] != '':\n return row['C']\n return row.name\ndf['C'] = df.apply(null_check, axis=1)\nprint(df)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19580067/" ]
74,286,513
<p>I have spent i a lot of time trying to write a VBA-code to automate my work, but can't figure out how. I hope someone in here can help me.</p> <p>The goal is to insert pictures in a tabel in a PowerPoint from a Folder based on values in Excel.</p> <p>I have <strong>5</strong> different pictures (.png) located in a folder on my device. The cell values in Excel goes from <strong>1</strong> to <strong>5</strong>.</p> <p>Depending on the cell value, I would like one of the 5 pictures to be inserted in a table in Powerpoint.</p> <p>E.g.: If excel-value = 2 then insert picture2 in powerpoint-table.</p> <p>I hope the above make sense, and I hope someone can help me.</p> <p>I have tried the following:</p> <pre><code>Sub ESG_Globes() Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual ' Define PPT objects Dim oPPT As PowerPoint.Presentation Dim appPPT As PowerPoint.Application Dim oWS As Excel.Worksheet Dim fileNameString As String Dim boolUploadToIntranet As Boolean Dim cells As Range Dim s14 As Integer, s15 As Integer, s13 As Integer Dim ESG1, ESG2, ESG3, ESG4, ESG5 As String Dim ImageBox, ImageBox2 As PowerPoint.Shape With oPPT.Slides(8) For k = 4 To 22 'Globes PNG Location ESG1 = &quot;S:\S8RENTE\Credit &amp; Equity Research\ESG\Grafik\Glober (PNG)\SustainabilityRating_Low.png&quot; ESG2 = &quot;S:\S8RENTE\Credit &amp; Equity Research\ESG\Grafik\Glober (PNG)\SustainabilityRating_BelowAverage.png&quot; ESG3 = &quot;S:\S8RENTE\Credit &amp; Equity Research\ESG\Grafik\Glober (PNG)\SustainabilityRating_Average.png&quot; ESG4 = &quot;S:\S8RENTE\Credit &amp; Equity Research\ESG\Grafik\Glober (PNG)\SustainabilityRating_AboveAverage.png&quot; ESG5 = &quot;S:\S8RENTE\Credit &amp; Equity Research\ESG\Grafik\Glober (PNG)\SustainabilityRating_High.png&quot; ' Check if file is open - if not, open it fOpen = IsFileOpen(&quot;S:\S8RENTE\Aktieanalyse\Vaerktoejer\Aktieoverblik\Aktieoverblik - Sektoropdeling\Aktieoverblik_PPT - Sektor.pptx&quot;) If Not fOpen Then Set appPPT = CreateObject(class:=&quot;PowerPoint.Application&quot;) Set oPPT = appPPT.Presentations.Open(&quot;S:\S8RENTE\Aktieanalyse\Vaerktoejer\Aktieoverblik\Aktieoverblik - Sektoropdeling\Aktieoverblik_PPT - Sektor.pptx&quot;) Else Set appPPT = GetObject(class:=&quot;PowerPoint.Application&quot;) Set oPPT = appPPT.Presentations(&quot;Udkast til Aktieoverblik.pptx&quot;) End If Application.ScreenUpdating = False Application.EnableEvents = False Set oWS = ActiveWorkbook.Worksheets(&quot;PPT DATA&quot;) Set owb = ActiveWorkbook If oWS.cells(k, 37) = &quot;1&quot; Then Set wdPic = .Cell(k, 37).Range.InlineShapes.AddPicture(filename:=ESG1, _ LinkToFile:=False, SaveWithDocument:=True) If oWS.cells(k, 37) = &quot;2&quot; Then Set wdPic = .Cell(k, 37).Range.InlineShapes.AddPicture(filename:=ESG2, _ LinkToFile:=False, SaveWithDocument:=True) If oWS.cells(k, 37) = &quot;3&quot; Then Set wdPic = .Cell(k, 37).Range.InlineShapes.AddPicture(filename:=ESG3, _ LinkToFile:=False, SaveWithDocument:=True) If oWS.cells(k, 37) = &quot;4&quot; Then Set wdPic = .Cell(k, 37).Range.InlineShapes.AddPicture(filename:=ESG4, _ LinkToFile:=False, SaveWithDocument:=True) If oWS.cells(k, 37) = &quot;5&quot; Then Set wdPic = .Cell(k, 37).Range.InlineShapes.AddPicture(filename:=ESG5, _ LinkToFile:=False, SaveWithDocument:=True) End If wdPic.Height = 0.3 * 28.34646 wdPic.Width = 0.3 * 28.34646 Set wdPic2 = wdPic.ConvertToShape wdPic2.Left = CentimetersToPoints(4 - (y * 0.3)) y = y + 1 End With End Sub </code></pre> <p>I know the above is probably completely wrong but I am lost :/</p>
[ { "answer_id": 74286542, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "range" }, { "answer_id": 74287018, "author": "Jahirul islam", "author_id": 7386944, "author_profile": "https://Stackoverflow.com/users/7386944", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndata = {\n \"A\": [12525, 14654, 24798, 24798, 13231],\n \"B\": [12525, 24798, 24798, 24798, 21231],\n \"C\": ['', '', 2, '', 4]\n}\ndf = pd.DataFrame(data)\ndef null_check(row):\n if row['C'] != '':\n return row['C']\n return row.name\ndf['C'] = df.apply(null_check, axis=1)\nprint(df)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395620/" ]
74,286,548
<p>i'm currently struggling with an SQL task.</p> <p>I have an select Statement like this</p> <p><code>SELECT * FROM data dt LEFT JOIN payment pm ON pm.month = dt.month AND pm.persID = dt.persID</code></p> <p>Two Colums of data table are relevant for the condition (data.department, pm.payout).</p> <p>Now i need all Information grouped by department where payout = 0.</p> <p>I tried first to simply group by department</p> <p><code>SELECT * FROM data dt LEFT JOIN payment pm ON pm.month = dt.month AND pm.persID = dt.persID GROUP BY dt.department</code></p> <p>But this error occurs: Selected non-aggregate values must be part of the associated group.</p> <p>Then i tried it with first checking if the payout is 0.</p> <p><code>SELECT * FROM data dt LEFT JOIN payment pm ON pm.month = dt.month AND pm.persID = dt.persID WHERE pm.payout = 0</code></p>
[ { "answer_id": 74286542, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "range" }, { "answer_id": 74287018, "author": "Jahirul islam", "author_id": 7386944, "author_profile": "https://Stackoverflow.com/users/7386944", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndata = {\n \"A\": [12525, 14654, 24798, 24798, 13231],\n \"B\": [12525, 24798, 24798, 24798, 21231],\n \"C\": ['', '', 2, '', 4]\n}\ndf = pd.DataFrame(data)\ndef null_check(row):\n if row['C'] != '':\n return row['C']\n return row.name\ndf['C'] = df.apply(null_check, axis=1)\nprint(df)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395564/" ]
74,286,566
<p>I created a custom menu on the UI of google sheets with different buttons like I show in the code bellow:</p> <pre><code>function onOpen(e) { SpreadsheetApp.getUi() // Or DocumentApp, SlidesApp, or FormApp. .createMenu('WOZTELL') .addItem('FAQ LVL 1', 'InstallFAQ1') .addToUi(); } </code></pre> <p>My question if I can get the value &quot;FAQ LVL 1&quot; when someones presses the button.</p>
[ { "answer_id": 74286542, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "range" }, { "answer_id": 74287018, "author": "Jahirul islam", "author_id": 7386944, "author_profile": "https://Stackoverflow.com/users/7386944", "pm_score": 2, "selected": true, "text": "import pandas as pd\ndata = {\n \"A\": [12525, 14654, 24798, 24798, 13231],\n \"B\": [12525, 24798, 24798, 24798, 21231],\n \"C\": ['', '', 2, '', 4]\n}\ndf = pd.DataFrame(data)\ndef null_check(row):\n if row['C'] != '':\n return row['C']\n return row.name\ndf['C'] = df.apply(null_check, axis=1)\nprint(df)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19615712/" ]
74,286,575
<p>I have CSS which I am adding a gradient to an Image. It is adding the gradient successfully but the background Image is repeating. I want to set it to cover the whole body and center it and have a no-repeat properties. How can I achieve this? I tried adding no repeat after the URL but it is taking no effects. Below is my code;</p> <pre><code> &lt;style&gt; body { background: linear-gradient(0deg, rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.50)), url(&quot;images/dms.jpg&quot;); } &lt;/style&gt; </code></pre> <p>I want to achieve something like the below code. I have the Image as a background which is not repeating and is centered.</p> <pre><code> &lt;style&gt; body { background-image: url(&quot;images/dms.jpg&quot;); background-size: cover; background-repeat: no-repeat; background-position: center center; } &lt;/style&gt; </code></pre>
[ { "answer_id": 74286816, "author": "dante velli", "author_id": 19338216, "author_profile": "https://Stackoverflow.com/users/19338216", "pm_score": 0, "selected": false, "text": "height" }, { "answer_id": 74286970, "author": "codeninja", "author_id": 15269321, "author_profile": "https://Stackoverflow.com/users/15269321", "pm_score": -1, "selected": false, "text": "!important" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15269321/" ]
74,286,582
<p>I need a route parameter in a VueJS componente. For example the <strong>42</strong> in <code>example.de/page/42</code>.</p> <pre class="lang-js prettyprint-override"><code>// router // ... { path: '/pages/:id', name: 'pages', component: () =&gt; import('../views/PageView.vue'), }, // ... </code></pre> <pre class="lang-js prettyprint-override"><code>// PageView.vue &lt;script setup&gt; import { onMounted } from &quot;vue&quot;; import { ref } from 'vue'; onMounted(async () =&gt; { console.log( $route.params.id ); } </code></pre> <p>Here I get the error: <code>Uncaught (in promise) ReferenceError: $route is not defined</code>.</p> <p>But in template of the component the access with <code>{{ $route.params.id }}</code> is possible. But I need it in the script. What am I doing wrong?</p>
[ { "answer_id": 74286664, "author": "Boussadjra Brahim", "author_id": 8172857, "author_profile": "https://Stackoverflow.com/users/8172857", "pm_score": 3, "selected": true, "text": "useRoute" }, { "answer_id": 74286667, "author": "Patel Pratik", "author_id": 9272654, "author_profile": "https://Stackoverflow.com/users/9272654", "pm_score": 2, "selected": false, "text": "import { useRoute } from \"vue-router\";\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18066399/" ]
74,286,609
<p>I recently started learning c# So I got a school assignment to make a German grammar-help-tool. It's a group assignment my task is:</p> <p>The application loads prefabricated sentences from a file, and randomly makes small changes to these sentences. For example, commas can be deleted, <code>ies</code> can be replaced by <code>i</code>, <code>s</code> can be replaced by <code>ss</code>, and so on. The user is presented with the changed sentence, and it is up to him to find the error.</p> <p>I tried using the string. Replace and streamReader/Writer, but it didn't work.</p> <pre><code>StreamReader reader = new StreamReader(File.OpenRead(@&quot;C:\Users\kamil\OneDrive\Dokumente\test grammatik.txt&quot;)); string fileContent = reader.ReadToEnd(); reader.Close(); fileContent = fileContent.Replace(&quot;tier&quot;, &quot;aff&quot;); StreamWriter writer = new StreamWriter(File.OpenWrite(&quot;C:\test grammatik.txt&quot;)); writer.Write(fileContent); writer.Close(); </code></pre> <p>the sentance in the txt file is: &quot;Ein grosses Tier&quot; and I wanted to replace the &quot;Tier&quot; with &quot;Aff&quot; and it's what i expected and I got:</p> <blockquote> <p>System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect. : 'C:\Users\kamil\source\repos\test\bin\Debug\netcoreapp3.1\ est grammatik.txt''</p> </blockquote> <p>in the Line:</p> <pre><code>StreamWriter writer = new StreamWriter(File.OpenWrite(&quot;C:\test grammatik.txt&quot;)); </code></pre> <p>[link to my file]<a href="https://www.dropbox.com/s/p0r3us5o0ik0oju/test.zip?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/p0r3us5o0ik0oju/test.zip?dl=0</a></p>
[ { "answer_id": 74286738, "author": "Maytham Fahmi", "author_id": 3088349, "author_profile": "https://Stackoverflow.com/users/3088349", "pm_score": 2, "selected": false, "text": "StreamWriter writer = new StreamWriter(File.OpenWrite(\"C:\\test grammatik.txt\"));\n" }, { "answer_id": 74286798, "author": "G.Medina", "author_id": 7327744, "author_profile": "https://Stackoverflow.com/users/7327744", "pm_score": -1, "selected": false, "text": "public String Replace(char oldChar, char newChar);\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395437/" ]
74,286,633
<p><strong>Note:</strong> If you have the same problem and found this question before the &quot;duplicated&quot; one, be aware that the answer to that question does not work. I marked the only working solution below.</p> <p>I'm trying to follow <a href="https://dynamic-linq.net/advanced-entityframework#like-operator" rel="nofollow noreferrer">this guide</a> which states that this should be possible in Dynamic LINQ:</p> <pre><code>var config = new ParsingConfig { ResolveTypesBySimpleName = true }; var example2 = Cars.Where(config, &quot;DynamicFunctions.Like(Brand, \&quot;%t%\&quot;)&quot;); example2.Dump(); </code></pre> <p>I'm using string concatination to build a complex query:</p> <pre><code>IQueryable&lt;DtcViewEntity&gt; queryable = ... string[] values = { &quot;%a%&quot; }; string myOperator = &quot;and&quot;; // or sometimes &quot;or&quot; bool isNot = false; // or sometimes &quot;true&quot; var query = string.Join($&quot; {myOperator} &quot;, values.Select((value, index) =&gt; $&quot;DynamicFunctions.Like(MyColumn, @{index})&quot;)); if (isNot) query = $&quot;not ({query})&quot;; var config = new ParsingConfig { ResolveTypesBySimpleName = true }; return queryable.Where(config, query, values); </code></pre> <p>But the actual error can be reproduced with code that looks almost identical to the example in the guide:</p> <pre><code>IQueryable&lt;DtcViewEntity&gt; queryable = ... var config = new ParsingConfig { ResolveTypesBySimpleName = true }; var result = queryable.Where(config, &quot;DynamicFunctions.Like(MyColumn, \&quot;%a%\&quot;)&quot;).ToList(); </code></pre> <p>And I get:</p> <pre><code>System.Linq.Dynamic.Core.Exceptions.ParseException : Enum type 'DynamicFunctions' not found at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseAsEnum(String id) at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseMemberAccess(Type type, Expression expression) at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseIdentifier() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParsePrimaryStart() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParsePrimary() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseUnary() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseMultiplicative() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseAdditive() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseShiftOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseComparisonOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseLogicalAndOrOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseIn() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseAndOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseOrOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseLambdaOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseNullCoalescingOperator() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseConditionalOperator() </code></pre> <p>I've seen <a href="https://github.com/zzzprojects/System.Linq.Dynamic.Core/blob/6fc7fcc43b248940560a0728c4d181e191f9eec1/src-console/ConsoleAppEF2.1.1/Program.cs#L117" rel="nofollow noreferrer">this code</a> as well, but using <code>var config = ParsingConfig.DefaultEFCore21;</code> will result in</p> <pre><code>System.Linq.Dynamic.Core.Exceptions.ParseException : Enum type 'DynamicFunctions' not found at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseAsEnum(String id) at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseMemberAccess(Type type, Expression expression) at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParseIdentifier() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParsePrimaryStart() at System.Linq.Dynamic.Core.Parser.ExpressionParser.ParsePrimary() </code></pre> <p>After adding <code>Microsoft.EntityFrameworkCore.DynamicLinq</code> to the dependencies I get:</p> <pre><code>System.Linq.Dynamic.Core.Exceptions.ParseException : No applicable method 'Like' exists in type 'DynamicFunctions' </code></pre> <p><a href="https://stackoverflow.com/users/5273580/falco-alexander">Falco Alexander</a> even found a &quot;<a href="https://dotnetfiddle.net/rFGM80" rel="nofollow noreferrer">working example</a>&quot; form ZZZ Projects that produces the very same error message:</p> <pre><code>Unhandled exception. Enum type 'DynamicFunctions' not found (at index 21) Command terminated by signal 6 </code></pre> <p>I can't find any information on this exception, so my question is: what am I doing wrong?</p>
[ { "answer_id": 74286727, "author": "G.Medina", "author_id": 7327744, "author_profile": "https://Stackoverflow.com/users/7327744", "pm_score": -1, "selected": false, "text": "var Something = SomethingElse.Filter(x => x.Argument.Contains(Description));\n" }, { "answer_id": 74287935, "author": "Svyatoslav Danyliv", "author_id": 10646316, "author_profile": "https://Stackoverflow.com/users/10646316", "pm_score": -1, "selected": true, "text": "GetItemsPredicate" }, { "answer_id": 74287948, "author": "Falco Alexander", "author_id": 5273580, "author_profile": "https://Stackoverflow.com/users/5273580", "pm_score": 0, "selected": false, "text": "var result = context.Cars.Where(c => EF.Functions.Like(c.Brand, \"%a%\")).ToList();\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3482793/" ]
74,286,740
<p>`</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;stack.csv&quot;) sector_select = &quot;Col2&quot; df[sector_select] = [&quot;100&quot;] df.to_csv(&quot;stack.csv&quot;, index=False, mode='a', header=False) </code></pre> <p>`</p> <p>stack.csv has no data other than a header: Col1,Col2,Col3,Col4,Col5</p> <p><code>ValueError: Length of values (1) does not match length of index (2)</code></p> <p>Im just trying to make a program where I can select a header and append data to the column under that header</p> <p>You can only run it twice until it gives an error!</p>
[ { "answer_id": 74286895, "author": "axel_ande", "author_id": 3332023, "author_profile": "https://Stackoverflow.com/users/3332023", "pm_score": 1, "selected": true, "text": "import pandas as pd\n\ndf = pd.read_csv(\"stack.csv\")\n\nsector_select = \"Col2\"\n\ndf.at[len(df), sector_select] = \"100\"\n\ndf.to_csv(\"stack.csv\", index=False)\n" }, { "answer_id": 74287469, "author": "Mato", "author_id": 20390882, "author_profile": "https://Stackoverflow.com/users/20390882", "pm_score": 1, "selected": false, "text": "df = df.append({\"Col2\": 100}, ignore_index=True)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20385594/" ]
74,286,741
<p>I have input data like this:</p> <pre><code>[{ &quot;name&quot;: &quot;outField2&quot;, &quot;value&quot;: &quot;something&quot; }, { &quot;name&quot;: &quot;outField3[index].outField4&quot;, &quot;value&quot;: &quot;something&quot; }, { &quot;name&quot;: &quot;outField3[index].outField5&quot;, &quot;value&quot;: &quot;something&quot; }, { &quot;name&quot;: &quot;outField3[index].outField6.outField7&quot;, &quot;value&quot;: &quot;something&quot; }] </code></pre> <p>I am trying to achieve an output like this based on substring <code>'[index]'</code> (i.e. if that substring is not present then that element should be an object instead of an array):</p> <pre><code>{ &quot;outField2&quot;: &quot;something&quot;, &quot;outField3[index]&quot;: [{ &quot;outField4&quot;: &quot;something&quot;, &quot;outField5&quot;: &quot;something&quot;, &quot;outField6&quot;: { &quot;outField7&quot;: &quot;something&quot; } }] } </code></pre> <p>My current code (below) is able to produce the <code>outField3</code> as an object if there is no substring <code>'[index]'</code> but I'm unable to find a good solution to generate it as an array in the presence of the substring. Can someone help out? I've tried a few options but none gives me the desired result.</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>function doThis(item, index) { let path = map[index].name.split("."); if (path.length &gt; 1) { createNestedObject(mapOutput, path, map[index].value); } else { mapOutput[map[index].name] = map[index].value; }; }; function createNestedObject(element, path, value) { var lastElement = arguments.length === 3 ? path.pop() : false; for (var i = 0; i &lt; path.length; i++) { if (path[i].includes('[index]')) { /*some logic here to push the child elements that do not contain [index] as an array into the ones that contain [index]*/ } else { element = element[path[i]] = element[path[i]] || {}; }; } if (lastElement) element = element[lastElement] = value; return element; }; const map = [{ "name": "outField2", "value": "something" }, { "name": "outField3[index].outField4", "value": "something" }, { "name": "outField3[index].outField5", "value": "something" }, { "name": "outField3[index].outField6.outField7", "value": "something" }]; let mapOutput = {}; map.forEach(doThis); let mapOutputJSON = JSON.stringify(mapOutput, null, 2); console.log(mapOutputJSON);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code></pre> </div> </div> </p>
[ { "answer_id": 74286895, "author": "axel_ande", "author_id": 3332023, "author_profile": "https://Stackoverflow.com/users/3332023", "pm_score": 1, "selected": true, "text": "import pandas as pd\n\ndf = pd.read_csv(\"stack.csv\")\n\nsector_select = \"Col2\"\n\ndf.at[len(df), sector_select] = \"100\"\n\ndf.to_csv(\"stack.csv\", index=False)\n" }, { "answer_id": 74287469, "author": "Mato", "author_id": 20390882, "author_profile": "https://Stackoverflow.com/users/20390882", "pm_score": 1, "selected": false, "text": "df = df.append({\"Col2\": 100}, ignore_index=True)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395763/" ]
74,286,753
<pre><code>std::mutex task_lock; std::mutex running_tasks_lock; std::vector&lt;std::string&gt; path; std::vector&lt;std::thread *&gt; vecOfThreads; </code></pre> <pre><code>void __get_fileTree(std::thread *thread) { qDebug() &lt;&lt; &quot;YES&quot;; } void MapSorter::get_fileTree() { task_lock.lock(); path.push_back(&quot;D:\\ymir work\\&quot;); task_lock.unlock(); vecOfThreads.clear(); for (int i = 0; i &lt; 4; i++) { vecOfThreads.push_back(new std::thread(__get_fileTree, this)); } bool tasks_done_ticker = 4; while (tasks_done_ticker &gt; 0) { Sleep(10); running_tasks_lock.lock(); task_lock.lock(); if (path.empty()) { tasks_done_ticker -= 1; } else { tasks_done_ticker = 4; } running_tasks_lock.unlock(); task_lock.unlock(); } for (std::thread *s : vecOfThreads) { s-&gt;join(); } } </code></pre> <p>I tryed to create 4 threads and just print a debug to test it. I get this compiler issue so i thought I may have done something wrong but after trying to change the function call several times i couldnt fix it. Any suggestions?</p> <p>ERROR MESSAGES: <a href="https://i.stack.imgur.com/ICDjs.png" rel="nofollow noreferrer">Error messages</a></p> <p>Changes to</p> <pre><code>vecOfThreads.push_back(new std::thread(&amp;MapSorter::Repeatget_fileTree, this)); </code></pre> <p>doesnt fix the issue</p>
[ { "answer_id": 74286895, "author": "axel_ande", "author_id": 3332023, "author_profile": "https://Stackoverflow.com/users/3332023", "pm_score": 1, "selected": true, "text": "import pandas as pd\n\ndf = pd.read_csv(\"stack.csv\")\n\nsector_select = \"Col2\"\n\ndf.at[len(df), sector_select] = \"100\"\n\ndf.to_csv(\"stack.csv\", index=False)\n" }, { "answer_id": 74287469, "author": "Mato", "author_id": 20390882, "author_profile": "https://Stackoverflow.com/users/20390882", "pm_score": 1, "selected": false, "text": "df = df.append({\"Col2\": 100}, ignore_index=True)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18416534/" ]
74,286,754
<p>I'm making a small application. for that I need the optimal amount of items that could fit in my grid if the grid box had the size of the entire viewport height.</p> <p>The data I have: item height and width, grid box width, viewport height.</p> <p>the item dimensions stay the same on each screen size, the other values change.</p> <p>the grid box gutter size is 20px or 1.25rem.</p> <p><a href="https://i.stack.imgur.com/HPDZI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HPDZI.png" alt="enter image description here" /></a></p> <pre><code>export const calcHitsPerPage = () =&gt; { const productCard = document.querySelector('.ProductCard____0JXki'); let productCardWidth = productCard.offsetWidth; let productCardHeight = productCard.offsetHeight; const grid = document.querySelector('.ProductGrid____hZ3pR'); let gridWidth = productCard.offsetWidth; var viewportWidth = window.innerWidth; var viewportHeight = window.innerHeight; }; </code></pre>
[ { "answer_id": 74287109, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 1, "selected": true, "text": "cardWidth * cardHeight" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20061501/" ]
74,286,771
<p><a href="https://i.stack.imgur.com/0KEjk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0KEjk.png" alt="array of objects" /></a></p> <p>i am expecting to be able to target the id and use it where I want and the name and also use it where i want.</p>
[ { "answer_id": 74287109, "author": "Robby Cornelissen", "author_id": 3558960, "author_profile": "https://Stackoverflow.com/users/3558960", "pm_score": 1, "selected": true, "text": "cardWidth * cardHeight" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19682247/" ]
74,286,773
<pre><code>(function (){ console.log([0, 1, 2, 3].filter(i =&gt; {i % 2 == 0})); })(); // Array[] </code></pre> <p>I want to print an array that contains only even numbers, that is 0 and 2 in the case above. Array.prototype.filter along with an arrow function are used for this purpose.</p> <p>The above code returns an empty array. However, if I remove braces, the code works as expected.</p> <pre><code>(function (){ console.log([0, 1, 2, 3].filter(i =&gt; i % 2 == 0)); })(); // Array[0, 2] </code></pre> <p>Can someone explain why it happens? I always used arrow functions with braces and they worked just fine but it seems to me that there are caveats.</p>
[ { "answer_id": 74286913, "author": "axiac", "author_id": 4265352, "author_profile": "https://Stackoverflow.com/users/4265352", "pm_score": 1, "selected": false, "text": "i => i % 2 == 0" }, { "answer_id": 74286994, "author": "Călin Bogdan", "author_id": 3953035, "author_profile": "https://Stackoverflow.com/users/3953035", "pm_score": 0, "selected": false, "text": "return" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18195837/" ]
74,286,776
<p>I have this issue with Pytest where unit tests run fine from PyCharm but doesn't when I run through pipeline &quot;python -m pytest&quot;.</p> <p>Below is my project structure:</p> <pre><code>Common |_____configuration.py | Services | |-----ServiceA | | | |___src | | |___utils | | |__ __init__.py | | |__ helper1.py | |__ helper2.py | |___Test | |___utils | |__ __init.py | |__ test1.py | |-----ServiceB | | </code></pre> <p>In helper1 I have code as</p> <pre><code> from Common import configuration </code></pre> <p>Tests runs absolutely fine when I run through Pycharm because it resolves all path but when I run it through pipeline, I get below error when running through cmd,</p> <p><code>ModuleNotFoundError: No module named 'Common' </code></p> <p>Can anyone help how to resolve this issue. TIA</p>
[ { "answer_id": 74289035, "author": "tmt", "author_id": 772810, "author_profile": "https://Stackoverflow.com/users/772810", "pm_score": 2, "selected": true, "text": "[tool.pytest.ini_options]\npythonpath = [\"Common\"]\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/770975/" ]
74,286,794
<p>As the title suggests I am trying to remove the gap where the x axis labels are meant to be for the top graphs - Root length and Root Surface Area. Any suggestions?</p> <p><strong>CODE</strong></p> <pre><code>#Tukeys lettering anova &lt;- aov(Root_Length ~Treatment, data =JO_Data) tukey &lt;- TukeyHSD(anova) cld &lt;- multcompLetters4(anova, tukey) JO_Data_Root_Length &lt;- JO_Data %&gt;% dplyr::group_by(Treatment) %&gt;% dplyr::summarise(mean=mean(Root_Length), sd = sd(Root_Length)) %&gt;% arrange(desc(mean)) cld &lt;- as.data.frame.list(cld$Treatment) JO_Data_Root_Length$cld &lt;- cld$Letters # Root length plot plot.JO_Data.Root_Length=ggplot(JO_Data_Root_Length,aes(x = Treatment, y = mean, fill=Treatment)) + geom_bar(aes(x=Treatment, y=mean), stat=&quot;identity&quot;, alpha=1) + geom_errorbar( aes(x = Treatment, ymin = mean -sd, ymax = mean +sd), width=0.4, colour=&quot;black&quot;, alpha=0.9, size=1) + geom_text(aes(label = cld, y = mean + sd), vjust = -0.5) + labs(y = expression(paste(&quot;Root Length (cm)&quot;)))+ scale_y_continuous(expand = c(0,0), limits = c(0,12000), breaks = seq(0, 12000, by = 2000)) + scale_x_discrete(limits = c(&quot;Control&quot;, &quot;Control + UAN 50&quot;, &quot;Control + UAN 100&quot;,&quot;Compost&quot;, &quot;Compost + UAN 50&quot;, &quot;LD&quot;, &quot;LD + UAN 50&quot;, &quot;SD&quot;, &quot;SD + UAN 50&quot;))+ scale_fill_manual(values = cbbPalette, breaks = c(&quot;Control&quot;, &quot;Control + UAN 50&quot;, &quot;Control + UAN 100&quot;,&quot;Compost&quot;, &quot;Compost + UAN 50&quot;, &quot;LD&quot;, &quot;LD + UAN 50&quot;, &quot;SD&quot;, &quot;SD + UAN 50&quot;))+ theme(axis.line = element_line(colour = &quot;black&quot;), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.text.x = element_blank(), axis.text.y = element_text(size = 12), axis.title.y = element_text(size = 12))+ theme(legend.justification = c(&quot;right&quot;, &quot;top&quot;))+ theme(legend.title = element_text(color = &quot;black&quot;, size = 16, face = &quot;bold&quot;))+ theme(legend.title.align = 0.5) + theme(legend.background = element_rect(linetype = &quot;solid&quot;, colour = &quot;black&quot;, size = 1))+ theme(legend.margin = margin(0.1,0.2,0.2,0.2, unit =&quot;cm&quot;))+ theme(legend.text = element_text(size=14, colour=&quot;black&quot;))+ theme(axis.title.x=element_blank()) plot.JO_Data.Root_Length ################### three other graphs not added in code to reduce size but is the same as Root length for the rest of the graphs ######## # Putting all the plots together # install.packages(&quot;gridExtra&quot;) library(gridExtra) # install.packages(&quot;cowplot&quot;) library(cowplot) ?plot_grid JO_plot2 &lt;- plot_grid(plot.JO_Data.Root_Length + theme(legend.position=&quot;none&quot;), plot.JO_Data.Root_SA + theme(legend.position=&quot;none&quot;), plot.JO_Data.Root_diameter + theme(legend.position=&quot;none&quot;), plot.JO_Data.Root_Vol + theme(legend.position=&quot;none&quot;), align = &quot;h&quot;, axis = &quot;b&quot;, hjust = 0.1, vjust = 0.1, nrow = 2, ncol =2) legend &lt;- get_legend(plot.JO_Data.Root_Length) Root_plot2 &lt;- plot_grid(JO_plot2, legend, rel_widths = c(1.75, 0.5)) Root_plot2 </code></pre> <p>Graph Output</p> <p><a href="https://i.stack.imgur.com/55fnx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/55fnx.png" alt="enter image description here" /></a></p> <p>I thought the axis.text.x = element_blank() would fix the problem but it hasn't.</p> <p>Cheers :)</p>
[ { "answer_id": 74298565, "author": "James", "author_id": 20087008, "author_profile": "https://Stackoverflow.com/users/20087008", "pm_score": 0, "selected": false, "text": "ggarrange(plot.JO_Data.Root_Length + theme(legend.position=\"none\"),\n plot.JO_Data.Root_SA,\n plot.JO_Data.Root_diameter + theme(legend.position=\"none\"),\n plot.JO_Data.Root_Vol + theme(legend.position=\"none\"), ncol = 2)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20087008/" ]
74,286,806
<p>I have the following piece of code that is working but I don't understand why it works (inspired by a real life code base):</p> <p>Base class definition:</p> <pre><code>class Pointers { private: int* Obj1; double* Obj2; public: Pointers(int* Obj1_, double* Obj2_) : Obj1{Obj1_}, Obj2{Obj2_} {} }; </code></pre> <p>We now derive a class from our base class where we shadow the two pointers with an <code>int</code> and a <code>double</code> of the same name:</p> <pre><code>class Objects : public Pointers { public: int Obj1{69}; double Obj2{72}; Objects() : Pointers(&amp;Obj1, &amp;Obj2) {} }; </code></pre> <p>Within the constructor of <code>Objects</code> we call the constructor of <code>Pointers</code> and pass the adresses of <code>Obj1</code> and <code>Obj2</code>. This actually works: The (shadowed) pointers will point to <code>Obj1 (69)</code>and <code>Obj2 (72)</code>.</p> <p>My question is: Why is this working? I thought that in the first step the base class members are constructed (which are the two pointers) and only after that the derived class members (the <code>int</code> and <code>double</code> with the same name) are constructed. How can we pass these objects adresses to the base class constructor in the first place?</p>
[ { "answer_id": 74286896, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": false, "text": "class Objects : public Pointers {\npublic:\n int Obj1{69};\n double Obj2{72};\n Objects() : Pointers(&Obj1, &Obj2) {}\n};\n" }, { "answer_id": 74287054, "author": "pptaszni", "author_id": 4165552, "author_profile": "https://Stackoverflow.com/users/4165552", "pm_score": 3, "selected": true, "text": " int Obj1{69};\n double Obj2{72};\n" }, { "answer_id": 74287107, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "new" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17006981/" ]
74,286,817
<p>In my Android Studio, Filter Option was disappear.</p> <p>In my Android Studio, there was a Filter Option like the red square in the picture below.</p> <p><a href="https://i.stack.imgur.com/qs8WT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qs8WT.png" alt="enter image description here" /></a></p> <p>However, I don't know when, but the Filter Option has disappeared as shown in the picture below.</p> <p><a href="https://i.stack.imgur.com/zWxXD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zWxXD.png" alt="enter image description here" /></a></p> <p>I want to see the log using &quot;Show only selected application&quot; in the Filter Option of Android Studio.</p> <p>How do I make the Filter Options visible again?...</p> <p>Note that,</p> <p>I am using these versions.</p> <ul> <li>Android Studio Dolphin | 2021.3.1 Patch 1 Runtime version: 11.0.13+0-b1751.21-8125866 amd64</li> <li>Android Gradle Plugin Version 7.3.1</li> <li>Gradle Version 7.4</li> <li>Bolt Toolkit version 1.14.7</li> </ul> <p>(Likewise, the Filter Option was not shown in Android Gradle Plugin Version 3.6.3, Gradle Version 5.6.4 and AGPV 4.2.2, GV 6.7.1.)</p> <p>And I have the following Event Logs.</p> <p>File pattern '<em>.log' (from 'Ideolog' plugin) was reassigned to file type 'log' by 'Bolt Toolkit' plugin. You can confirm or revert reassigning pattern '</em>.log'. Confirm reassign this pattern to file type 'log' from plugin 'Bolt Toolkit'. Revert this pattern to file type 'LOG' from plugin 'Ideolog'. Edit file type 'LOG'. Edit file type 'log'.</p>
[ { "answer_id": 74286896, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": false, "text": "class Objects : public Pointers {\npublic:\n int Obj1{69};\n double Obj2{72};\n Objects() : Pointers(&Obj1, &Obj2) {}\n};\n" }, { "answer_id": 74287054, "author": "pptaszni", "author_id": 4165552, "author_profile": "https://Stackoverflow.com/users/4165552", "pm_score": 3, "selected": true, "text": " int Obj1{69};\n double Obj2{72};\n" }, { "answer_id": 74287107, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "new" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9279134/" ]
74,286,842
<p>I have return statement within a recursive function that looks like this:</p> <pre><code>def recursive_function(data): .... return {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': refs} </code></pre> <p>Sometimes some of these values can be None (ex: when the title has a value, the string's value will be None, and vice-versa). The application I'm using does not recognize keys with None values, how do I prevent those keys from returning when the values are None?</p> <p>Thank you in advance.</p>
[ { "answer_id": 74286896, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": false, "text": "class Objects : public Pointers {\npublic:\n int Obj1{69};\n double Obj2{72};\n Objects() : Pointers(&Obj1, &Obj2) {}\n};\n" }, { "answer_id": 74287054, "author": "pptaszni", "author_id": 4165552, "author_profile": "https://Stackoverflow.com/users/4165552", "pm_score": 3, "selected": true, "text": " int Obj1{69};\n double Obj2{72};\n" }, { "answer_id": 74287107, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": false, "text": "new" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16154666/" ]
74,286,871
<p>Say I have struct S:</p> <pre class="lang-cpp prettyprint-override"><code>struct S { const int i; const bool b; } </code></pre> <p>And I want to create an (non-const) array of this struct like so:</p> <pre class="lang-cpp prettyprint-override"><code>std::array&lt;S, 16&gt; arr; for(int i = 0; i&lt;arr.size(); i++) arr[i] = { i, i%2==0 }; </code></pre> <p>Then the compiler will complain that I didn't initialize the a const variable when I initialized the array.</p> <p>I tried doing it with a vector as an intermediary. But int the function I'm writing I have to pass the original array in another struct, and return that other struct.</p> <pre class="lang-cpp prettyprint-override"><code>struct OtherStruct { const std::array&lt;S,16&gt; sArray; }; OtherStruct f() { std::vector&lt;S&gt; vec(16); for(int i = 0; i&lt;16; i++) vec.push_back({ i, i%2==0 }); return { vec.data() }; } </code></pre> <p>But that didn't work either. I hoped that passing the pointer to the vector data would be cast into a C-style array, from which an std::array could be made. What is the cleanest way to fix this?</p> <p>I'm working with C++11.</p> <p>Note that this example is a gross simplification. The line <code>arr[i] = { i, i%2==0 };</code> would be replaced by a function that parses incoming network data. The actual array is way bigger and the struct is also more complicated. None of the data that will populate the struct will be known at compile time, only the layout.</p>
[ { "answer_id": 74287320, "author": "Caleth", "author_id": 2610810, "author_profile": "https://Stackoverflow.com/users/2610810", "pm_score": 2, "selected": false, "text": "std::index_sequence" }, { "answer_id": 74287323, "author": "VLL", "author_id": 2527795, "author_profile": "https://Stackoverflow.com/users/2527795", "pm_score": 1, "selected": false, "text": "BOOST_PP_REPEAT" }, { "answer_id": 74287548, "author": "Gio", "author_id": 17784198, "author_profile": "https://Stackoverflow.com/users/17784198", "pm_score": -1, "selected": false, "text": "const" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6849045/" ]
74,286,876
<p>While using <code>TopologyTestDriver</code> I want to test my stream and do assrtions on intermediate state between incoming messages. But after using <code>TestOutputTopic.readKeyValuesToMap()</code> tested topic is cleared. How to &quot;peek&quot; and do assertions between messages?</p> <pre><code>import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.*; import org.apache.kafka.streams.kstream.Consumed; import org.apache.kafka.streams.kstream.Grouped; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.test.TestRecord; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.Properties; public class AggregationTest { private static TestInputTopic&lt;String, String&gt; inputTopic; private static TestOutputTopic&lt;String, String&gt; outputTopic; private static TopologyTestDriver testDriver; @BeforeAll public static void setup() { StreamsBuilder builder = new StreamsBuilder(); builder .stream(&quot;inputTopic&quot;, Consumed.with(Serdes.String(), Serdes.String())) .toTable(Materialized.with(Serdes.String(), Serdes.String())) .groupBy( KeyValue::pair, Grouped.with(&quot;group-by-internal&quot;, Serdes.String(), Serdes.String())) .aggregate( () -&gt; &quot;&quot;, (key, incomingMessage, existingMessage) -&gt; incomingMessage + &quot; &quot; + existingMessage, (key, incomingMessage, existingMessage) -&gt; existingMessage ).toStream().to(&quot;outputTopic&quot;, Produced.with(Serdes.String(), Serdes.String())); testDriver = new TopologyTestDriver(builder.build(), new Properties() {{ put(StreamsConfig.APPLICATION_ID_CONFIG, &quot;test&quot;); put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, Serdes.String().getClass().getName()); put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); put(StreamsConfig.STATE_DIR_CONFIG, &quot;/tmp/kafka-streams&quot;); }}); inputTopic = testDriver.createInputTopic(&quot;inputTopic&quot;, Serdes.String().serializer(), Serdes.String().serializer()); outputTopic = testDriver.createOutputTopic(&quot;outputTopic&quot;, Serdes.String().deserializer(), Serdes.String().deserializer()); } @Test public void testAggregation() { TestRecord&lt;String, String&gt; message1 = new TestRecord&lt;&gt;( &quot;Key1&quot;, &quot;Value1&quot;); TestRecord&lt;String, String&gt; message2 = new TestRecord&lt;&gt;( &quot;Key2&quot;, &quot;Value2&quot;); TestRecord&lt;String, String&gt; message3 = new TestRecord&lt;&gt;( &quot;Key1&quot;, &quot;Value3&quot;); inputTopic.pipeInput(message1); inputTopic.pipeInput(message2); var outputMap = outputTopic.readKeyValuesToMap(); System.out.println(outputMap); // {Key2=Value2 , Key1=Value1 } // Assert that message1 and message2 was not effected inputTopic.pipeInput(message3); var outputMap2 = outputTopic.readKeyValuesToMap(); System.out.println(outputMap2); // {Key1=Value3 Value1 } // where message with Key2 disappeared? // How to assert that message3 was merged with message1, but message2 was not effected? } @AfterAll public static void tearDown() { testDriver.close(); } } </code></pre>
[ { "answer_id": 74290374, "author": "WnaJ", "author_id": 5528518, "author_profile": "https://Stackoverflow.com/users/5528518", "pm_score": 0, "selected": false, "text": "readKeyValuesToMap" }, { "answer_id": 74295681, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 2, "selected": true, "text": "Key2" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9918701/" ]
74,286,884
<pre><code>def add(x, y): return x + y def do twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b)) </code></pre> <p>Someone Please explain it to me in simple words..</p>
[ { "answer_id": 74286945, "author": "Shirley", "author_id": 10939465, "author_profile": "https://Stackoverflow.com/users/10939465", "pm_score": 0, "selected": false, "text": "do_twice(add, a, b)" }, { "answer_id": 74286954, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 0, "selected": false, "text": "do_twice(add, a, b)" }, { "answer_id": 74286959, "author": "alexis", "author_id": 699305, "author_profile": "https://Stackoverflow.com/users/699305", "pm_score": 2, "selected": false, "text": "add" }, { "answer_id": 74286962, "author": "Fabian Thorsen", "author_id": 12206155, "author_profile": "https://Stackoverflow.com/users/12206155", "pm_score": 1, "selected": false, "text": "add(x,y)" }, { "answer_id": 74287051, "author": "Sivadithiyan", "author_id": 18426816, "author_profile": "https://Stackoverflow.com/users/18426816", "pm_score": -1, "selected": false, "text": "def add(x, y):\n return x + y\n\ndef do_twice(func, x, y):\n return func(func(x, y), func(x, y))\n\na = 5 \nb = 10\n\nprint(do_twice(add, a, b))\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20377131/" ]
74,286,928
<p>I got a big problem... I am using drawattention and everything was fine untill suddenly the sections are broken, I believe it got something to do with elementor...</p> <p>When I enter the elementor editor, it looks great and then on preview its broken. And when u go to inspect page it gets fixed.</p> <p>How do I fix this?</p> <p>Website: <a href="https://plgrupa.hr/projekti/projekt-harambasiceva/stanovi-harambasiceva-57/" rel="nofollow noreferrer">https://plgrupa.hr/projekti/projekt-harambasiceva/stanovi-harambasiceva-57/</a></p> <p>Thanks in advance!</p> <p>I tryed changing CSS in many ways and nothing helped...</p>
[ { "answer_id": 74286945, "author": "Shirley", "author_id": 10939465, "author_profile": "https://Stackoverflow.com/users/10939465", "pm_score": 0, "selected": false, "text": "do_twice(add, a, b)" }, { "answer_id": 74286954, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 0, "selected": false, "text": "do_twice(add, a, b)" }, { "answer_id": 74286959, "author": "alexis", "author_id": 699305, "author_profile": "https://Stackoverflow.com/users/699305", "pm_score": 2, "selected": false, "text": "add" }, { "answer_id": 74286962, "author": "Fabian Thorsen", "author_id": 12206155, "author_profile": "https://Stackoverflow.com/users/12206155", "pm_score": 1, "selected": false, "text": "add(x,y)" }, { "answer_id": 74287051, "author": "Sivadithiyan", "author_id": 18426816, "author_profile": "https://Stackoverflow.com/users/18426816", "pm_score": -1, "selected": false, "text": "def add(x, y):\n return x + y\n\ndef do_twice(func, x, y):\n return func(func(x, y), func(x, y))\n\na = 5 \nb = 10\n\nprint(do_twice(add, a, b))\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20289486/" ]
74,286,930
<pre><code>#Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9. ri = input(&quot;please enter four digits&quot;) if len(ri) == 4 and ri.isnumeric() == True: print(ri[0]+ri[1]+ri[2]+ri[3]) else: print(&quot;Error: should be four digits!&quot;) </code></pre> <p>How do I do this? Haven't seen something like this before I'm sure, and as you can see my code fails....</p>
[ { "answer_id": 74286967, "author": "caf9", "author_id": 19385211, "author_profile": "https://Stackoverflow.com/users/19385211", "pm_score": -1, "selected": false, "text": "input_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += str(sum)\n\nprint (output_string)\n" }, { "answer_id": 74287034, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n" }, { "answer_id": 74287045, "author": "sat", "author_id": 12639184, "author_profile": "https://Stackoverflow.com/users/12639184", "pm_score": 1, "selected": true, "text": "ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\n res += int(n)\nprint (ri[0]+\"+\"+ri[1]+\"+\"+ri[2]+\"+\"+ri[3]+\"=\"+str(res))\n" }, { "answer_id": 74287056, "author": "9001_db", "author_id": 11026899, "author_profile": "https://Stackoverflow.com/users/11026899", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter some digits: \")\ntry:\n print(\"Digit sum: \" + str(sum([int(x) for x in ri])))\nexcept:\n raise ValueError(\"That was no valid number!\")\n" }, { "answer_id": 74287176, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "ri = input('please enter four digits:')\nif len(ri) == 4 and ri.isnumeric():\n print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))\nelse:\n print('Error: should be four digits')\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20231159/" ]
74,286,943
<p>I have a .NET CORE 3.1 Console application running on a Ubuntu20 x64 server, and randomly experiencing High Cpu(100% for 4 cores) cases.</p> <p>I'm following <a href="https://docs.microsoft.com/en-us/dotnet/core/diagnostics/debug-highcpu?tabs=windows" rel="nofollow noreferrer">diagnostics</a> to start a diag during the peak time for my app like:</p> <pre><code>dotnet-trace collect -p 1039 --providers Microsoft-DotNETCore-SampleProfiler </code></pre> <p>from the resulted <code>.nettrace</code> file opened in Visual Studio, I can see the Funcions list with CPU Time for each single function.</p> <p>But I understand the CPU time here is actually the <code>wall time</code> that just means the time of a function call stayed in a thread stack, and no matter it consumes real CPU caculation resource or not.</p> <p>The hotest spot my this <code>.nettrace</code> now is pointing to these lines of code(pseudo code):</p> <pre><code>while(true) { Thread.Sleep(1000);//&lt;---------hottest spot socket.Send(bytes); } </code></pre> <p>and</p> <pre><code>while(true) { ManualResetEvent.WaitOne();//&lt;---------hottest spot httpClient.Post(data); } </code></pre> <p>Obviously above 2 hottest spot will not consume real CPU resource but just idle waitting, so any way to trace the functions that used the real cpu usage, just like the JetBrains <a href="https://www.jetbrains.com/profiler/" rel="nofollow noreferrer">dotTrace</a> provided: <a href="https://i.stack.imgur.com/Z1j80.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z1j80.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74286967, "author": "caf9", "author_id": 19385211, "author_profile": "https://Stackoverflow.com/users/19385211", "pm_score": -1, "selected": false, "text": "input_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += str(sum)\n\nprint (output_string)\n" }, { "answer_id": 74287034, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n" }, { "answer_id": 74287045, "author": "sat", "author_id": 12639184, "author_profile": "https://Stackoverflow.com/users/12639184", "pm_score": 1, "selected": true, "text": "ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\n res += int(n)\nprint (ri[0]+\"+\"+ri[1]+\"+\"+ri[2]+\"+\"+ri[3]+\"=\"+str(res))\n" }, { "answer_id": 74287056, "author": "9001_db", "author_id": 11026899, "author_profile": "https://Stackoverflow.com/users/11026899", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter some digits: \")\ntry:\n print(\"Digit sum: \" + str(sum([int(x) for x in ri])))\nexcept:\n raise ValueError(\"That was no valid number!\")\n" }, { "answer_id": 74287176, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "ri = input('please enter four digits:')\nif len(ri) == 4 and ri.isnumeric():\n print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))\nelse:\n print('Error: should be four digits')\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1602160/" ]
74,286,946
<p>I'm trying to figure out how to split words from a sentence in an array without using split() but using charAt() function.</p> <pre><code>function sentenceToWordArray(sentence) { let stringArray = [&quot;&quot;] let j = 0 for (let i = 0; i &lt; sentence.length; i++) { if (sentence.charAt(i) == &quot; &quot;) { j++; stringArray.push(&quot;&quot;) } else { stringArray[j] += sentence.charAt(i) } } return stringArray } </code></pre> <p>Now I have the code working but I'm encountering some problems like for example &quot;Hello World&quot; turns into &quot;Hello&quot;, &quot;World&quot; but if I add extra spaces for example &quot; Hello World &quot; it outputs ['', 'hello', '', 'there', '']. Is there a way to remove the extra spaces?</p>
[ { "answer_id": 74286967, "author": "caf9", "author_id": 19385211, "author_profile": "https://Stackoverflow.com/users/19385211", "pm_score": -1, "selected": false, "text": "input_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += str(sum)\n\nprint (output_string)\n" }, { "answer_id": 74287034, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n" }, { "answer_id": 74287045, "author": "sat", "author_id": 12639184, "author_profile": "https://Stackoverflow.com/users/12639184", "pm_score": 1, "selected": true, "text": "ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\n res += int(n)\nprint (ri[0]+\"+\"+ri[1]+\"+\"+ri[2]+\"+\"+ri[3]+\"=\"+str(res))\n" }, { "answer_id": 74287056, "author": "9001_db", "author_id": 11026899, "author_profile": "https://Stackoverflow.com/users/11026899", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter some digits: \")\ntry:\n print(\"Digit sum: \" + str(sum([int(x) for x in ri])))\nexcept:\n raise ValueError(\"That was no valid number!\")\n" }, { "answer_id": 74287176, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "ri = input('please enter four digits:')\nif len(ri) == 4 and ri.isnumeric():\n print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))\nelse:\n print('Error: should be four digits')\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20141582/" ]
74,286,961
<p>I have a matrix that I want to convert to 3D so that I can be able to print the element of list[i][j][k]</p> <pre><code>a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]] print(a[5][5][0]) # I want to be able to print in 3D` </code></pre> <p>I get right output if I do a[5][5] but wrong when I add the [0]. Is there anyway of converting my matrix such that this will be solved?</p> <p>I tried to just wrap the list up with brackets [list], but it did not work. I also did: b = [[i] for i in a]</p> <p>which gave me [[[0,1,2,3,4,5]],[[1,2,3,4,5,6]],... and it still did not work!</p> <p>NOTE: I want the i to be the row, j to be the column and k to be 0 or 1, so k = 0 (in which case the value is the row index of the cell is pointing to), or the k = 1 (the value is the column index).</p>
[ { "answer_id": 74286967, "author": "caf9", "author_id": 19385211, "author_profile": "https://Stackoverflow.com/users/19385211", "pm_score": -1, "selected": false, "text": "input_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += str(sum)\n\nprint (output_string)\n" }, { "answer_id": 74287034, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n" }, { "answer_id": 74287045, "author": "sat", "author_id": 12639184, "author_profile": "https://Stackoverflow.com/users/12639184", "pm_score": 1, "selected": true, "text": "ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\n res += int(n)\nprint (ri[0]+\"+\"+ri[1]+\"+\"+ri[2]+\"+\"+ri[3]+\"=\"+str(res))\n" }, { "answer_id": 74287056, "author": "9001_db", "author_id": 11026899, "author_profile": "https://Stackoverflow.com/users/11026899", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter some digits: \")\ntry:\n print(\"Digit sum: \" + str(sum([int(x) for x in ri])))\nexcept:\n raise ValueError(\"That was no valid number!\")\n" }, { "answer_id": 74287176, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "ri = input('please enter four digits:')\nif len(ri) == 4 and ri.isnumeric():\n print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))\nelse:\n print('Error: should be four digits')\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20179855/" ]
74,286,986
<p>I have this issue where I need to print <code>float</code> number while I use <code>int</code> parameters in function.</p> <pre><code>float lift_a_car(const int stick_length, const int human_weight, const int car_weight) { return (stick_length*human_weight)/(car_weight+human_weight); } </code></pre> <p>I'm checking it by using:</p> <pre><code>printf(&quot;%.4f\n&quot;, lift_a_car(2, 80, 1400)); </code></pre> <p>It only returns 0.0000.</p>
[ { "answer_id": 74286967, "author": "caf9", "author_id": 19385211, "author_profile": "https://Stackoverflow.com/users/19385211", "pm_score": -1, "selected": false, "text": "input_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += str(sum)\n\nprint (output_string)\n" }, { "answer_id": 74287034, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n" }, { "answer_id": 74287045, "author": "sat", "author_id": 12639184, "author_profile": "https://Stackoverflow.com/users/12639184", "pm_score": 1, "selected": true, "text": "ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\n res += int(n)\nprint (ri[0]+\"+\"+ri[1]+\"+\"+ri[2]+\"+\"+ri[3]+\"=\"+str(res))\n" }, { "answer_id": 74287056, "author": "9001_db", "author_id": 11026899, "author_profile": "https://Stackoverflow.com/users/11026899", "pm_score": 0, "selected": false, "text": "ri = input(\"please enter some digits: \")\ntry:\n print(\"Digit sum: \" + str(sum([int(x) for x in ri])))\nexcept:\n raise ValueError(\"That was no valid number!\")\n" }, { "answer_id": 74287176, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "ri = input('please enter four digits:')\nif len(ri) == 4 and ri.isnumeric():\n print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))\nelse:\n print('Error: should be four digits')\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18930163/" ]
74,286,991
<p>Say I have a dataframe with negative values on specific columns:</p> <pre><code>df = pd.DataFrame([[1, 1, -1],[-1, 1, 1],[-1, -1, 1]]) </code></pre> <p>Now, I want to <strong>inplace</strong> clip the negative values to 0 on only specific lines and columns:</p> <pre><code>df.loc[[1, 2], [0, 1]].clip(lower=0, inplace=True) </code></pre> <p>But this doesn't work:</p> <pre><code>df Out: 0 1 2 0 1 1 -1 1 -1 1 1 2 -1 -1 1 </code></pre> <p>This is because slicing dataframe with a list of integers returns a copy:</p> <pre><code>df.loc[[1, 2], [0, 1]] is df.loc[[1, 2], [0, 1]] Out: False </code></pre> <p>How do I make <strong>inplace</strong> changes to specific rows and columns then?</p>
[ { "answer_id": 74287098, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 0, "selected": false, "text": "df.loc[[1, 2], [0, 1]] = df.loc[[1, 2], [0, 1]].clip(lower=0)\n" }, { "answer_id": 74287219, "author": "ouroboros1", "author_id": 18470692, "author_profile": "https://Stackoverflow.com/users/18470692", "pm_score": 1, "selected": false, "text": "df.lt" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4803860/" ]
74,286,993
<p>Update: I have found a better website for getting the data. If you press my link, you can see in the top of the screen there are multiple future games. I would like to get details about the games that BC Copenhagen plays. The details should be live stats (points, players' points...). Is this possible?</p> <p>Website: <a href="https://basketligaen.dk/" rel="nofollow noreferrer">https://basketligaen.dk/</a></p> <hr /> <p>I have a pretty difficult question. I want to fetch live data from a basketball game website. However, this is very tricky, because first of all: The live games change all the time, and I'm only interested when one team is playing: &quot;BC Copenhagen&quot;. (However, if I get more data from different teams, that would work as well) When you click on the list, you get moved to a detailed screen about the live game. And this is the data I'm interested in. So I need to somehow get data from the live games. Is it even possible to do this with Excell commands, or do I need to work with APIs like Zapier or Make? However, I have no idea how to do this. Do you maybe have to give the Link to the game every time the game starts? But this would really not be a reliable solution. Note: I'm using this data for a Glide App Website: <a href="https://official.mvpapp.dk/live.php" rel="nofollow noreferrer">https://official.mvpapp.dk/live.php</a></p>
[ { "answer_id": 74287098, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 0, "selected": false, "text": "df.loc[[1, 2], [0, 1]] = df.loc[[1, 2], [0, 1]].clip(lower=0)\n" }, { "answer_id": 74287219, "author": "ouroboros1", "author_id": 18470692, "author_profile": "https://Stackoverflow.com/users/18470692", "pm_score": 1, "selected": false, "text": "df.lt" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74286993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19282494/" ]
74,287,007
<p>I would like to resample a pandas series with <code>timedelta</code> starting with the zero interval (<code>timedelta(seconds=0)</code>) instead of the first occurrence.</p> <p>For example, for</p> <pre><code>from datetime import timedelta from random import sample s = pd.Series(1, index=[timedelta(minutes=m) for m in sample(range(1, 100), 10)]) s.resample('1h').count() </code></pre> <p>I get</p> <pre><code>0 days 00:12:00 9 0 days 01:12:00 1 </code></pre> <p>But I need</p> <pre><code>0 days 00:00:00 9 0 days 01:00:00 0 0 days 02:00:00 1 </code></pre>
[ { "answer_id": 74287098, "author": "T C Molenaar", "author_id": 8814131, "author_profile": "https://Stackoverflow.com/users/8814131", "pm_score": 0, "selected": false, "text": "df.loc[[1, 2], [0, 1]] = df.loc[[1, 2], [0, 1]].clip(lower=0)\n" }, { "answer_id": 74287219, "author": "ouroboros1", "author_id": 18470692, "author_profile": "https://Stackoverflow.com/users/18470692", "pm_score": 1, "selected": false, "text": "df.lt" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1864294/" ]
74,287,047
<p>I have several ip addresses like</p> <pre><code>162.1.10.15 160.15.20.222 145.155.222.1 </code></pre> <p>I am trying to replace the ip's like below.</p> <pre><code>162.x.xx.xx 160.xx.xx.xxx 145.xxx.xxx.x </code></pre> <p>How to achieve this in python.</p>
[ { "answer_id": 74287152, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "re.sub" }, { "answer_id": 74287287, "author": "Abhijit Sarkar", "author_id": 839733, "author_profile": "https://Stackoverflow.com/users/839733", "pm_score": 3, "selected": true, "text": "import re\n\ntxt = \"192.1.2.3\"\n\nx = txt.split(\".\", 1) # ['192', '1.2.3']\ny = x[0] + \".\" + re.sub(r\"\\d\", \"x\", x[1])\n\nprint(y) # 192.x.x.x\n" }, { "answer_id": 74287299, "author": "Sivadithiyan", "author_id": 18426816, "author_profile": "https://Stackoverflow.com/users/18426816", "pm_score": 0, "selected": false, "text": "ip = \"162.1.10.15\"\n\n#Splitting the IPv4 address using '.' as the delimiter\nip = ip.split(\".\")\n\n#Converting the substrings to x's except 1st string\nfor i,val in enumerate(ip[1:]):\n cnt = 0\n for x in val:\n cnt += 1\n ip[i+1] = \"x\" * cnt\n\n#Combining the substrings back to ip\nip = \".\".join(ip)\nprint(ip)\n\n" }, { "answer_id": 74287309, "author": "Farhan Mushtaq", "author_id": 20396064, "author_profile": "https://Stackoverflow.com/users/20396064", "pm_score": 1, "selected": false, "text": "import re\nIp_string = \"160.15.20.222\"\nIp_string = Ip_string.split('.')\nIp_String_x =\"\"\nflag = False\nfor num in Ip_string:\n if flag:\n num = re.sub('\\d','x',num)\n Ip_String_x = Ip_String_x + '.'+ num\n else:\n flag = True\n Ip_String_x = num\n" }, { "answer_id": 74287321, "author": "Boseong Choi", "author_id": 7562853, "author_profile": "https://Stackoverflow.com/users/7562853", "pm_score": 1, "selected": false, "text": "import re\n\n\nstrings = [\n '162.1.10.15',\n '160.15.20.222',\n '145.155.222.1',\n]\n\nfor string in strings:\n print(re.sub(r'(?:(?<=\\.)|(?<=\\.\\d)|(?<=\\.\\d\\d))\\d', 'x', string))\n" }, { "answer_id": 74287397, "author": "HelpfulHelper", "author_id": 18155054, "author_profile": "https://Stackoverflow.com/users/18155054", "pm_score": 0, "selected": false, "text": "def replace_ips(ip_list):\n r_list=[]\n for i in ip_list:\n first,*other=i.split(\".\",3)\n r_item=[]\n r_item.append(first)\n for i2 in other:\n r_item.append(\"x\"*len(i2))\n r_list.append(\".\".join(r_item))\n return r_list\n" }, { "answer_id": 74288399, "author": "EVGENY OGRYZKOV", "author_id": 15239072, "author_profile": "https://Stackoverflow.com/users/15239072", "pm_score": 0, "selected": false, "text": "import re\n\nips = ['162.1.10.15', '160.15.20.222', '145.155.222.1']\npattern = r'\\d{1,3}'\nreplacement_sign = 'x'\n\nres = [re.sub(pattern, replacement_sign, ip[::-1], 3)[::-1] for ip in ips]\n\nprint(res)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8832641/" ]
74,287,070
<p>The nestjs class-validator does not work. For example, if I send a post request with a number for LoginId, I get a normal response.</p> <pre><code>import { IsNumber, IsString } from 'class-validator'; export class LoginUserDto { @IsString() loginId: string; @IsString() password: string; } </code></pre>
[ { "answer_id": 74287152, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "re.sub" }, { "answer_id": 74287287, "author": "Abhijit Sarkar", "author_id": 839733, "author_profile": "https://Stackoverflow.com/users/839733", "pm_score": 3, "selected": true, "text": "import re\n\ntxt = \"192.1.2.3\"\n\nx = txt.split(\".\", 1) # ['192', '1.2.3']\ny = x[0] + \".\" + re.sub(r\"\\d\", \"x\", x[1])\n\nprint(y) # 192.x.x.x\n" }, { "answer_id": 74287299, "author": "Sivadithiyan", "author_id": 18426816, "author_profile": "https://Stackoverflow.com/users/18426816", "pm_score": 0, "selected": false, "text": "ip = \"162.1.10.15\"\n\n#Splitting the IPv4 address using '.' as the delimiter\nip = ip.split(\".\")\n\n#Converting the substrings to x's except 1st string\nfor i,val in enumerate(ip[1:]):\n cnt = 0\n for x in val:\n cnt += 1\n ip[i+1] = \"x\" * cnt\n\n#Combining the substrings back to ip\nip = \".\".join(ip)\nprint(ip)\n\n" }, { "answer_id": 74287309, "author": "Farhan Mushtaq", "author_id": 20396064, "author_profile": "https://Stackoverflow.com/users/20396064", "pm_score": 1, "selected": false, "text": "import re\nIp_string = \"160.15.20.222\"\nIp_string = Ip_string.split('.')\nIp_String_x =\"\"\nflag = False\nfor num in Ip_string:\n if flag:\n num = re.sub('\\d','x',num)\n Ip_String_x = Ip_String_x + '.'+ num\n else:\n flag = True\n Ip_String_x = num\n" }, { "answer_id": 74287321, "author": "Boseong Choi", "author_id": 7562853, "author_profile": "https://Stackoverflow.com/users/7562853", "pm_score": 1, "selected": false, "text": "import re\n\n\nstrings = [\n '162.1.10.15',\n '160.15.20.222',\n '145.155.222.1',\n]\n\nfor string in strings:\n print(re.sub(r'(?:(?<=\\.)|(?<=\\.\\d)|(?<=\\.\\d\\d))\\d', 'x', string))\n" }, { "answer_id": 74287397, "author": "HelpfulHelper", "author_id": 18155054, "author_profile": "https://Stackoverflow.com/users/18155054", "pm_score": 0, "selected": false, "text": "def replace_ips(ip_list):\n r_list=[]\n for i in ip_list:\n first,*other=i.split(\".\",3)\n r_item=[]\n r_item.append(first)\n for i2 in other:\n r_item.append(\"x\"*len(i2))\n r_list.append(\".\".join(r_item))\n return r_list\n" }, { "answer_id": 74288399, "author": "EVGENY OGRYZKOV", "author_id": 15239072, "author_profile": "https://Stackoverflow.com/users/15239072", "pm_score": 0, "selected": false, "text": "import re\n\nips = ['162.1.10.15', '160.15.20.222', '145.155.222.1']\npattern = r'\\d{1,3}'\nreplacement_sign = 'x'\n\nres = [re.sub(pattern, replacement_sign, ip[::-1], 3)[::-1] for ip in ips]\n\nprint(res)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11502562/" ]
74,287,082
<p>For example,</p> <pre class="lang-cs prettyprint-override"><code> string myString1 = &quot;abcdef&quot;; string myString2; myString2 = myString1.Replace(&quot;a&quot;, &quot;abc&quot;).Replace(&quot;b&quot;, &quot;bcd&quot;); </code></pre> <p>The output will be &quot;abcdcbcdcdef&quot;. I want my output to be &quot;abcbcdcdef&quot;. I know that you could do that with a StringBuilder, but is there a shorter version? I need to do this with a large number of characters (&gt; 100).</p>
[ { "answer_id": 74287155, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 4, "selected": true, "text": "string myString1 = \"abcdef\";\nStringBuilder result = new StringBuilder();\nforeach (char c in myString1)\n{\n if (c == 'a') // if the character is a, append abc\n {\n result.Append(\"abc\");\n }\n else if (c == 'b') // if the character is b, append bcd\n {\n result.Append(\"bcd\");\n }\n else // otherwise append the character verbatim\n {\n result.Append(c);\n }\n}\nstring myString2 = result.ToString(); // produce a string from the StringBuilder\n" }, { "answer_id": 74289217, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "Key" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396023/" ]
74,287,084
<p>I Have created a list box containing list of items and i need to bind them on selection changed(Select and deselect).</p> <p>ABCD.xalm</p> <pre><code>&lt;ListBox Grid.Column=&quot;2&quot; Grid.ColumnSpan=&quot;9&quot; Height=&quot;30&quot; Margin=&quot;0 0 5 0&quot; Foreground=&quot;{StaticResource AcresTheme}&quot; SelectedItem=&quot;{Binding Path=UpdateSimulationItem,UpdateSourceTrigger=PropertyChanged}&quot; ItemsSource=&quot;{Binding SmulationTypes, NotifyOnSourceUpdated=True}&quot; Background=&quot;{Binding }&quot; MinHeight=&quot;65&quot; SelectionMode=&quot;Multiple&quot;&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;CheckBox Foreground=&quot;{StaticResource AcresTheme}&quot; Content=&quot;{Binding Item}&quot; IsChecked=&quot;{Binding Path=IsSelected, Mode=TwoWay}&quot;&gt;&lt;/CheckBox&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;ListBox.ItemContainerStyle&gt; &lt;Style TargetType=&quot;{x:Type ListBoxItem}&quot;&gt; &lt;Setter Property=&quot;IsSelected&quot; Value=&quot;{Binding Mode=TwoWay, Path=IsSelected}&quot;/&gt; &lt;/Style&gt; &lt;/ListBox.ItemContainerStyle&gt; &lt;/ListBox&gt; </code></pre> <p>ABCD.cs (View Model)</p> <pre><code>public List&lt;string&gt; SimulationTypesList { get; set; } = new List&lt;string&gt;(); private ObservableCollection&lt;SimulationType&gt; _simulationTypes = new ObservableCollection&lt;SimulationType&gt;(); public ObservableCollection&lt;Items&gt; SimulationTypes { get { return _simulationTypes; } set { _simulationTypes = value; OnPropertyChanged(&quot;SimulationTypes&quot;); } } private Items _updateSimulationItem; public Items UpdateSimulationItem { get { return _updateSimulationItem; } set { //Logic for getting the selected item _updateSimulationItem = value; OnPropertyChanged(&quot;UpdateSimulationItem&quot;); } } public ABCD() { SimulationTypes.Add(new SimulationType() { Item = &quot;Simulation 1&quot;, IsSelected = false }); SimulationTypes.Add(new SimulationType() { Item = &quot;Simulation 2&quot;, IsSelected = false }); SimulationTypes.Add(new SimulationType() { Item = &quot;Simulation 3&quot;, IsSelected = false }); } </code></pre> <p>Items.cs</p> <pre><code>public class Items: ViewModelBase { private string item; public string Item { get { return item; } set { item = value; this.OnPropertyChanged(&quot;Item&quot;); } } private bool isSelected; public bool IsSelected { get { return isSelected; } set { isSelected = value; this.OnPropertyChanged(&quot;IsSelected&quot;); } } } </code></pre> <p>I did try the solution given in <a href="https://stackoverflow.com/a/34632944/12020323">https://stackoverflow.com/a/34632944/12020323</a> This worked fine for deleting a single item or selecting a single item.</p> <p>When we select the second item it does not trigger the property change.</p>
[ { "answer_id": 74287155, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 4, "selected": true, "text": "string myString1 = \"abcdef\";\nStringBuilder result = new StringBuilder();\nforeach (char c in myString1)\n{\n if (c == 'a') // if the character is a, append abc\n {\n result.Append(\"abc\");\n }\n else if (c == 'b') // if the character is b, append bcd\n {\n result.Append(\"bcd\");\n }\n else // otherwise append the character verbatim\n {\n result.Append(c);\n }\n}\nstring myString2 = result.ToString(); // produce a string from the StringBuilder\n" }, { "answer_id": 74289217, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "Key" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12020323/" ]
74,287,090
<p>I have function written in R.</p> <pre><code>V &lt;- function(c, E, HS, EC_50) E + (1 - E) / (1 + exp(HS * (c - EC_50)) </code></pre> <p>I would like to get the same function in Python but I don't know how. I haven't used Python very much before. Therefore, I am asking for forum help.</p>
[ { "answer_id": 74287155, "author": "ProgrammingLlama", "author_id": 3181933, "author_profile": "https://Stackoverflow.com/users/3181933", "pm_score": 4, "selected": true, "text": "string myString1 = \"abcdef\";\nStringBuilder result = new StringBuilder();\nforeach (char c in myString1)\n{\n if (c == 'a') // if the character is a, append abc\n {\n result.Append(\"abc\");\n }\n else if (c == 'b') // if the character is b, append bcd\n {\n result.Append(\"bcd\");\n }\n else // otherwise append the character verbatim\n {\n result.Append(c);\n }\n}\nstring myString2 = result.ToString(); // produce a string from the StringBuilder\n" }, { "answer_id": 74289217, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "Key" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178136/" ]
74,287,103
<p>So some agency want to know how many users are allowed to get into their system they send me all users that are allowed, now i want match every user with their data, if the user exit in their column then write &quot;TRUE&quot; if not &quot;FALSE&quot;? Thank you.<a href="https://i.stack.imgur.com/vkDzQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vkDzQ.png" alt="enter image description here" /></a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Names</th> <th>Agency1</th> <th>Allowed?</th> </tr> </thead> <tbody> <tr> <td>user565</td> <td>user44</td> <td>FALSE</td> </tr> <tr> <td>user4851</td> <td><em><strong>user4</strong></em></td> <td>TRUE</td> </tr> <tr> <td>user548</td> <td>user3</td> <td>FALSE</td> </tr> <tr> <td><em><strong>user4</strong></em></td> <td>user884</td> <td>FALSE</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74287903, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 2, "selected": false, "text": "MATCH(C2,B$2:B)" }, { "answer_id": 74289394, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": false, "text": "=INDEX(IFNA(MATCH(B2:B5; A2:A5; ))>0)\n" }, { "answer_id": 74289696, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 1, "selected": false, "text": "=ArrayFormula(countif(A2:A5,B2:B5)>0)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20042190/" ]
74,287,115
<p>I m having list of relations, when I select <code>Other</code>, new fields shows <code>AddOther</code>, and when I enter <code>Test</code> into new field, in database i get stored <code>Other</code>, because it takes from the <code>f.select</code>. What should i do to save into database from new field when i choose <code>Other</code> from the list.</p> <pre><code>= f.select(:relationship, ['Father', 'Mother', &quot;Sibling&quot;, &quot;Children&quot;, &quot;Friend&quot;, &quot;Spouse&quot;, &quot;Other&quot;], {}, { :class =&gt; 'form-select RelationshipSelect' }) fieldset class=&quot;form-group&quot; style=&quot;display:none&quot; input#AddOther.mt-4.form-control[type=&quot;text&quot; style=&quot;display:none&quot; placeholder=&quot;Enter other relationship&quot;] $('.RelationshipSelect').change(function() { var v; v = $(this).val(); if (v == 'Other') { $('#AddOther').slideDown(); } else { $('#AddOther').slideUp(); } }); </code></pre> <p>I tried to add <code>AddOther</code> to f.select but no progress. Cant figure it out how to save <code>AddOther</code> into list to be able to save it as <code>Father</code>, <code>Mother</code>....</p>
[ { "answer_id": 74296813, "author": "AndyV", "author_id": 1266795, "author_profile": "https://Stackoverflow.com/users/1266795", "pm_score": 1, "selected": false, "text": "$('#AddOther').on('change', function(){\n relationship = $(this).val();\n $('.RelationshipSelect').append(\"<option value=\\\"\" + relationship + \"\\\">\" + relationship + \"</option>\").val(relationship);\n $(this).slideUp();\n});\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1872074/" ]
74,287,146
<p>I'm trying to access the dictonary inside the jsonfield serializer &quot;assigned_facilities&quot;. But i'm receiving the following error:</p> <pre><code>django.db.utils.IntegrityError: null value in column &quot;assigned_facilities_id&quot; of relation &quot;users_leadfacilityassign&quot; violates not-null constraint DETAIL: Failing row contains (78, null, null, 159). File &quot;/app/users/api/views.py&quot;, line 53, in perform_create serializer.save(agent=self.request.user) File &quot;/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py&quot;, line 205, in save self.instance = self.create(validated_data) File &quot;/app/users/api/serializers.py&quot;, line 252, in create instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime')) </code></pre> <p>I'm basically trying to create a &quot;LeadFacilityAssign&quot; object for each item inside my json so i can have a &quot;LeadFacilityAssign&quot; object for each facility i want to add to a lead.</p> <p>Does anyone know what is causing this error? I tried a few different things but nothing worked so far.</p> <p>json</p> <pre><code>{ &quot;facilities&quot;: [{ &quot;facility_id&quot;: &quot;1&quot;, &quot;datetime&quot;: &quot;2018-12-19 09:26:03.478039&quot; }, { &quot;facility_id&quot;: &quot;1&quot;, &quot;datetime&quot;: &quot;2018-12-19 09:26:03.478039&quot; } ] } </code></pre> <p>serializers.py</p> <pre><code>class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True) class Meta: model = Lead fields = ( &quot;id&quot;, &quot;first_name&quot;, &quot;last_name&quot;, &quot;is_owner&quot;, &quot;assigned_facilities&quot;, ) read_only_fields = (&quot;id&quot;, &quot;is_owner&quot;) def get_is_owner(self, obj): user = self.context[&quot;request&quot;].user return obj.agent == user def create(self, validated_data): assigned_facilities = validated_data.pop(&quot;assigned_facilities&quot;) instance = Lead.objects.create(**validated_data) for facility in assigned_facilities: instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get(&quot;datetime&quot;)) return instance </code></pre> <p>models.py</p> <pre><code>class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f&quot;{self.first_name} {self.last_name}&quot; class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility') lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility') datetime = models.DateTimeField() </code></pre> <p>views.py</p> <pre><code>class LeadCreateView(CreateAPIView): permission_classes = [IsAuthenticated, IsLeadOwner] serializer_class = LeadUpdateSerializer def perform_create(self, serializer): serializer.save(agent=self.request.user) class LeadUpdateView(UpdateAPIView): permission_classes = [IsAuthenticated, IsLeadOwner] serializer_class = LeadUpdateSerializer def get_queryset(self): return Lead.objects.all() </code></pre>
[ { "answer_id": 74289293, "author": "Utkucan Bıyıklı", "author_id": 7437136, "author_profile": "https://Stackoverflow.com/users/7437136", "pm_score": 0, "selected": false, "text": "assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True)" }, { "answer_id": 74364651, "author": "Victor Donoso", "author_id": 14210971, "author_profile": "https://Stackoverflow.com/users/14210971", "pm_score": 1, "selected": false, "text": "class LeadUpdateSerializer(serializers.ModelSerializer):\n is_owner = serializers.SerializerMethodField()\n assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True)\n\n class Meta:\n model = Lead\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"is_owner\",\n \"assigned_facilities\",\n )\n read_only_fields = (\"id\", \"is_owner\")\n" }, { "answer_id": 74389818, "author": "Mahammadhusain kadiwala", "author_id": 19205926, "author_profile": "https://Stackoverflow.com/users/19205926", "pm_score": 0, "selected": false, "text": "instance.leadfacility.create(assigned_facilities_id__id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get(\"datetime\"))\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530084/" ]
74,287,150
<p>I have created a data service on Enterprise Integrator that searches a microsoft sql server database for a usercode, if the usercode I am searching for exists in the db the response is the users first name and last name. Is it possible for the user to get redirected to a c# webpage instead of their first name and last name being returned? I am then calling my data service with my rest api, my intention is to search an microsft sql db and if the data is in the db I should be redirected to a c# webpage. However when I try to test my API I am getting back my json from the Result (Output Mapping) in my query from my data service. I am unsure how to resolve the conflict and any assistance would be greatly appreciated.</p> <p>My Data Service Code:</p> <p>`</p> <pre><code>&lt;data name=&quot;restds&quot; transports=&quot;http https&quot;&gt; &lt;config enableOData=&quot;false&quot; id=&quot;restdb&quot;&gt; &lt;property name=&quot;carbon_datasource_name&quot;&gt;REST&lt;/property&gt; &lt;/config&gt; &lt;query id=&quot;query2&quot; useConfig=&quot;restdb&quot;&gt; &lt;sql&gt;select UserCode,FirstName,LastName from UserDB.dbo.Users where UserCode=?&lt;/sql&gt; &lt;result outputType=&quot;json&quot; useColumnNumbers=&quot;true&quot;&gt; {&amp;#xd;&quot;users&quot;: {&amp;#xd;&quot;user&quot;: [&amp;#xd; {&amp;#xd; &quot;UserCode&quot;: &quot;$1&quot;,&amp;#xd; &quot;FirstName&quot;: &quot;$2&quot;,&amp;#xd; &quot;LastName&quot;: &quot;$3&quot;&amp;#xd; }&amp;#xd; ]&amp;#xd; }&amp;#xd;} &amp;#xd; &amp;#xd; &lt;/result&gt; &lt;param name=&quot;UserCode&quot; optional=&quot;false&quot; sqlType=&quot;STRING&quot;/&gt; &lt;/query&gt; &lt;resource method=&quot;GET&quot; path=&quot;Users&quot;&gt; &lt;call-query href=&quot;query2&quot;&gt; &lt;with-param name=&quot;UserCode&quot; query-param=&quot;UserCode&quot;/&gt; &lt;/call-query&gt; &lt;/resource&gt; &lt;/data&gt; </code></pre> <p>My REST API Code:</p> <pre><code>`&lt;api xmlns=&quot;http://ws.apache.org/ns/synapse&quot; name=&quot;DSAPI2&quot; context=&quot;/dsapi2&quot;&gt; &lt;resource methods=&quot;GET&quot; uri-template=&quot;/{UserCode}&quot;&gt; &lt;inSequence&gt; &lt;call&gt; &lt;endpoint&gt; &lt;http method=&quot;GET&quot; uri-template=&quot;http://localhost:8280/services/restds/Users&quot;/&gt; &lt;/endpoint&gt; &lt;/call&gt; &lt;filter xpath=&quot;$body//FirstName/text() != ''&quot;&gt; &lt;then&gt; &lt;log&gt; &lt;property name=&quot;Message&quot; value=&quot;Name Exists Lets redirect&quot;/&gt; &lt;/log&gt; &lt;property name=&quot;HTTP_SC&quot; value=&quot;302&quot; scope=&quot;axis2&quot; type=&quot;STRING&quot;/&gt; &lt;property name=&quot;Location&quot; value=&quot;https://wso2.com/&quot; scope=&quot;transport&quot; type=&quot;STRING&quot;/&gt; &lt;/then&gt; &lt;else&gt; &lt;log&gt; &lt;property name=&quot;HTTP_SC&quot; value=&quot;302&quot;/&gt; &lt;property name=&quot;Location&quot; value=&quot;https://www.youtube.com/&quot;/&gt; &lt;/log&gt; &lt;/else&gt; &lt;/filter&gt; &lt;respond/&gt; &lt;/inSequence&gt; &lt;outSequence/&gt; &lt;faultSequence/&gt; &lt;/resource&gt; &lt;/api&gt; ` </code></pre> <p>I was expecting to redirect when testing the API, however the response body I am getting is:</p> <pre><code>{ &quot;users&quot;: {} } </code></pre> <p>Which is from the json in my data service</p>
[ { "answer_id": 74289293, "author": "Utkucan Bıyıklı", "author_id": 7437136, "author_profile": "https://Stackoverflow.com/users/7437136", "pm_score": 0, "selected": false, "text": "assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True)" }, { "answer_id": 74364651, "author": "Victor Donoso", "author_id": 14210971, "author_profile": "https://Stackoverflow.com/users/14210971", "pm_score": 1, "selected": false, "text": "class LeadUpdateSerializer(serializers.ModelSerializer):\n is_owner = serializers.SerializerMethodField()\n assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True)\n\n class Meta:\n model = Lead\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"is_owner\",\n \"assigned_facilities\",\n )\n read_only_fields = (\"id\", \"is_owner\")\n" }, { "answer_id": 74389818, "author": "Mahammadhusain kadiwala", "author_id": 19205926, "author_profile": "https://Stackoverflow.com/users/19205926", "pm_score": 0, "selected": false, "text": "instance.leadfacility.create(assigned_facilities_id__id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get(\"datetime\"))\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20220789/" ]
74,287,169
<p>I have 2 tables on MySQL: phy and VM.</p> <p>Here is the phy table:</p> <p><a href="https://i.stack.imgur.com/UJAkq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UJAkq.png" alt="phy table" /></a></p> <p>and here is the VM table:</p> <p><a href="https://i.stack.imgur.com/E2RYC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E2RYC.png" alt="The VM table" /></a></p> <p>I want to get a result like an image below:</p> <p><a href="https://i.stack.imgur.com/u7vzA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u7vzA.png" alt="expected result" /></a></p> <p>I type the command below like this:</p> <pre><code>select ip, name, brand, vm.mem, vm.mem FROM phy JOIN vm ON phy.ip = vm.ip </code></pre> <p>but the result is like this:</p> <p><a href="https://i.stack.imgur.com/kyUaW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kyUaW.png" alt="results obtained" /></a></p> <p>what command do I have to type in order for me to get the result I want?</p>
[ { "answer_id": 74287290, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 3, "selected": true, "text": "SELECT *\nFROM phy\nJOIN vm USING (ip)\n" }, { "answer_id": 74287443, "author": "beyzanur", "author_id": 13137259, "author_profile": "https://Stackoverflow.com/users/13137259", "pm_score": 1, "selected": false, "text": "SELECT phy.id, phy.name, phy.brand, vm.mem, vm.hdd\nFROM phy\nINNER JOIN vm ON phy.id=vm.id;\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12836719/" ]
74,287,240
<p>I have a list where i want to remove all first articles: [&quot;the house&quot;, &quot;the beautiful garten&quot;, &quot;the beautiful garten of the house&quot;]</p> <p>and i want the list to only contain: [&quot;house&quot;, &quot;beautiful garten&quot;, &quot;beautiful garten of the house&quot;]</p> <p>If the first word is an article, then remove. In case the articles appears in the sentence, they should be kept.</p>
[ { "answer_id": 74287344, "author": "frfritz", "author_id": 10636089, "author_profile": "https://Stackoverflow.com/users/10636089", "pm_score": 1, "selected": false, "text": "new_list = [s[4:] if s.startswith('the ') else s for s in old_list]\n" }, { "answer_id": 74288215, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "re" }, { "answer_id": 74288473, "author": "match", "author_id": 9203110, "author_profile": "https://Stackoverflow.com/users/9203110", "pm_score": 0, "selected": false, "text": "articles = [\"the\", \"a\", \"an\"]\n\nsentences = [\"the house\", \"a beautiful garten\", \"an amazing garten of the house\"]\n\n\nout = []\nfor s in sentences:\n new = s\n for a in articles:\n if s.startswith(f'{a} '):\n new = s[len(a)+1:]\n out.append(new)\n\nprint(out)\n\n['house', 'beautiful garten', 'amazing garten of the house']\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20099097/" ]
74,287,252
<p>I would like to change the background color depending on the bluetooth status. When the button is clicked, the text (Bluetooth on) appears in the text view. After the second press of the same button, the text (Bluetooth Off) appears and I wanted to change the background color depending on the text. `</p> <pre><code> switch (Tv.getText().toString()){ case &quot;Bluetooth ON&quot;: layoutleft.setBackgroundResource(R.color.Green); break; case &quot;Bluetooth OFF&quot;: layoutleft.setBackgroundResource(R.color.Red); break; } </code></pre> <p>`</p> <pre><code>&lt;LinearLayout android:id=&quot;@+id/layout&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;413dp&quot; android:layout_below=&quot;@+id/ListView&quot; android:layout_alignParentStart=&quot;true&quot; android:layout_alignParentLeft=&quot;true&quot; android:layout_alignParentEnd=&quot;true&quot; android:layout_alignParentRight=&quot;true&quot; android:layout_alignParentBottom=&quot;true&quot; android:layout_marginStart=&quot;4dp&quot; android:layout_marginLeft=&quot;4dp&quot; android:layout_marginTop=&quot;48dp&quot; android:layout_marginEnd=&quot;277dp&quot; android:layout_marginRight=&quot;277dp&quot; android:layout_marginBottom=&quot;6dp&quot; android:orientation=&quot;horizontal&quot;&gt; </code></pre> <p>I tried to do it like this: (code ) seems to work but doesn't change dynamically until after turning the screen off and on.</p>
[ { "answer_id": 74287344, "author": "frfritz", "author_id": 10636089, "author_profile": "https://Stackoverflow.com/users/10636089", "pm_score": 1, "selected": false, "text": "new_list = [s[4:] if s.startswith('the ') else s for s in old_list]\n" }, { "answer_id": 74288215, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "re" }, { "answer_id": 74288473, "author": "match", "author_id": 9203110, "author_profile": "https://Stackoverflow.com/users/9203110", "pm_score": 0, "selected": false, "text": "articles = [\"the\", \"a\", \"an\"]\n\nsentences = [\"the house\", \"a beautiful garten\", \"an amazing garten of the house\"]\n\n\nout = []\nfor s in sentences:\n new = s\n for a in articles:\n if s.startswith(f'{a} '):\n new = s[len(a)+1:]\n out.append(new)\n\nprint(out)\n\n['house', 'beautiful garten', 'amazing garten of the house']\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13482837/" ]
74,287,285
<p>I've several SAS (PROC SQL) queries using a <code>MIN(startdate)</code> and <code>MAX(enddate)</code>.<br /> To avoid having to calculate these every time I want to do this once at the beginning and store it in a macro variable but I get an error every time.</p> <p>What is going wrong or how to achieve this ?<br /> Thanks in advance for the help !</p> <p><strong>This works:</strong></p> <pre><code>WHERE DATE BETWEEN (SELECT MIN(startdate format yymmddn8. FROM work.mydata) AND (SELECT MAX(enddate format yymmddn8. FROM work.mydata) </code></pre> <p><code>DATE</code> format is <code>YYMMDD8n</code> and length is <code>8</code>.</p> <p><strong>Creating macro variables:</strong></p> <pre><code>PROC SQL; SELECT MIN(startdate), MAX(enddate) INTO :start_date, :end_date FROM work.mydata QUIT; /*Formatting the macro variable:*/ %macro format(value,format); %if %datatyp(&amp;value)=CHAR %THEN %SYSFUNC(PUTC(&amp;value, &amp;format)); %ELSE %LEFT(%QSYSFUNC(PUTN($value,&amp;format))); %MEND format; </code></pre> <p><strong>Tried:</strong></p> <pre><code>WHERE DATE BETWEEN &quot;%format(&amp;start_date, yymmddn8.)&quot; AND &quot;%format(&amp;end_date, yymmddn8.)&quot; </code></pre> <p><strong>Error message:</strong></p> <pre><code>ERROR: Expression using equals (=) has components that are of different data types </code></pre>
[ { "answer_id": 74287344, "author": "frfritz", "author_id": 10636089, "author_profile": "https://Stackoverflow.com/users/10636089", "pm_score": 1, "selected": false, "text": "new_list = [s[4:] if s.startswith('the ') else s for s in old_list]\n" }, { "answer_id": 74288215, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "re" }, { "answer_id": 74288473, "author": "match", "author_id": 9203110, "author_profile": "https://Stackoverflow.com/users/9203110", "pm_score": 0, "selected": false, "text": "articles = [\"the\", \"a\", \"an\"]\n\nsentences = [\"the house\", \"a beautiful garten\", \"an amazing garten of the house\"]\n\n\nout = []\nfor s in sentences:\n new = s\n for a in articles:\n if s.startswith(f'{a} '):\n new = s[len(a)+1:]\n out.append(new)\n\nprint(out)\n\n['house', 'beautiful garten', 'amazing garten of the house']\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439621/" ]
74,287,336
<p>iam trying to call the nest/node api in crafter cms but it is throwing errors</p> <p>1)This is my Groovy controller code</p> <pre><code>import groovy.json.JsonSlurper def apiUrl = &quot;http://localhost:3000/&quot; def json = new URL(apiUrl).text //assuming it's json def object = new JsonSlurper().parseText(json) templateModel.myObject </code></pre> <p>2)This is my ftl code</p> <pre><code>&lt;#import &quot;/templates/system/common/crafter.ftl&quot; as crafter /&gt; &lt;#assign x = contentModel.name_s!&quot;&quot; /&gt; &lt;@crafter.h1&gt;${myObject.x}&lt;@crafter.h1 /&gt; </code></pre> <p>3)after saving the above codes iam getting this error</p> <p><a href="https://i.stack.imgur.com/XQb7f.png" rel="nofollow noreferrer">!(https://i.stack.imgur.com/XQb7f.png)</a></p>
[ { "answer_id": 74289867, "author": "Russ Danner", "author_id": 557925, "author_profile": "https://Stackoverflow.com/users/557925", "pm_score": 1, "selected": false, "text": "<@crafter.h1>${myObject.x}<@crafter.h1 />\n" }, { "answer_id": 74298723, "author": "Mohammed Alaif H", "author_id": 19584239, "author_profile": "https://Stackoverflow.com/users/19584239", "pm_score": 0, "selected": false, "text": "{\n \"_id\": \"632833ecf89459939bd47dd5\",\n \"name\": \"Random Blood Sugar\",\n \"price\": 350,\n \"description\": \"Random Blood SugarTimely screening can help you in avoiding illnesses and with Healthians Random Blood Sugar you can keep a track of your health in the best way because Healthians is India's leading health test @ home service with more than 20 lac satisfied customers across 140+ cities.\",\n \"imgURL\": \"https://i0.wp.com/post.healthline.com/wp-content/uploads/2021/10/blood-test-sample-tube-1296-728-header.jpg?w=1155&h=1528\",\n \"__v\": 0\n },\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19584239/" ]
74,287,345
<p>How can I draw a dynamic family tree So that whenever you add or remove a family member, the tree will paint itself</p> <p>I tried drawing on bitmap but I couldn't draw it Family data in a local database</p>
[ { "answer_id": 74288199, "author": "Axel Kemper", "author_id": 1911064, "author_profile": "https://Stackoverflow.com/users/1911064", "pm_score": 0, "selected": false, "text": "@startwbs\n* Marjory & John I\n** Elena & Tom\n*** John II\n*** Thekla\n** Marion & Mustafa\n@endwbs\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396221/" ]
74,287,377
<p>I try to make a request from the foursquare api. If I change the request URL it does no longer get me a result</p> <p>when I make a request with this line of code everything is fine:</p> <pre class="lang-py prettyprint-override"><code>def venue_details(): detail_results = requests.get('https://api.foursquare.com/v2/venues/4e96cf73b8f7d8c690f48384/?client_id=[my client id]&amp;client_secret=[my client secret]&amp;v=20180604').json() </code></pre> <p>When I make a request with this line of code I get an error:</p> <pre class="lang-py prettyprint-override"><code>`VENUE_ID = '4e96cf73b8f7d8c690f48384' CLIENT_ID = '[my client id]' CLIENT_SECRET = '[my client secret]' VERSION = '20180604' url = 'https://api.foursquare.com/v2/venues/?venue_id={}/?client_id={}&amp;client_secret={}&amp;v={}'.format( VENUE_ID, CLIENT_ID, CLIENT_SECRET, VERSION ) detail_results = requests.get(url).json() </code></pre> <pre><code>{'meta': {'code': 400, 'errorType': 'invalid_auth', 'errorDetail': 'Missing access credentials. See https://developer.foursquare.com/docs/api/configuration/authentication for details.', 'requestId': '63623c5231edc703599dc1da'}, 'response': {}} </code></pre> <p>I think I get the authentication error because it stops reading the url at <code>&quot;?venue_id&quot;</code></p>
[ { "answer_id": 74288199, "author": "Axel Kemper", "author_id": 1911064, "author_profile": "https://Stackoverflow.com/users/1911064", "pm_score": 0, "selected": false, "text": "@startwbs\n* Marjory & John I\n** Elena & Tom\n*** John II\n*** Thekla\n** Marion & Mustafa\n@endwbs\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14142231/" ]
74,287,387
<p>Edited... check Update #1</p> <h2>Description of the issue</h2> <p>I'm working in a form where I have an async validation for a FormControl that is patched by another FormControl.</p> <p>I'm using Angular Material with mat-form-field, mat-input and mat-error.</p> <p>It has two inputs, the first one is to input a business name and it will automatically fill the second input with the slugified version of the name. The second input has an async validation where it checks against the backend if the slug is already in use.</p> <p>The problem is when the user types a business name which its slug is already in use, the form status is &quot;INVALID&quot; (as expected), however it should display the styling of an invalid input on the second FormControl and it doesn't. If I click on the invalid field and click away it shows the FormControl as invalid but I want that behavior without clicking in the second Control.</p> <p><a href="https://i.stack.imgur.com/lsfWH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lsfWH.gif" alt="Error" /></a></p> <h2>Expected behavior</h2> <p>If the user types &quot;Test Name&quot; in the business name. The second FormControl show display the slugified version and the input should has the styling of an invalid control. As soon as the user changes the slugified version to &quot;test-name2&quot; it should be valid and show the normal styling for a valid input.</p> <h2>Example</h2> <p>I've created a Stackblitz where I've set up an example: <a href="https://stackblitz.com/edit/angular-ivy-r9nsk3?file=src/app/app.component.html" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-r9nsk3?file=src/app/app.component.html</a></p> <h2>Update #1</h2> <p>For some reason when I tried to bring the proposed solution into my app it still doesn't work. However I could narrow the cause to an Observable.</p> <p>Before that, let me provide some background. The second FieldControl has an async validator that's called when it changes its value. This validator returns a reference to an Observable which is a property in a Service.</p> <p>To make it easier, I created a method (On the right side of the GIFS) that has the call to the backend (Firebase's Callable Function) (it returns Observable&lt;ValidationErrors | null&gt;) or it returns an Observable created with &quot;of&quot; with an initial value set manually (type Observable&lt;ValidationErrors | null&gt;)</p> <p>Now, let's check both cases: Case #1 (expected behavior): When I type the last letter, it marks the FormControl as &quot;INVALID&quot; instantly, shows the field in red, and shows the mat-error with the error message. <a href="https://i.stack.imgur.com/sx8D8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sx8D8.gif" alt="test1" /></a></p> <p>Case #2 (Current behavior): When I type the last letter, it updates the second field with the slugified version of the first field (as expected). However the FormControl stays in &quot;PENDING&quot; and the input's style doesn't change. <a href="https://i.stack.imgur.com/GMG0S.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMG0S.gif" alt="test2" /></a></p> <p>Finally, I thought the cause was that the Observable didn't finish, but as you can see with the &quot;finalize&quot; operator, both cases display the message confirming that both observables complete.</p>
[ { "answer_id": 74288199, "author": "Axel Kemper", "author_id": 1911064, "author_profile": "https://Stackoverflow.com/users/1911064", "pm_score": 0, "selected": false, "text": "@startwbs\n* Marjory & John I\n** Elena & Tom\n*** John II\n*** Thekla\n** Marion & Mustafa\n@endwbs\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612074/" ]
74,287,389
<p>I've created a macro (using lots of online help) to take data from one sheet, create another sheet, format the data and set up the printer. Everything works as it should but the macro seems to take a long time to run. Would someone be able to look at my code and see if I've done something that I shouldn't?</p> <p>Thanks</p> <pre><code>Sub Preactor_Sort() Application.ScreenUpdating = False '**Copy &quot;Full List&quot; Data into New Sheet** Sheets(&quot;FULL LIST&quot;).Select Range(&quot;A8:R8&quot;).Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Sheets.Add(Before:=Sheets(&quot;MASTER&quot;)).Name = &quot;Sorted Full&quot; Range(&quot;A1&quot;).Select ActiveSheet.Paste ActiveWindow.Zoom = 60 '************************************************** '**Formatting and removing previous conditional formatting** Cells.FormatConditions.Delete Cells.Select With Selection.Font .Name = &quot;Calibri&quot; .Size = 9 .Bold = False .Color = vbBlack End With With Selection .VerticalAlignment = xlCenter .HorizontalAlignment = xlCenter .WrapText = True .Interior.ColorIndex = 0 .RowHeight = 23 End With Cells.EntireColumn.AutoFit '*************************************************** '**Deleting Unwanted Columns** Columns(&quot;E:E&quot;).Select Selection.Cut Columns(&quot;C:C&quot;).Select Selection.Insert Shift:=xlToRight Columns(&quot;A:C&quot;).Select Range(&quot;A1&quot;).Activate Selection.Delete Shift:=xlToLeft '*************************************************** '**Rearranging Columns** Columns(&quot;G:H&quot;).Select Selection.Cut Columns(&quot;B:B&quot;).Select Selection.Insert Shift:=xlToRight Columns(&quot;K:L&quot;).Select Selection.Cut Columns(&quot;E:E&quot;).Select Selection.Insert Shift:=xlToRight '**************************************************** '**Sorting Day/Date** Columns(&quot;C:C&quot;).Select Selection.NumberFormat = &quot;dd/mm/yy hh:mm&quot; Columns(&quot;C:C&quot;).EntireColumn.AutoFit Columns(&quot;C:C&quot;).Select Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove Columns(&quot;C:C&quot;).Select Selection.NumberFormat = &quot;General&quot; '**Find Last Row** LR = Cells.Find(&quot;*&quot;, Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row '**Insert Formula** Range(&quot;C2&quot;).Formula = &quot;=TEXT(D2,&quot;&quot;ddd&quot;&quot;)&quot; '**Drag Formula down to last row** Range(&quot;C2&quot;).AutoFill Range(&quot;C2:C&quot; &amp; LR) Columns(&quot;C:C&quot;).EntireColumn.AutoFit '***************************************************** '**Sorting** With ActiveSheet.Sort .SortFields.Add2 Key:=Range(&quot;C1&quot;), Order:=xlAscending, CustomOrder:=&quot;Mon,Tue,Wed,Thu,Fri,Sat,Sun&quot;, DataOption:=xlSortNormal .SortFields.Add2 Key:=Range(&quot;B1&quot;), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=&quot;Make,Discharge,Packing,Wrapping&quot;, DataOption:=xlSortNormal .SetRange Range(&quot;A:P&quot;) .Header = xlYes .Apply End With '****************************************************** '**Formatting** Range(&quot;C:C,E:E&quot;).Select With Selection .Font.Bold = True End With Columns(&quot;B:B&quot;).Select Selection.ColumnWidth = 10 Columns(&quot;F:G&quot;).Select Selection.ColumnWidth = 25 Columns(&quot;A:A&quot;).Select Selection.ColumnWidth = 8 Columns(&quot;I:J&quot;).Select Selection.ColumnWidth = 5 Columns(&quot;L:N&quot;).Select Selection.ColumnWidth = 15 Columns(&quot;O:O&quot;).Select Selection.ColumnWidth = 80 Columns(&quot;H:H&quot;).Select Selection.ColumnWidth = 40 Columns(&quot;K:K&quot;).Select Selection.ColumnWidth = 6 '**Conditional Formatting** '** Alternating Rows Dim lastRow As Long lastRow = Range(&quot;A1:P1&quot;).End(xlDown).Row For Each cell In Range(&quot;A1:P&quot; &amp; lastRow) If cell.Row Mod 2 = 1 Then cell.Interior.ColorIndex = 34 'Light Blue End If Next cell '**Highlighting Operations Dim cell1 As Range For Each cell1 In Range(&quot;B:B&quot;) If cell1.Value = &quot;Make&quot; Then cell1.Interior.ColorIndex = 35 'Light Green ElseIf cell1.Value = &quot;Discharge&quot; Then cell1.Interior.ColorIndex = 36 'Light Yellow ElseIf cell1.Value = &quot;Packing&quot; Then cell1.Interior.ColorIndex = 19 'Light Cream ElseIf cell1.Value = &quot;Wrapping&quot; Then cell1.Interior.ColorIndex = 6 'Yellow ElseIf cell1.Value = &quot;Boxing&quot; Then cell1.Interior.ColorIndex = 44 'Light Orange ElseIf cell1.Value = &quot;Oil Phase&quot; Then cell1.Interior.ColorIndex = 38 'Pink End If Next '**Highlighting Day Dim cell2 As Range For Each cell2 In Range(&quot;C:C&quot;) If cell2.Value = &quot;Mon&quot; Then cell2.Interior.ColorIndex = 7 'Pink ElseIf cell2.Value = &quot;Tue&quot; Then cell2.Interior.ColorIndex = 4 'Green ElseIf cell2.Value = &quot;Wed&quot; Then cell2.Interior.ColorIndex = 6 'Yellow ElseIf cell2.Value = &quot;Thu&quot; Then cell2.Interior.ColorIndex = 45 'Orange ElseIf cell2.Value = &quot;Fri&quot; Then cell2.Interior.ColorIndex = 33 'Blue End If Next '** Top Bar Colour Range(&quot;A1:P1&quot;).Select With Selection .Interior.ColorIndex = 15 .Font.Bold = True End With '********************************************************* '** Printer Setup Application.PrintCommunication = True With ActiveSheet.PageSetup .PrintTitleRows = &quot;&quot; .PrintTitleColumns = &quot;&quot; End With ActiveSheet.PageSetup.PrintArea = &quot;&quot; With ActiveSheet.PageSetup .LeftMargin = Application.InchesToPoints(0.12) .RightMargin = Application.InchesToPoints(0.12) .TopMargin = Application.InchesToPoints(0.16) .BottomMargin = Application.InchesToPoints(0.16) .HeaderMargin = Application.InchesToPoints(0.12) .FooterMargin = Application.InchesToPoints(0.12) .PrintHeadings = False .PrintGridlines = False .PrintComments = xlPrintNoComments .PrintQuality = 600 .CenterHorizontally = True .CenterVertically = False .Orientation = xlLandscape .Draft = False .PaperSize = xlPaperA3 .FirstPageNumber = xlAutomatic .Order = xlDownThenOver .BlackAndWhite = False .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = False .PrintErrors = xlPrintErrorsDisplayed .OddAndEvenPagesHeaderFooter = False .DifferentFirstPageHeaderFooter = False .ScaleWithDocHeaderFooter = True .AlignMarginsHeaderFooter = True End With ' Application.PrintCommunication = False End Sub </code></pre>
[ { "answer_id": 74288199, "author": "Axel Kemper", "author_id": 1911064, "author_profile": "https://Stackoverflow.com/users/1911064", "pm_score": 0, "selected": false, "text": "@startwbs\n* Marjory & John I\n** Elena & Tom\n*** John II\n*** Thekla\n** Marion & Mustafa\n@endwbs\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396252/" ]
74,287,403
<p>I'm trying to properly reduce scale, formatting a float value and returning it as a String in Swift.</p> <p>For example:</p> <pre><code>let value: Float = 4.8962965 // formattedFalue should be 4.90 or 4,90 based on localization let formattedValue = value.formatNumber() </code></pre> <p>Here is what I did:</p> <pre><code>extension Float { func reduceScale(to places: Int) -&gt; Float { let multiplier = pow(10, Float(places)) let newDecimal = multiplier * self // move the decimal right let truncated = Float(Int(newDecimal)) // drop the fraction let originalDecimal = truncated / multiplier // move the decimal back return originalDecimal } func formatNumber() -&gt; String { let num = abs(self) let numberFormatter = NumberFormatter() numberFormatter.usesGroupingSeparator = true numberFormatter.minimumFractionDigits = 0 numberFormatter.maximumFractionDigits = 2 numberFormatter.roundingMode = .up numberFormatter.numberStyle = .decimal numberFormatter.locale = // we take it from app settings let formatted = num.reduceScale(to: 2) let returningString = numberFormatter.string(from: NSNumber(value: formatted))! return &quot;\(returningString)&quot; } } </code></pre> <p>But when I use this code I get 4.89 (or 4,89 depending on the localization) instead of 4.90 (or 4,90) as I expect.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74287759, "author": "Daniele Citi", "author_id": 7258324, "author_profile": "https://Stackoverflow.com/users/7258324", "pm_score": 1, "selected": false, "text": "reduceScale" }, { "answer_id": 74287785, "author": "JeremyP", "author_id": 169346, "author_profile": "https://Stackoverflow.com/users/169346", "pm_score": 2, "selected": false, "text": "reduceScale(to:)" }, { "answer_id": 74295238, "author": "Jessy", "author_id": 652038, "author_profile": "https://Stackoverflow.com/users/652038", "pm_score": 0, "selected": false, "text": "Foundation" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7258324/" ]
74,287,445
<p>I'm loading data for a page dynamically depending on the data I get from my backend , My code looks like this :</p> <pre><code> return ( &lt;p className=&quot;font-mukta tracking-0.165 text-center lg:text-start text-32px md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug&quot;&gt; {title} &lt;/p&gt; </code></pre> <p>if my title for example is: Lorem Ipsum is simply dummy text of the printing and I want to add a line break after a certain word in that text , for example a line break after the word simply but it's dynamic ,Is there anyway I can force a line break from the string itself for example by adding the html tag <code>&lt;br&gt;</code> or <code>/n</code> in the actual string but that doesn't really work , Any tips ?</p>
[ { "answer_id": 74287759, "author": "Daniele Citi", "author_id": 7258324, "author_profile": "https://Stackoverflow.com/users/7258324", "pm_score": 1, "selected": false, "text": "reduceScale" }, { "answer_id": 74287785, "author": "JeremyP", "author_id": 169346, "author_profile": "https://Stackoverflow.com/users/169346", "pm_score": 2, "selected": false, "text": "reduceScale(to:)" }, { "answer_id": 74295238, "author": "Jessy", "author_id": 652038, "author_profile": "https://Stackoverflow.com/users/652038", "pm_score": 0, "selected": false, "text": "Foundation" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14115760/" ]
74,287,446
<p>so i am trying to imitate googles search page. I want to move the navbar to start on the TOP right. So that would be the 'Image and advanced search' buttons.</p> <p>It always starts top left which I understand. but when I use the 'float:right' inside the CSS it moves to the right, but then drops lower to be inline with the google logo image. I want it to stay top right.</p> <p>I can't post images yet because of my reputation score.</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>.nav { padding: 10px; margin-right: 25px; float: right; } .logo { padding: 20px; margin-top: 100px; margin-left: auto; margin-right: auto; width: 30%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;nav class="nav"&gt; &lt;div class="index"&gt; &lt;a href="image.html"&gt;Images&lt;/a&gt; &lt;/div&gt; &lt;a href="advanced.html"&gt;Advanced search&lt;/a&gt; &lt;/nav&gt; &lt;div class="logo"&gt; &lt;img src="https://placekitten.com/50/50" alt="Google search"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I tried using float: right. It moved the navbar right but also inline with the logo and not top right. I tried using margins</p>
[ { "answer_id": 74287759, "author": "Daniele Citi", "author_id": 7258324, "author_profile": "https://Stackoverflow.com/users/7258324", "pm_score": 1, "selected": false, "text": "reduceScale" }, { "answer_id": 74287785, "author": "JeremyP", "author_id": 169346, "author_profile": "https://Stackoverflow.com/users/169346", "pm_score": 2, "selected": false, "text": "reduceScale(to:)" }, { "answer_id": 74295238, "author": "Jessy", "author_id": 652038, "author_profile": "https://Stackoverflow.com/users/652038", "pm_score": 0, "selected": false, "text": "Foundation" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20338288/" ]
74,287,451
<p>I have 2 api calls which i want to send one after the other. I need a response of the 1st one to send the 2nd api request, but i also need the data from first call. Looks like switchMap is the way to go, atm it looks like this:</p> <pre><code>this.apiCall1().pipe(switchMap(res1 =&gt; this.apiCall2(res.data))).subscribe(res =&gt; ...) </code></pre> <p>but i need to assign the res1.differentData to a variable which seems impossible with switchMap. Or maybe im just missing some syntax.</p>
[ { "answer_id": 74287537, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "apiCall1()" }, { "answer_id": 74287615, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "let res1Stored;\n\nthis\n .apiCall1()\n .pipe(switchMap(res1 => {\n res1Stored = res1.differentData;\n return this.apiCall2(res.data);\n }))\n .subscribe(res => ...)\n" }, { "answer_id": 74287619, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 2, "selected": false, "text": "this.apiCall1().pipe(\n switchMap(res1 => this.apiCall2(res1).pipe(\n map(res2=>({res1:res1,res2:res2})))\n )\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17947665/" ]
74,287,452
<p>The following is an abstraction of my problem and thus does not make too much sense:</p> <p>Given I have a simple utility <code>callMethodIf</code> that's returning the return of another imported method (<code>blackbox</code>).</p> <p>~~/utils/call-method-if.js:</p> <pre class="lang-js prettyprint-override"><code>import { blackbox } from '~~/utils/blackbox'; export const callMethodIf = (condition) =&gt; { return blackbox(condition); }; </code></pre> <p>~~/utils/blackbox.js:</p> <pre class="lang-js prettyprint-override"><code>export const blackbox = (condition) =&gt; { return { called: condition }; }; </code></pre> <p>How would I run one test case which calls the actual implementation of <code>blackbox()</code> and another one where I mock the return value of <code>blackbox()</code>?</p> <p>I tried to do it that way:</p> <pre class="lang-js prettyprint-override"><code>import { describe, expect, it } from 'vitest'; import { callMethodIf } from '~~/utils/call-method-if'; describe('Call method if', () =&gt; { it('returns &quot;called: true&quot; if condition is true', () =&gt; { const result = callMethodIf(true); expect(result).toEqual({ called: true }); }); it('returns mocked blackbox return object', () =&gt; { vi.mock('~~/utils/blackbox', () =&gt; ({ blackbox: vi.fn().mockReturnValue({ mock: true }) })); const result = callMethodIf(false); expect(result).toEqual({ mock: true }); }); }); </code></pre> <p>Both tests work if I run only one of them, but they don't work when combined.</p> <p>Running <code>vi.clearAllMocks()</code> or <code>vi.resetAllMocks()</code> don't help.</p> <p>Defining a global mock and overwriting it in my first test doesn't work either:</p> <pre class="lang-js prettyprint-override"><code>import { describe, expect, it } from 'vitest'; import { callMethodIf } from '~~/utils/call-method-if'; vi.mock('~~/utils/blackbox', () =&gt; ({ blackbox: vi.fn().mockReturnValue({ mock: true }) })); describe('Call method if', () =&gt; { it('returns &quot;called: true&quot; if condition is true', () =&gt; { vi.mock('~~/utils/blackbox', async () =&gt; ({ blackbox: (await vi.importActual('~~/utils/blackbox')).blackbox })); const result = callMethodIf(true); expect(result).toEqual({ called: true }); }); it('returns mocked blackbox return object', () =&gt; { const result = callMethodIf(false); expect(result).toEqual({ mock: true }); }); }); </code></pre>
[ { "answer_id": 74287537, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "apiCall1()" }, { "answer_id": 74287615, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "let res1Stored;\n\nthis\n .apiCall1()\n .pipe(switchMap(res1 => {\n res1Stored = res1.differentData;\n return this.apiCall2(res.data);\n }))\n .subscribe(res => ...)\n" }, { "answer_id": 74287619, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 2, "selected": false, "text": "this.apiCall1().pipe(\n switchMap(res1 => this.apiCall2(res1).pipe(\n map(res2=>({res1:res1,res2:res2})))\n )\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13482004/" ]
74,287,458
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div className="row d-flex"&gt; &lt;div&gt; &lt;h3&gt;Duration&lt;/h3&gt; &lt;/div&gt; &lt;div&gt; &lt;h3&gt;Distance&lt;/h3&gt; &lt;/div&gt; &lt;div&gt; &lt;h3&gt;Back to Center&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The d-flex is not working while other bootstrap classes works properly.i want it to be in horizental line these h3's</p>
[ { "answer_id": 74287537, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "apiCall1()" }, { "answer_id": 74287615, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "let res1Stored;\n\nthis\n .apiCall1()\n .pipe(switchMap(res1 => {\n res1Stored = res1.differentData;\n return this.apiCall2(res.data);\n }))\n .subscribe(res => ...)\n" }, { "answer_id": 74287619, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 2, "selected": false, "text": "this.apiCall1().pipe(\n switchMap(res1 => this.apiCall2(res1).pipe(\n map(res2=>({res1:res1,res2:res2})))\n )\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20394408/" ]
74,287,477
<p>I have been trying with last an hour but not getting solution and failing completely to understand why its showing an error...</p> <p>I have created a function for fetching data,</p> <p>I have placed print statement for seeing what does it returns...here it is printing data but while inside feature builder it showing an error...</p> <p>when I run app its showing output with</p> <pre><code> list&lt;dynamic&gt; is not a subtype of type FutureOr&lt;List&lt;Map&lt;String,dynamic&gt;&gt; </code></pre> <p>it means its executes snapshot.haserror part</p> <p>here is my code</p> <pre><code> class _HomeScreenState extends State&lt;HomeScreen&gt; { Future&lt;List&lt;Map&lt;String,dynamic&gt;&gt;&gt; fetchdata() async { var resp = await http.get(Uri.parse(&quot;https://jsonplaceholder.typicode.com/photos&quot;)); print(&quot;fetchdata function showing&quot;+json.decode(resp.body).toString()); return json.decode(resp.body); } @override void initState() { // TODO: implement initState super.initState(); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: MyBody(), ), ); } MyBody() { return FutureBuilder&lt;List&lt;Map&lt;String,dynamic&gt;&gt;&gt;( future: fetchdata(), builder: (context, snapshot) { print(&quot;Futurebuilder showing:&quot;+snapshot.toString()); switch (snapshot.connectionState) { case ConnectionState.waiting: return Center(child: CircularProgressIndicator()); default: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { print('againt'+snapshot.toString()); List&lt;Map&lt;String,dynamic&gt;&gt; data = snapshot.data ?? []; return ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return Container( padding: EdgeInsets.all(8.0), child: Text(data[index]['title'])); }); } } }, ); }} </code></pre>
[ { "answer_id": 74287537, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 3, "selected": true, "text": "apiCall1()" }, { "answer_id": 74287615, "author": "damonholden", "author_id": 17670742, "author_profile": "https://Stackoverflow.com/users/17670742", "pm_score": 0, "selected": false, "text": "let res1Stored;\n\nthis\n .apiCall1()\n .pipe(switchMap(res1 => {\n res1Stored = res1.differentData;\n return this.apiCall2(res.data);\n }))\n .subscribe(res => ...)\n" }, { "answer_id": 74287619, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 2, "selected": false, "text": "this.apiCall1().pipe(\n switchMap(res1 => this.apiCall2(res1).pipe(\n map(res2=>({res1:res1,res2:res2})))\n )\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18817235/" ]
74,287,493
<p>I am trying to write a program in which one thread writes to a queue and another thread reads from the queue</p> <p>But I am facing an issue regarding accessing the 'queue' in the thread that reads the queue</p> <p>Below is the code which is not compiling</p> <pre><code>use ::std::collections::VecDeque; use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher}; use std::cell::RefCell; use std::path::{Path, PathBuf}; use std::thread; use std::time::Duration; fn main() { //let path = std::env::args() // .nth(1) // .expect(&quot;Argument 1 needs to be a path&quot;); //println!(&quot;watching {}&quot;, path); let path = &quot;c:\\testfolder&quot;; if let Err(e) = watch(path) { println!(&quot;error: {:?}&quot;, e) } } fn process_queue(queue: &amp;VecDeque&lt;String&gt;) -&gt; () {} fn watch&lt;P: AsRef&lt;Path&gt;&gt;(path: P) -&gt; notify::Result&lt;()&gt; { let (tx, rx) = std::sync::mpsc::channel(); // Automatically select the best implementation for your platform. // You can also access each implementation directly e.g. INotifyWatcher. let mut watcher = RecommendedWatcher::new(tx, Config::default())?; // Add a path to be watched. All files and directories at that path and // below will be monitored for changes. let mut queue: VecDeque&lt;String&gt; = VecDeque::new(); thread::spawn(|| { // everything in here runs process_queue(&amp;queue) }); watcher.watch(path.as_ref(), RecursiveMode::Recursive)?; for res in rx { match res { Ok(event) =&gt; { println!(&quot;changed: {:?}&quot;, event.paths); let os_str: String = String::from(event.paths[0].to_str().unwrap()); //let my_str: String = os_str.unwrap().to_str().unwrap(); //let s =os_str.into_os_string(); queue.push_back(os_str); } Err(e) =&gt; println!(&quot;watch error: {:?}&quot;, e), } } Ok(()) } </code></pre> <p>The output from the Rust compiler</p> <pre class="lang-none prettyprint-override"><code>error[E0373]: closure may outlive the current function, but it borrows `queue`, which is owned by the current function --&gt; src\main.rs:43:19 | 43 | thread::spawn(|| { | ^^ may outlive borrowed value `queue` ... 47 | process_queue(&amp;queue) | ----- `queue` is borrowed here | note: function requires argument type to outlive `'static` --&gt; src\main.rs:43:5 | 43 | / thread::spawn(|| { 44 | | 45 | | // everything in here runs 46 | | 47 | | process_queue(&amp;queue) 48 | | 49 | | }); | |______^ help: to force the closure to take ownership of `queue` (and any other referenced variables), use the `move` keyword | 43 | thread::spawn(move || { | ++++ error[E0502]: cannot borrow `queue` as mutable because it is also borrowed as immutable --&gt; src\main.rs:63:17 | 43 | thread::spawn(|| { | - -- immutable borrow occurs here | _____| | | 44 | | 45 | | // everything in here runs 46 | | 47 | | process_queue(&amp;queue) | | ----- first borrow occurs due to use of `queue` in closure 48 | | 49 | | }); | |______- argument requires that `queue` is borrowed for `'static` ... 63 | queue.push_back(os_str); | ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here </code></pre> <p>From the errors I understand that the compiler does not allow both mutable and immutable references at the same time.</p> <p>But I don't know how to implement what I am trying to do with these restrictions.</p>
[ { "answer_id": 74287725, "author": "Ferdinand Keller", "author_id": 13223443, "author_profile": "https://Stackoverflow.com/users/13223443", "pm_score": -1, "selected": false, "text": "Arc" }, { "answer_id": 74290948, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Box" }, { "answer_id": 74298501, "author": "mjk6035", "author_id": 1213289, "author_profile": "https://Stackoverflow.com/users/1213289", "pm_score": 0, "selected": false, "text": "use std::thread;\nuse std::time::Duration;\nuse notify::{RecommendedWatcher, RecursiveMode, Watcher, Config};\nuse std::path::Path;\nuse std::path::PathBuf;\n\n\n//\nfn main() {\n \n \n //let path = std::env::args()\n // .nth(1)\n // .expect(\"Argument 1 needs to be a path\");\n //println!(\"watching {}\", path);\n let path=\"c:\\\\testfolder\"; \n\n if let Err(e) = watch(path) {\n println!(\"error: {:?}\", e)\n }\n \n}\n\n\n\n\n\nfn watch<P: AsRef<Path>>(path: P) -> notify::Result<()> {\n let (tx, rx) = std::sync::mpsc::channel(); \n \n // Automatically select the best implementation for your platform.\n // You can also access each implementation directly e.g. INotifyWatcher.\n let mut watcher = RecommendedWatcher::new(tx, Config::default())?;\n\n // Add a path to be watched. All files and directories at that path and\n // below will be monitored for changes.\n \n let handle=thread::spawn(move || {\n\n // everything in here runs \n \n for res in rx {\n match res {\n Ok(event) =>{\n \n // println!(\"changed: {:?}\", event.paths); \n let os_str:String = String::from(event.paths[0].to_str().unwrap());\n println!(\"file name: {}\", os_str); \n \n },\n Err(e) => println!(\"watch error: {:?}\", e),\n }\n }\n \n }); \n\n watcher.watch(path.as_ref(), RecursiveMode::Recursive)?; \n handle.join(); \n\n Ok(())\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1213289/" ]
74,287,606
<p>From the dataframe, unique values are taken in &quot;Region&quot; and would like to extract the &quot;Name&quot; However, when one Name is in Region, it spells out the name (l-i-n-d-a instead of linda)</p> <pre><code> import pandas as pd data = { 'Region': ['South','West', 'North','West', 'North', 'South','West', 'North', 'East'], 'Name': ['Tom', 'nick', 'krish', 'jack','peter','sam','jon','megan','linda'] } df = pd.DataFrame(data) list_region = df['Region'].unique().tolist() for region in list_region: list_person = df.set_index('Region').loc[region, 'Name'] for person in list_person: print(region + ' &gt;&gt; ' + person) </code></pre> <p>partial output as below, linda was spelled out</p> <pre><code>North &gt;&gt; megan East &gt;&gt; l East &gt;&gt; i East &gt;&gt; n East &gt;&gt; d East &gt;&gt; a </code></pre>
[ { "answer_id": 74287725, "author": "Ferdinand Keller", "author_id": 13223443, "author_profile": "https://Stackoverflow.com/users/13223443", "pm_score": -1, "selected": false, "text": "Arc" }, { "answer_id": 74290948, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 0, "selected": false, "text": "Box" }, { "answer_id": 74298501, "author": "mjk6035", "author_id": 1213289, "author_profile": "https://Stackoverflow.com/users/1213289", "pm_score": 0, "selected": false, "text": "use std::thread;\nuse std::time::Duration;\nuse notify::{RecommendedWatcher, RecursiveMode, Watcher, Config};\nuse std::path::Path;\nuse std::path::PathBuf;\n\n\n//\nfn main() {\n \n \n //let path = std::env::args()\n // .nth(1)\n // .expect(\"Argument 1 needs to be a path\");\n //println!(\"watching {}\", path);\n let path=\"c:\\\\testfolder\"; \n\n if let Err(e) = watch(path) {\n println!(\"error: {:?}\", e)\n }\n \n}\n\n\n\n\n\nfn watch<P: AsRef<Path>>(path: P) -> notify::Result<()> {\n let (tx, rx) = std::sync::mpsc::channel(); \n \n // Automatically select the best implementation for your platform.\n // You can also access each implementation directly e.g. INotifyWatcher.\n let mut watcher = RecommendedWatcher::new(tx, Config::default())?;\n\n // Add a path to be watched. All files and directories at that path and\n // below will be monitored for changes.\n \n let handle=thread::spawn(move || {\n\n // everything in here runs \n \n for res in rx {\n match res {\n Ok(event) =>{\n \n // println!(\"changed: {:?}\", event.paths); \n let os_str:String = String::from(event.paths[0].to_str().unwrap());\n println!(\"file name: {}\", os_str); \n \n },\n Err(e) => println!(\"watch error: {:?}\", e),\n }\n }\n \n }); \n\n watcher.watch(path.as_ref(), RecursiveMode::Recursive)?; \n handle.join(); \n\n Ok(())\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396393/" ]
74,287,632
<p>I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function.</p> <p>Now I need to change all the class details of the success_url, for instance from:</p> <pre><code>reverse_lazy('login') </code></pre> <p>to:</p> <pre><code>reverse_lazy('accounts:login') </code></pre> <p>but overwriting the original urls.py is not a good practice. I'm a python beginner and struggling with this problem already for a month..</p> <p>how can I achieve this?</p> <p>What I attemptd was making subclasses in my views inherent from each of the class in django.contrib.auth.views.</p> <p>I even tried putting try/except method with except 'NoReverseMatch:' but the function itself did not exist.</p>
[ { "answer_id": 74288871, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 0, "selected": false, "text": "LOGIN_URL" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20372074/" ]
74,287,658
<p>I wanted to copy some data from one Rails server (same application, different DB) to another... for various reasons I chose to experiment with a hacky method in the console: <code>Marshal.dump(MyModel.all)</code> on one server and <code>File.open ... { |f| Marshal.load(f).each(&amp;:save!) }</code> in the other.</p> <p>I was suprised (seemed too good to be true) to see that the latter resulted in <code>[true, true, true...]</code> which made me think the records were saved. However, there was no change to the DB.</p> <p>I had to use <code>Marshal.load(f).map { |x| MyModel.new(x.attributes) }.each(&amp;:save!)</code>. This did write the records to the DB.</p> <p>I'm guessing there is something I don't understand about <code>Marshal.load</code>; why is it that I had to create a new instance of ostensibly the same class in order to actually save the records? Since I did get <code>true</code> back from each call to <code>save!</code>, what was actually happening there?</p>
[ { "answer_id": 74289189, "author": "Konstantin Strukov", "author_id": 8008340, "author_profile": "https://Stackoverflow.com/users/8008340", "pm_score": 0, "selected": false, "text": "save!" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160604/" ]
74,287,677
<p>Example data</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>Gender</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>F</td> <td>22</td> </tr> <tr> <td>2</td> <td>Fem</td> <td>18</td> </tr> <tr> <td>3</td> <td>male</td> <td>45</td> </tr> <tr> <td>4</td> <td>She/Her</td> <td>30</td> </tr> <tr> <td>5</td> <td>Male</td> <td>25</td> </tr> <tr> <td>6</td> <td>Non-bianary</td> <td>26</td> </tr> <tr> <td>7</td> <td>M</td> <td>18</td> </tr> <tr> <td>8</td> <td>female</td> <td>20</td> </tr> <tr> <td>9</td> <td>Male</td> <td>56</td> </tr> </tbody> </table> </div> <p>I want to be able to standardise this somewhat by replacing all cells with an 'F' in them with 'Female', and all cells with 'M' in them with 'Male'. I know the first step is to cast the whole column into capitals</p> <pre><code>df.Gender = df.Gender.str.capitalize() </code></pre> <p>and I know that I can do it value-by-value with</p> <pre><code>df['Gender'] = df['Gender'].replace(['F', 'Fem', 'Female'], 'Female') </code></pre> <p>but is there a way to do this somewhat programmatically?</p> <p>such as</p> <pre><code>df.Gender = df.Gender.str.capitalise() for i in df.Gender: if 'F' in str(i): #pd.replace call something like... df[df.Gender == i] = 'Female' #I know that line is very wrong elif 'M' in str(i)... </code></pre>
[ { "answer_id": 74287760, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "import re\n\ndf[\"Gender\"] = df[\"Gender\"].str.replace(\n r\"^F\\S*$\", \"Female\", flags=re.I, regex=True\n)\nprint(df)\n" }, { "answer_id": 74288210, "author": "Omar", "author_id": 9289463, "author_profile": "https://Stackoverflow.com/users/9289463", "pm_score": 1, "selected": false, "text": "for indx, row in df.iterrows:\n if row[\"Gender\"] == \"F\": #Or other conditions\n df.loc[index,\"Gender\"] = \"Female\"\n else:\n pass #or whatever condition u want to add\n" }, { "answer_id": 74289137, "author": "jkhadka", "author_id": 5516267, "author_profile": "https://Stackoverflow.com/users/5516267", "pm_score": 1, "selected": false, "text": "df['Gender'][df['Gender'].isin(['F', 'Fem', 'Female'])] = 'Female'\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10992997/" ]
74,287,685
<p>I have a code that makes extensive use of a type, let say, for simplicity:</p> <pre><code>type, public :: my_type real, allocatable, dimension(:) :: x real, allocatable, dimension(:,:) :: coeffs end type my_type ... type(my_type) :: data </code></pre> <p>Later in the code, we need to write <code>data%x</code> and <code>data%coeffs</code> to a file. Whether the user wants it or not, this file could be written in a standard unformatted binary file and recently we add the possibility to write the file in HDF5 format.</p> <p>In this case, when creating the data sets for <code>data%x</code> or <code>data%coeffs</code>, I need to pass a pointer, pointing on them, as argument to some hdf5 subroutines. This pointer can be defined as follow:</p> <pre><code>f_ptr = c_loc( data%x(1) ) </code></pre> <p>But to do that, I should have given the target attribute to <code>x</code> and <code>coeffs</code> in <code>my_type</code> definition.</p> <p>My questions are then:</p> <ul> <li>is it safe to give this target attribute, just in case, even if, in the end, the user does not want to use HDF5 format ?</li> <li>Would it have an impact on performance ?</li> <li>Would it be better to make, in the routine that writes the data, a local copy of <code>data%x</code> and <code>data%coeffs</code> to same shape arrays with the target attribute and then point at them and pass the pointer to hdf5 subroutines ?</li> </ul> <p>If it helps, this code can be compiled either with <code>gfortran</code> or <code>ifort</code>.</p> <p>Thanks in advance !</p>
[ { "answer_id": 74287760, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "import re\n\ndf[\"Gender\"] = df[\"Gender\"].str.replace(\n r\"^F\\S*$\", \"Female\", flags=re.I, regex=True\n)\nprint(df)\n" }, { "answer_id": 74288210, "author": "Omar", "author_id": 9289463, "author_profile": "https://Stackoverflow.com/users/9289463", "pm_score": 1, "selected": false, "text": "for indx, row in df.iterrows:\n if row[\"Gender\"] == \"F\": #Or other conditions\n df.loc[index,\"Gender\"] = \"Female\"\n else:\n pass #or whatever condition u want to add\n" }, { "answer_id": 74289137, "author": "jkhadka", "author_id": 5516267, "author_profile": "https://Stackoverflow.com/users/5516267", "pm_score": 1, "selected": false, "text": "df['Gender'][df['Gender'].isin(['F', 'Fem', 'Female'])] = 'Female'\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7316986/" ]
74,287,697
<p>Ive got a little issue while coding a script that takes a CSV string and is supposed to select a column name and value based on the input. The CSV string contains Names of NBA players, their Universities etc. Now when the input is &quot;name&quot; &amp;&amp; &quot;Andre Brown&quot;, it should search for those values in the given CSV string. I have a rough code laid out - but I am unsure on how to implement the where method. Any ideas?</p> <pre><code>import csv import pandas as pd import io class MySelectQuery: def __init__(self, table, columns, where): self.table = table self.columns = columns self.where = where def __str__(self): return f&quot;SELECT {self.columns} FROM {self.table} WHERE {self.where}&quot; csvString = &quot;name,year_start,year_end,position,height,weight,birth_date,college\nAlaa Abdelnaby,1991,1995,F-C,6-10,240,'June 24, 1968',Duke University\nZaid Abdul-Aziz,1969,1978,C-F,6-9,235,'April 7, 1946',Iowa State University\nKareem Abdul-Jabbar,1970,1989,C,7-2,225,'April 16, 1947','University of California, Los Angeles\nMahmoud Abdul-Rauf,1991,2001,G,6-1,162,'March 9, 1969',Louisiana State University\n&quot; df = pd.read_csv(io.StringIO(csvString), error_bad_lines=False) where = &quot;name = 'Alaa Abdelnaby' AND year_start = 1991&quot; df = df.query(where) print(df) </code></pre> <p>The CSV string is being transformed into a pandas Dataframe, which should then find the values based on the input - however I get the error &quot;name 'where' not defined&quot;. I believe everything until the df = etc. part is correct, now I need help implementing the where method. (Ive seen one other solution on SO but wasnt able to understand or figure that out)</p>
[ { "answer_id": 74287760, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "import re\n\ndf[\"Gender\"] = df[\"Gender\"].str.replace(\n r\"^F\\S*$\", \"Female\", flags=re.I, regex=True\n)\nprint(df)\n" }, { "answer_id": 74288210, "author": "Omar", "author_id": 9289463, "author_profile": "https://Stackoverflow.com/users/9289463", "pm_score": 1, "selected": false, "text": "for indx, row in df.iterrows:\n if row[\"Gender\"] == \"F\": #Or other conditions\n df.loc[index,\"Gender\"] = \"Female\"\n else:\n pass #or whatever condition u want to add\n" }, { "answer_id": 74289137, "author": "jkhadka", "author_id": 5516267, "author_profile": "https://Stackoverflow.com/users/5516267", "pm_score": 1, "selected": false, "text": "df['Gender'][df['Gender'].isin(['F', 'Fem', 'Female'])] = 'Female'\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20271049/" ]
74,287,718
<p>I'm looking for a tool that could help me to do the following operation:</p> <p>Given that code:</p> <pre><code>const before = (arg1: string, arg2: string) =&gt; null; </code></pre> <p>I would like to have the following result:</p> <pre><code>const after = ({ arg1, arg2 }: { arg1: string; arg2: string }) =&gt; null; </code></pre> <p>Is it possible to do that with a snippet ? (for exemple, i select my args and it directly transform them)</p>
[ { "answer_id": 74288810, "author": "rioV8", "author_id": 9938317, "author_profile": "https://Stackoverflow.com/users/9938317", "pm_score": 2, "selected": true, "text": " \"Convert Arguments\": {\n \"prefix\": \"conarg\",\n \"body\": [\n \"{ ${TM_SELECTED_TEXT/(\\\\w+):[^,]*(,\\\\s*)?/$1$2/g} }: { ${TM_SELECTED_TEXT/,/;/g}}\"\n ],\n \"description\": \"Convert Arguments\"\n }\n" }, { "answer_id": 74288892, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": " {\n \"label\": \"vueconv\",\n \"type\": \"shell\",\n \"command\": \"tsx scripts/vueconv ${file}\",\n \"problemMatcher\": [],\n \"presentation\": {\n \"echo\": true,\n \"reveal\": \"always\",\n \"focus\": true,\n \"panel\": \"shared\",\n \"showReuseMessage\": false,\n \"clear\": true\n }\n },\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20242416/" ]
74,287,719
<p>I'm working with node and mongo 5.0 . I have a preexisting record that I want to add 2 fields to. I am trying to insert 2 numbers (due, assessed) into the fields Owed and Yearly. These 2 fields do not currently exist within each record. I tried multiple variations including:</p> <pre><code> await collection.updateOne({ _id: record._id }, { $set: [{ &quot;Owed&quot;: due}, {&quot;Yearly&quot;: assessed }]}); </code></pre> <p>which gives:</p> <pre><code>'MongoServerError: Modifiers operate on fields but we found type array instead. For example: {$mod: {&lt;field&gt;: ...}} not {$set: [ { Owed: 0 }, { Yearly: 466.64 } ]}\n </code></pre> <p>How to I add multiple fields to a record here?</p> <p>Edit:</p> <p>I changed my code to yours. Now I am seeing:</p> <pre><code>MongoServerError: Modifiers operate on fields but we found type array instead. For example: {$mod: {&lt;field&gt;: ...}} not {$set: [ { Owed: 0 }, { Yearly: 466.64 } ]} </code></pre> <p>Any thoughts?</p>
[ { "answer_id": 74289902, "author": "Vivek Rahul", "author_id": 19554161, "author_profile": "https://Stackoverflow.com/users/19554161", "pm_score": 1, "selected": false, "text": "upsert" }, { "answer_id": 74308723, "author": "user1592380", "author_id": 1592380, "author_profile": "https://Stackoverflow.com/users/1592380", "pm_score": 0, "selected": false, "text": "await collection.updateOne({ _id: record._id }, { $set: { \"Owed\": due, \"Yearly\": assessed }});\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1592380/" ]
74,287,731
<p>In detail, I want the key of Map to be the date and time, and the value to be Map(person's name -&gt; the maximum value taken by that person on that date and time). How can I do this?</p> <pre><code>val d = Map(2020-01-30 -&gt; Seq(Map(&quot;fff&quot; -&gt; 177), Map(&quot;fsdzf&quot; -&gt; 219), Map(&quot;fff&quot; -&gt; 300), Map(&quot;fff&quot; -&gt; 0)), 2020-01-26 -&gt; Seq(Map(&quot;fvcfdf&quot; -&gt; 188), Map(&quot;vav&quot; -&gt; 273))) </code></pre> <p>TI want the code above to look like the code below.</p> <pre><code>Map(2020-01-30 -&gt; Map(fff -&gt; 300, fsdzf -&gt; 219), 2020-01-26 -&gt; Map(fvcfdf -&gt; 188, vav -&gt; 273)) </code></pre>
[ { "answer_id": 74289470, "author": "AminMal", "author_id": 14672383, "author_profile": "https://Stackoverflow.com/users/14672383", "pm_score": 1, "selected": false, "text": "\"values\"" }, { "answer_id": 74289964, "author": "Dima", "author_id": 4254517, "author_profile": "https://Stackoverflow.com/users/4254517", "pm_score": 3, "selected": true, "text": " originalMap\n .view\n .mapValues(_.flatten)\n .mapValues(_.groupMapReduce(_._1)(_._2)(_ max _))\n .toMap\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396543/" ]
74,287,736
<p>I am performing Head call as below using http:</p> <pre><code>Future&lt;void&gt; fetchModifiedDate(String fileUrl,BuildContext context) async{ if (await checkNetworkConnection(context)) { var responseValue = []; var response = http.head(Uri.parse(fileUrl)); response.then((value) { responseValue = value.headers.values.toString().split(&quot;,&quot;); modifiedDate = responseValue[1].trim(); print(value.headers.toString()); print(value.headers.values.toString()); }); } </code></pre> <p>The values which I am getting from Header is as below :</p> <ol> <li>For print(value.hedaers.toString()),</li> </ol> <blockquote> <p>{x-served-by: psm100.akshar-dev.ml, connection: keep-alive, last-modified: Thu, 13 Oct 2022 00:09:35 GMT, accept-ranges: bytes, date: Wed, 02 Nov 2022 10:24:35 GMT, content-length: 69910, etag: &quot;6347573f-11116&quot;, content-type: application/json, server: openresty}</p> </blockquote> <ol start="2"> <li>For print(value.headers.values.toString()),</li> </ol> <blockquote> <p>(psm100.akshar-dev.ml, keep-alive, Thu, 13 Oct 2022 00:09:35 GMT, ..., application/json, openresty)</p> </blockquote> <p>I want specific header value i.e. The value for <strong>last-modified</strong> key. How can I get it?</p>
[ { "answer_id": 74287883, "author": "Jeet Raval", "author_id": 5705996, "author_profile": "https://Stackoverflow.com/users/5705996", "pm_score": 3, "selected": true, "text": "value.hedaers['last-modified']\n" }, { "answer_id": 74287934, "author": "amit.flutter", "author_id": 13078639, "author_profile": "https://Stackoverflow.com/users/13078639", "pm_score": 0, "selected": false, "text": "if (response.statusCode == 200) {\n return Album.fromJson(jsonDecode(response.body));\n} else {\n throw Exception('Failed to load album');\n}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4827817/" ]
74,287,742
<p>I am using below SQL in java code to update date in Oracle DB.</p> <pre><code>UPDATE CUS_LOGS SET START_DATE=to_date(systimestamp + 3,'DD-MON-RRRR'), END_DATE=to_date(systimestamp + 21921,'DD-MON-RRRR') WHERE CUS_ID IN ('9b90cb8175ba0ca60175ba12d8711006'); </code></pre> <p>My expectation is:</p> <pre><code>START_DATE = 05-NOV-2022 END_DATE = 08-NOV-2082. </code></pre> <p>However the result I see as</p> <pre><code>START_DATE = 05-NOV-2022 END_DATE = 08-NOV-1982 ********** </code></pre> <p>Apparently issue happens when the date pass <code>31-12-2049</code>. i.e. adding <code>+ 9922</code> as of today (02/11/2022)</p>
[ { "answer_id": 74287982, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 3, "selected": true, "text": "DD-MON-RR" }, { "answer_id": 74288396, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "UPDATE CUS_LOGS\nSET START_DATE = TRUNC(SYSDATE) + INTERVAL '3' DAY,\n END_DATE = ADD_MONTHS(TRUNC(SYSDATE), 60*12) + INTERVAL '6' DAY \nWHERE CUS_ID = '9b90cb8175ba0ca60175ba12d8711006';\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2303693/" ]
74,287,797
<p>Given a type of Map, for example:</p> <pre><code>type Foo = Map&lt;string, number&gt;; </code></pre> <p>Is there a way to then get the type that was used for the <code>key</code> and for the <code>value</code>?</p>
[ { "answer_id": 74287879, "author": "limdev", "author_id": 10753732, "author_profile": "https://Stackoverflow.com/users/10753732", "pm_score": 2, "selected": false, "text": "type Foo = Map<string, number>;\n\ntype Key = Parameters<Foo[\"set\"]>[0];\ntype Value = Parameters<Foo[\"set\"]>[1];\n" }, { "answer_id": 74288066, "author": "Garuno", "author_id": 5625089, "author_profile": "https://Stackoverflow.com/users/5625089", "pm_score": 4, "selected": true, "text": "type Foo = Map<string, number>;\n\ntype MapKey<T> = T extends Map<infer K, any> ? K : never;\ntype MapValue<T> = T extends Map<any, infer V> ? V : never;\n\ntype FooKey = MapKey<Foo>\ntype FooValue = MapValue<Foo>\n\n// Or if you just need it for the current case:\n\ntype FooKey2 = Foo extends Map<infer K, any> ? K : never;\ntype FooValue2 = Foo extends Map<any, infer V> ? V : never;\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6251097/" ]
74,287,812
<p>Is there a way to simplify this block of <code>if</code> statements?</p> <pre><code> if ro&lt;=1: F=1.23 elif 1&lt;ro&lt;=1.05: F=1.24 elif 1.05&lt;ro&lt;=1.1: F=1.25 elif 1.1&lt;ro&lt;=1.12: F=1.26 elif 1.12&lt;ro&lt;=1.16: F=1.27 elif 1.16&lt;ro&lt;=1.19: F=1.28 elif 1.19&lt;ro&lt;=1.21: F=1.29 elif 1.21&lt;ro&lt;=1.24: F=1.3 elif 1.24&lt;ro&lt;=1.28: F=1.31 elif 1.28&lt;ro&lt;=1.32: F=1.32 elif 1.32&lt;ro&lt;=1.37: F=1.34 elif 1.37&lt;ro&lt;=1.43: F=1.35 elif 1.43&lt;ro&lt;=1.51: F=1.37 elif 1.51&lt;ro&lt;=1.62: F=1.39 elif 1.62&lt;ro&lt;=1.78: F=1.42 elif 1.78&lt;ro&lt;=2.06: F=1.45 elif 2.06&lt;ro&lt;=2.74: F=1.49 </code></pre>
[ { "answer_id": 74287940, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 0, "selected": false, "text": "ranges = {\n (0.0, 1.0): 1.23,\n (1.0, 1.05): 1.24,\n (1.05, 1.1): 1.25,\n (1.1, 1.12): 1.26,\n (1.12, 1.16): 1.27,\n (1.16, 1.19): 1.28,\n (1.19, 1.21): 1.29,\n (1.21, 1.24): 1.3,\n (1.24, 1.28): 1.31,\n (1.28, 1.32): 1.32,\n (1.32, 1.37): 1.34,\n (1.37, 1.43): 1.35,\n (1.43, 1.51): 1.37,\n (1.51, 1.62): 1.39,\n (1.62, 1.78): 1.42,\n (1.78, 2.06): 1.45,\n (2.06, 1.74): 1.49 # note: this range doesn't make sense\n}\n\nfor (low, high), f_value in ranges.items():\n if low < ro <= high:\n F = f_value\n" }, { "answer_id": 74287984, "author": "Boseong Choi", "author_id": 7562853, "author_profile": "https://Stackoverflow.com/users/7562853", "pm_score": 3, "selected": true, "text": "<" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8081903/" ]
74,287,826
<p>I need to write a function combineArray(arr1, arr2), which takes 2 arrays, and returns a new array consisting only of numeric elements of arrays arr1 and arr2. For example:</p> <pre><code> combineArray([12, &quot;User01&quot;, 22, true, -8], [&quot;Index&quot;, 6, null, 15])); result --&gt; [12, 22, -8, 6, 15] </code></pre> <p>I tried to do it like this:</p> <pre><code>function combineArray(arr1, arr2) { let numArr = []; let newArr = arr1.concat(arr2); for(let i = 0; i &lt; newArr.lenght; i++){ if(typeof newArr[i] == &quot;number&quot;) numArr.push(newArr[i]); } return numArr } let result = combineArray([12, &quot;User01&quot;, 22, true, -8], [&quot;Index&quot;, 6, null, 15]) console.log(result) </code></pre> <p>But my function returns empty array.</p>
[ { "answer_id": 74287897, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "function returnNums(arr1, arr2) {\n let numArr = []\n for (const val of arr1) {\n if (typeof val === 'number') numArr.push(val)\n }\n for (const val of arr2) {\n if (typeof val === 'number') numArr.push(val)\n }\n return numArr;\n}\n\nconsole.log(returnNums([1, 2, 'a'], [3, 4, 'b']))" }, { "answer_id": 74287912, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 2, "selected": false, "text": "length" }, { "answer_id": 74287927, "author": "l2aelba", "author_id": 622813, "author_profile": "https://Stackoverflow.com/users/622813", "pm_score": 1, "selected": false, "text": "const a = [12, 'User01', 22, true, -8]\nconst b = ['Index', 6, null, 15]\n\n// Merge arrays by [...a, ...b] then filter it\nconst result = [...a, ...b].filter(v => typeof v === 'number')\n// Or using concat\nconst result = a.concat(b).filter(v => typeof v === 'number')\n" }, { "answer_id": 74288002, "author": "MUKILAN K", "author_id": 15624830, "author_profile": "https://Stackoverflow.com/users/15624830", "pm_score": -1, "selected": false, "text": "for(let i = 0; i < newArr.length; i++){\n" }, { "answer_id": 74288249, "author": "R4ncid", "author_id": 14326899, "author_profile": "https://Stackoverflow.com/users/14326899", "pm_score": 0, "selected": false, "text": "const combine = type => (...arrays) => arrays.flat().filter(v => typeof v === type )\n\nconst combineNumers = combine('number')\nconst combineStrings = combine('string')\n\nlet resultNumber = combineNumers([12, \"User01\", 22, true, -8], [\"Index\", 6, null, 15])\nconsole.log(resultNumber)\n\nlet resultString = combineStrings([12, \"User01\", 22, true, -8], [\"Index\", 6, null, 15])\nconsole.log(resultString)" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178852/" ]
74,287,837
<p>I need a text after a keyword</p> <p>My text file like this. I am trying to extract the car info, car model, and append in to the python dict.</p> <pre class="lang-none prettyprint-override"><code># car name BMW suzuki # car model X1 TT # color red blue </code></pre> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>keywords = [car_name,car_model,color] parsed_content = {} def car_info(text): content = {} indices = [] keys = [] for key in Keywords: try: content[key] = text[text.index(key) + len(key):] indices.append(text.index(key)) keys.append(key) except: pass zipped_lists = zip(indices, keys) sorted_pairs = sorted(zipped_lists) # sorted_pairs tuples = zip(*sorted_pairs) indices, keys = [ list(tuple) for tuple in tuples] # return keys print(keys) content = [] for idx in range(len(indices)): if idx != len(indices)-1: content.append(text[indices[idx]: indices[idx+1]]) else: content.append(text[indices[idx]: ]) for i in range(len(indices)): parsed_content[keys[i]] = content[i] return parsed_content </code></pre> <p>my output is</p> <pre class="lang-none prettyprint-override"><code>parsed_content = {car_name : car_name BMW SUZUKI, car_model : car_model x1 tt, color : color red blue } </code></pre> <p>Expected output:</p> <pre><code>{'car_name': ['bmw', 'suzuki'], 'car_model': ['x1', 'TT'], 'color': ['red', 'blue'] } </code></pre>
[ { "answer_id": 74288052, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 2, "selected": false, "text": "from collections import defaultdict\n\ndef car_info(filename):\n with open(filename) as lines:\n values = defaultdict(list)\n for line in lines:\n line = line.strip()\n if not line:\n continue\n elif line.startswith(\"# \"):\n keyword = line[2:]\n else:\n values[keyword].append(line.rstrip('\\n'))\n return values\n" }, { "answer_id": 74289378, "author": "Ramesh", "author_id": 18014805, "author_profile": "https://Stackoverflow.com/users/18014805", "pm_score": 1, "selected": true, "text": "txt = '''# car name \nBMW\nsuzuki\n\n# car model \nX1 \nTT\n\n# color\nred \nblue'''\n\ntxt_split = [i.strip() for i in txt.split('\\n') if i.strip()]\nheader_list = ['# car name', '# car model', '# color']\nheaders = [txt_split.index(i) for i in txt_split if i in header_list]\nfor i in range(len(headers)):\n values = txt_split[headers[i]].partition('#')[2].strip().replace(' ', '_')\n if i == len(headers) - 1:\n keys = txt_split[headers[i] + 1:]\n else:\n keys = txt_split[headers[i] + 1:headers[i + 1]]\n print({values: keys})\n\n >>>> {'car_name': ['BMW', 'suzuki']}\n >>>> {'car_model': ['X1', 'TT']}\n >>>> {'color': ['red', 'blue']}\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20239100/" ]
74,287,838
<p>On NuGet.org there is only a very old <code>System.Console</code> package targeting <code>.NET Framework 4.6</code> but no one for <code>.NET 6</code>.</p> <p>Is this last version 4.3.1 from 2018 still valid for <code>.NET 6</code> or is it part of another assembly?</p>
[ { "answer_id": 74287925, "author": "Richard", "author_id": 67392, "author_profile": "https://Stackoverflow.com/users/67392", "pm_score": 3, "selected": true, "text": "System.Console" }, { "answer_id": 74287946, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 0, "selected": false, "text": "Microsoft.NET.Sdk" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
74,287,866
<p>I am trying to call REST API using Oracle APEX provided function <strong>apex_web_service.make_rest_request</strong> by passing JSON.</p> <p>JSON is created by using below utility by passing the sys_refcursor.</p> <pre><code>apex_json.open_object; apex_json.write(l_sys_refcursor); apex_json.close_object; lclob_body := apex_json.get_clob_output; </code></pre> <p>Now I am passing the value of lclob_body to below</p> <pre><code> begin apex_web_service.set_request_headers( p_name_01 =&gt; 'Content-Type', p_value_01 =&gt; 'application/json', p_name_02 =&gt; 'User-Agent', p_value_02 =&gt; 'APEX', p_name_03 =&gt; 'Authorization', p_value_03 =&gt; 'Basic xxxasdasdasdsaddsadsdsasfsafa', p_reset =&gt; true, p_skip_if_exists =&gt; true ); end; v_response := apex_web_service.make_rest_request ( p_url =&gt; 'https://....api_url', p_http_method =&gt; 'POST', p_body =&gt; lclob_body ); </code></pre> <p>This is working fine for single JSON but when sys_refcursor returns multiple rows then multiple json is getting created. In this case, only first json is passing to API call.</p> <p>How to pass each json <strong>(for each row returned by sys_refcursor)</strong> one by one to the function make_rest_request to call the API?</p> <p><strong>Edit : 1</strong></p> <p>I have done this simply by iterating the sys_refcursor into variables.</p> <pre><code>loop fetch l_cursor into p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15; exit when l_cursor%notfound; apex_json.open_object; apex_json.write('field1',p1); apex_json.write('field2',p2); apex_json.write('field3',p3); apex_json.write('field4',p4); apex_json.write('field5',p5); apex_json.write('field6',p6); apex_json.write('field7',p7); apex_json.write('field8',p8); apex_json.write('field9',p9); apex_json.write('field10',p10); apex_json.write('field11',p11); apex_json.write('field12',p12); apex_json.write('field13',p13); apex_json.write('field14',p14); apex_json.write('field15',p15); apex_json.close_object; lclob_body := apex_json.get_clob_output; begin apex_web_service.set_request_headers( p_name_01 =&gt; 'Content-Type', p_value_01 =&gt; 'application/json', p_name_02 =&gt; 'User-Agent', p_value_02 =&gt; 'APEX', p_name_03 =&gt; 'Authorization', p_value_03 =&gt; 'Basic xxxasdasdasdsaddsadsdsasfsafa', p_reset =&gt; true, p_skip_if_exists =&gt; true ); end; v_response := apex_web_service.make_rest_request ( p_url =&gt; 'https://....api_url', p_http_method =&gt; 'POST', p_body =&gt; lclob_body ); dbms_output.put_line(v_response); exception when others then null; end; apex_json.free_output; end loop; </code></pre> <p>With this approach, able to call API for each json. But not sure if this is right way to achieve this or not. Please suggest if there is any other better way to achieve this.</p> <p>Thank You!</p>
[ { "answer_id": 74360381, "author": "SKG", "author_id": 3531157, "author_profile": "https://Stackoverflow.com/users/3531157", "pm_score": 1, "selected": true, "text": " set serveroutput on;\n declare\n v_response clob;\n\n cursor c1 is\n SELECT\n json_object('field1' value 'AABBCC', \n 'field2' value t2.col1 ,\n 'field3' value t1.col1, \n 'field4' value 'Corp' , \n 'field5' value 'AABB'||t2.col2 ,\n 'field6' value JSON_object (\n 'nested_field1' value '2029-11-13',\n 'nested_field2' value 'XYZ' ,\n 'nested_field3' value 'ABC' ,\n 'nested_field4' value '2019-11-12', \n 'nested_field5' value '1234' ,\n 'nested_field6' value 'ABC' \n ) ,\n \n 'field7' value '' ,\n 'field8' value 'TEAM' ,\n 'field9' value 'true' , \n 'field10' value '12345' , \n 'field11' value 'Scale' ,\n 'field12' value t2.col3 , \n 'field13' value t1.col2 ,\n 'field14' value 'RUP' , \n 'field15' value 'ZZ' \n ) a\n FROM\n tab1 t1,\n tab2 t2\n WHERE\n t1.col1 = t2.col2\n AND t1.col5 IS NULL;\n \n begin\n apex_web_service.set_request_headers(\n p_name_01 => 'Content-Type',\n p_value_01 => 'application/json',\n p_name_02 => 'User-Agent',\n p_value_02 => 'APEX',\n p_name_03 => 'Authorization',\n p_value_03 => 'Basic xxxasdasdasdsaddsadsdsasfsafa',\n p_reset => true,\n p_skip_if_exists => true );\n \n for i in c1 loop\n \n begin\n \n v_response := apex_web_service.make_rest_request\n (\n p_url => 'https://....api_url',\n p_http_method => 'POST',\n p_body => i.a\n );\n \n exception when others then \n null;\n end; \n \n end loop;\n\n end;\n /\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531157/" ]
74,287,876
<p>We are switching our authentication service from a custom implementation with cookies to an approach with refresh tokens by Auth0. The Auth0 react package provides us with a <code>getAccessTokenSilently</code> function which we use in an <code>Interceptor</code> context provider and add the token to our <code>Axios</code> client via an interceptor.</p> <p>The structure of the different parts looks like this:</p> <p><strong>App.js</strong></p> <pre><code>const App = () =&gt; { return ( &lt;Auth0Provider domain={process.env.REACT_APP_AUTH0_DOMAIN} clientId={process.env.REACT_APP_AUTH0_CLIENT_ID} redirectUri={window.location.origin} audience={process.env.REACT_APP_AUTH0_AUDIENCE} &gt; &lt;BrowserRouter&gt; &lt;NotificationProvider&gt; &lt;Interceptor&gt; &lt;NotificationList /&gt; &lt;Router /&gt; &lt;/Interceptor&gt; &lt;/NotificationProvider&gt; &lt;/BrowserRouter&gt; &lt;/Auth0Provider&gt; ); }; export default App; </code></pre> <p><strong>apiClient.js</strong></p> <pre><code>import axios from 'axios'; const apiClient = axios.create({ baseURL: process.env.REACT_APP_API, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, timeout: 10000, }); export default apiClient; </code></pre> <p><strong>Interceptor.js</strong></p> <pre><code>const Interceptor = ({ children }) =&gt; { const { addNotification } = useContext(NotificationContext); const { getAccessTokenSilently } = useAuth0(); const [accessToken, setAccessToken] = useState(); useEffect(() =&gt; { const getAccessToken = async () =&gt; { try { const token = await getAccessTokenSilently(); console.log('TOKEN: ', token); setAccessToken(token); } catch (error) { console.log(error); } } getAccessToken(); }, [getAccessTokenSilently]); useMemo(() =&gt; { apiClient.interceptors.request.use( (config) =&gt; { config.headers.Authorization = `Bearer ${accessToken}`; return config; }, (error) =&gt; { return Promise.reject(error); }, ); apiClient.interceptors.response.use( (response) =&gt; { return response; }, (error) =&gt; { if (error.message === 'Network Error') { if (error?.response?.status === 504) { addNotification('error', 'Oops!', 'gateway_timeout'); } else { addNotification('error', 'Oops!', 'server_down'); } } else { addNotification('error', error.response?.data?.title || 'Oops!', error.response?.data?.description); } return Promise.reject(error); }, ); }, [accessToken]); return &lt;&gt;{children}&lt;/&gt;; }; export default Interceptor; </code></pre> <p><strong>profileService.js</strong></p> <pre><code>import apiClient from '../utils/apiClient'; export default { getProfileInfo() { return apiClient.get(`/profile`); }, updateProfile(data) { return apiClient.put('/profile', data); }, }; </code></pre> <p>We use different service files to separate our calls to the backend by topic and centralize them away from our user interface.</p> <p>We are expecting that our access token would be added as Bearer token to our calls to the API but this is not the case. If we check the headers from our call we get <code>Authorization: Bearer undefined</code> while if we console.log the access token in the Interceptor provider we get an access token.</p> <p>How can we set the token correctly via an interceptor?</p> <p><strong>EDIT 1: Extra code to show where the profileService functions are being used</strong></p> <p><strong>Router.js</strong></p> <p>This is a part of the router.js file. in App.js is executing this code</p> <pre><code>const ProtectedRoutes = () =&gt; { const { isAuthenticated, loginWithRedirect } = useAuth0(); return isAuthenticated ? &lt;Outlet /&gt; : loginWithRedirect(); }; const Router = () =&gt; { const { isLoading } = useAuth0(); if (isLoading) { return &lt;Spinner /&gt;; } return ( &lt;Routes&gt; &lt;Route element={&lt;GuestRoute /&gt;}&gt; &lt;Route element={&lt;GuestLayout /&gt;}&gt; &lt;Route path='/account/verify' element={&lt;VerifyAccount /&gt;} /&gt; &lt;/Route&gt; &lt;/Route&gt; &lt;Route element={&lt;ProtectedRoutes /&gt;}&gt; &lt;Route element={&lt;OnboardingLayout /&gt;}&gt; &lt;Route path='/onboarding' element={&lt;Onboarding /&gt;} /&gt; &lt;/Route&gt; &lt;Route element={&lt;AppLayout /&gt;}&gt; &lt;Route path='/' element={&lt;Navigate to='/profile' replace /&gt;} /&gt; &lt;Route path='/profile' element={&lt;Profile /&gt;} /&gt; &lt;/Route&gt; &lt;/Route&gt; &lt;Route path='404' element={&lt;NotFound /&gt;} /&gt; &lt;Route path='*' element={&lt;Navigate to='/404' replace /&gt;} /&gt; &lt;/Routes&gt; ); }; </code></pre> <p><strong>Profile page</strong></p> <p>Part of the profile page where the call to profileService.getProfileInfo is being called.</p> <pre><code>const ProfileOverview = () =&gt; { useEffect(() =&gt; { getProfileInfo(); }, []); const getProfileInfo = async () =&gt; { const { data } = await profileService.getProfileInfo(); reset({ ...data }); }; const { handleSubmit, register, watch, reset, getValues, formState: { errors, isDirty }, } = useForm({ resolver: useYupResolver(editProfileValidationSchema), }); </code></pre>
[ { "answer_id": 74360381, "author": "SKG", "author_id": 3531157, "author_profile": "https://Stackoverflow.com/users/3531157", "pm_score": 1, "selected": true, "text": " set serveroutput on;\n declare\n v_response clob;\n\n cursor c1 is\n SELECT\n json_object('field1' value 'AABBCC', \n 'field2' value t2.col1 ,\n 'field3' value t1.col1, \n 'field4' value 'Corp' , \n 'field5' value 'AABB'||t2.col2 ,\n 'field6' value JSON_object (\n 'nested_field1' value '2029-11-13',\n 'nested_field2' value 'XYZ' ,\n 'nested_field3' value 'ABC' ,\n 'nested_field4' value '2019-11-12', \n 'nested_field5' value '1234' ,\n 'nested_field6' value 'ABC' \n ) ,\n \n 'field7' value '' ,\n 'field8' value 'TEAM' ,\n 'field9' value 'true' , \n 'field10' value '12345' , \n 'field11' value 'Scale' ,\n 'field12' value t2.col3 , \n 'field13' value t1.col2 ,\n 'field14' value 'RUP' , \n 'field15' value 'ZZ' \n ) a\n FROM\n tab1 t1,\n tab2 t2\n WHERE\n t1.col1 = t2.col2\n AND t1.col5 IS NULL;\n \n begin\n apex_web_service.set_request_headers(\n p_name_01 => 'Content-Type',\n p_value_01 => 'application/json',\n p_name_02 => 'User-Agent',\n p_value_02 => 'APEX',\n p_name_03 => 'Authorization',\n p_value_03 => 'Basic xxxasdasdasdsaddsadsdsasfsafa',\n p_reset => true,\n p_skip_if_exists => true );\n \n for i in c1 loop\n \n begin\n \n v_response := apex_web_service.make_rest_request\n (\n p_url => 'https://....api_url',\n p_http_method => 'POST',\n p_body => i.a\n );\n \n exception when others then \n null;\n end; \n \n end loop;\n\n end;\n /\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391416/" ]
74,287,884
<p>I have a reduce method done in JavaScript to combine the contents of an array of objects where there is a match with the same key.</p> <p>For example:</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 data = [{ "stage": "AT_CALLCENTER", "content": "Hello", }, { "stage": "AT_CALLCENTER", "content": "Bye", }, { "stage": "AT_SITE", "content": "Good", }, { "stage": "AT_SITE", "content": "Morning", } ] const result = data.reduce((val, item) =&gt; ({ ...val, [`${item.stage}`]: [...(val[item.stage] || []), item.content] }), {}); console.log(result)</code></pre> </div> </div> </p> <p>I was told by a friend that a filter can perform better; this is important because I'm expecting much more data in production, and this code is executed 2x per row.</p> <p>How can I achieve the same functionality, but with a filter instead of a reduction? Or is filter not actually the better option?</p>
[ { "answer_id": 74288261, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 3, "selected": true, "text": "reduce/spread" }, { "answer_id": 74289532, "author": "Gabriel Rodríguez Flores", "author_id": 11299601, "author_profile": "https://Stackoverflow.com/users/11299601", "pm_score": 2, "selected": false, "text": "filter" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7882685/" ]
74,287,908
<p>I am getting a list from servers like this</p> <pre><code>[ { &quot;Date&quot;: &quot;2022-10-21&quot;, &quot;Wages&quot;: [ { &quot;Name&quot;: &quot;101 Working hours&quot;, &quot;Balance&quot;: &quot;8.00&quot;, &quot;Date&quot;: &quot;2022-10-21&quot;, &quot;ShiftName&quot;: &quot;AU128&quot; }, { &quot;Name&quot;: &quot;102 Bonus pay&quot;, &quot;Balance&quot;: &quot;3:48&quot;, &quot;Date&quot;: &quot;2022-10-21&quot;, &quot;ShiftName&quot;: &quot;&quot; }, { &quot;Name&quot;: &quot;110 Split Shift&quot;, &quot;Balance&quot;: &quot;1:00&quot;, &quot;Date&quot;: &quot;2022-10-21&quot;, &quot;ShiftName&quot;: &quot;&quot; }, { &quot;Name&quot;: &quot;111 Wage reduction&quot;, &quot;Balance&quot;: &quot;1:00&quot;, &quot;Date&quot;: &quot;2022-10-21&quot;, &quot;ShiftName&quot;: &quot;&quot; } ] }, ] </code></pre> <p>I want to get ShiftName if it is not empty and shows at FE. shift name is in Wages List</p> <pre><code>Text( Wages[i].shiftName ?? &quot;&quot;, style: wageTextStyle, ), </code></pre> <p>I try to use <code>List.any((any) =&gt; any.containsValue());</code></p> <p>but I do not know which value I get from server because shiftName can be changed</p> <p>my API calling method from provider Consumer</p> <pre><code> Consumer&lt;EmployeeWageAccountsProvider&gt;( builder: (context, data, child) { if (!data.isLoading) { int length = data.getEmployeeAccountsData!.length; if (data.getEmployeeAccountsData!.isNotEmpty) { wageAccountsData = data.getEmployeeAccountsData!; return ListView.builder( itemCount: length, shrinkWrap: true, scrollDirection: Axis.vertical, itemBuilder: (context, i) { return WageAccountsCard( date: Helper.formatStringDate( wageAccountsData[i].date!), shiftName: wageAccountsData[i].wages! [i].shiftName!.isEmpty ? &quot;&quot;:wageAccountsData[i].wages! [i].shiftName, wages: wageAccountsData[i].wages, ); }, ); } return noDataFound(context, 50); } return const WageAccountsShimmer(); }), </code></pre> <p>wage accounts card to displaying data to user</p> <pre><code> class WageAccountsCard extends StatelessWidget { final String? date; final String? shiftName; final List&lt;Wages&gt;? wages; const WageAccountsCard( {Key? key, this.date, this.shiftName, this.wages}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.all(10), padding: const EdgeInsets.all(8), decoration: CustomBoxDecoration.cardDecoration(context, shadow: true), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( shiftName ?? &quot;&quot;, style: wageTextStyle, ), Text( date.toString(), style: wageTextStyle, ), ], ), SizedBox( height: Styles.height(context) * 0.01, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( S.of(context).wage_type, style: cTextStyle, ), Text( S.of(context).balance, style: cTextStyle, ), ], ), const Divider( color: Colors.black, ), ] ), ); } } </code></pre> <p><a href="https://i.stack.imgur.com/SVKnem.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SVKnem.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/GLMWim.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GLMWim.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74288261, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 3, "selected": true, "text": "reduce/spread" }, { "answer_id": 74289532, "author": "Gabriel Rodríguez Flores", "author_id": 11299601, "author_profile": "https://Stackoverflow.com/users/11299601", "pm_score": 2, "selected": false, "text": "filter" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12204643/" ]
74,287,918
<p>I am facing a matching problem... I am trying to mark the multiple dots in an incorrect mail address so that only the relevant dots appear:</p> <pre><code>mike.smith@yahoo..com mike....smith@yahoo.com </code></pre> <p>My approach <code>(\.(?!(\.\w)))</code> works correctly for several dots in a row, but still matches the single dot in mike.smith@yahoo.com</p> <p>Do you have an idea? Any help appreciated.</p>
[ { "answer_id": 74289396, "author": "MonkeyZeus", "author_id": 2191572, "author_profile": "https://Stackoverflow.com/users/2191572", "pm_score": 1, "selected": false, "text": "\\.{2,}" }, { "answer_id": 74291410, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "\\.(?=\\.[^@\\s]*@)|(?<=@[^\\s@]*\\.)\\.\n" }, { "answer_id": 74300207, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 0, "selected": false, "text": "\\.(?=\\.+\\w)\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396439/" ]
74,287,954
<p>I'm having difficulty targeting the child div of <code>id=&quot;videoContainer&quot;</code> and changing its style</p> <pre><code>&lt;div id=&quot;videoContainer&quot;&gt; &lt;div style=&quot;width: 640px; height: 360px&quot;&gt; &lt;------- target this &lt;video src=&quot;&quot; preload=&quot;auto&quot; autoplay=&quot;&quot; style=&quot;width: 100%; height: 100%&quot; &gt;&lt;/video&gt; &lt;/div&gt; &lt;/div&gt; const videoContainer = document.getElementById('videoContainer') document.getElementById('videoContainer').children?.[0]?.setAttribute(&quot;style&quot;, `width: 150px; height: 200px;`); </code></pre>
[ { "answer_id": 74288005, "author": "aloisdg", "author_id": 1248177, "author_profile": "https://Stackoverflow.com/users/1248177", "pm_score": 3, "selected": true, "text": ">" }, { "answer_id": 74288034, "author": "habby", "author_id": 8574562, "author_profile": "https://Stackoverflow.com/users/8574562", "pm_score": 1, "selected": false, "text": "<div id=\"videoContainer\">\n <div id=\"idname\" class=\"classname\" style=\"width: 640px; height: 360px\"> \n //....\n </div>\n</div>\n" }, { "answer_id": 74288471, "author": "Sudhanshu", "author_id": 7584658, "author_profile": "https://Stackoverflow.com/users/7584658", "pm_score": 0, "selected": false, "text": "document.getElementById(\"videoContainer\").children[0].style.background=\"red\";" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8305219/" ]
74,287,967
<p>I often find myself trying to figure out how a particular annotation works under the hood. Performing a 'find usages' on the annotation in the IDE(like IntelliJ) will usually just bring you to where the annotation is actually used. I don't see an easy way however of finding the logic that processes the annotation.</p> <p>I get that because of the nature of annotations that it's difficult to see where they are being processed, but at the same time, when they are consumed one would have had to import the specific annotation so there is a link established.</p> <p>Take the case of</p> <p>SomeAnnotation.java</p> <pre><code>@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SomeAnnotation { } </code></pre> <p>and it's being consumed in AnnotationConsumer.java</p> <pre><code>import com.annotations.SomeAnnotation public class AnnotationProcessor { public AnnotationProcessor() { if (currentClass.isAnnotationPresent(SomeAnnotation.class)) { // do some logic } } } </code></pre> <p>Usually, some piece of code will be tagged with @SomeAnnotation.</p> <p>What I would like to do is find the AnnotationProcessor class where SomeAnnotation is being processed.</p> <p>Anything I've searched for so far simply leads me down a path of HOW to process annotations, not WHERE they are being processed.</p>
[ { "answer_id": 74288515, "author": "hunter", "author_id": 5177506, "author_profile": "https://Stackoverflow.com/users/5177506", "pm_score": 2, "selected": true, "text": "Class.isAnnotationPresent(Class<? extends Annotation> a)" }, { "answer_id": 74292002, "author": "mernst", "author_id": 173852, "author_profile": "https://Stackoverflow.com/users/173852", "pm_score": 0, "selected": false, "text": "-processor" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74287967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6478781/" ]
74,288,015
<p>I have a situation where I need to compare multiple pairs of columns (the number of pairs will vary and can come from a list as shown in below code snippet) and get 1/0 flag for match/mismatch respectively. Eventually use this to identify the number of records/rows with mismatch and % records mismatched</p> <pre class="lang-py prettyprint-override"><code>NONKEYCOLS= ['Marks', 'Qualification'] </code></pre> <p>The first image is <em>source df</em> and second image is <em>expected df</em>.</p> <p><a href="https://i.stack.imgur.com/KdtMV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KdtMV.png" alt="Source DF" /></a></p> <p>[<img src="https://i.stack.imgur.com/ncFFb.png" alt="Expected Results2" /></p> <p><a href="https://i.stack.imgur.com/ncFFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ncFFb.png" alt="enter image description here" /></a></p> <p>Since this is happening for multiple pairs on a loop, it is very slow for about a billion records. Need help with something efficient.</p> <p>I have the below code but the part that calculates change records is taking long time.</p> <pre><code> for ind,cols in enumerate(NONKEYCOLS): print(ind) print(cols) globals()['new_dataset' + '_char_changes_tmp']=globals()['new_dataset' + '_char_changes_tmp']\ .withColumn(&quot;records_changed&quot; + str(ind),\ F.sum(col(&quot;records_ch_flag_&quot; + str(ind)))\ .over(w1)) globals()['new_dataset' + '_char_changes_tmp']=globals()['new_dataset' + '_char_changes_tmp']\ .withColumn(&quot;records_changed&quot; + str(ind),\ F.sum(col(&quot;records_ch_flag_&quot; + str(ind)))\ .over(w1)) globals()['new_dataset' + '_char_changes_tmp']=globals()['new_dataset' + '_char_changes_tmp']\ .withColumn(&quot;records_changed_cnt&quot; + str(ind),\ F.count(col(&quot;records_ch_flag_&quot; + str(ind)))\ .over(w1)) </code></pre>
[ { "answer_id": 74288515, "author": "hunter", "author_id": 5177506, "author_profile": "https://Stackoverflow.com/users/5177506", "pm_score": 2, "selected": true, "text": "Class.isAnnotationPresent(Class<? extends Annotation> a)" }, { "answer_id": 74292002, "author": "mernst", "author_id": 173852, "author_profile": "https://Stackoverflow.com/users/173852", "pm_score": 0, "selected": false, "text": "-processor" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7697375/" ]
74,288,023
<p>i have two dictionary</p> <pre class="lang-py prettyprint-override"><code>dict1 = { &quot;abc&quot;: sm.xyz.cdd(), &quot;def&quot;: sm.acf.fdr(), &quot;ghi&quot;: sm.rty.qsd(), } </code></pre> <p>I need to create a function that takes 2 parameters 1st is the key of dict1 and 2nd parameter would be a string and i want the output</p> <pre class="lang-py prettyprint-override"><code>fun(&quot;abc&quot;, &quot;log&quot;) # then this must be my output sm.xyz.cdd(&quot;log&quot;) </code></pre>
[ { "answer_id": 74288082, "author": "Tenobaal", "author_id": 18861247, "author_profile": "https://Stackoverflow.com/users/18861247", "pm_score": 0, "selected": false, "text": "dict1={\n \"abc\":sm.xyz.cdd,\n \"def\":sm.acf.fdr,\n \"ghi\":sm.rty.qsd,\n}\ndef fun(key, *args, **vaargs):\n dict1[key](*args, **vaargs)\n" }, { "answer_id": 74288132, "author": "thestarwarsnerd", "author_id": 18931013, "author_profile": "https://Stackoverflow.com/users/18931013", "pm_score": 1, "selected": false, "text": "\ndef fun(dictKey, funInput):\n \n return dict1[dictKey](funInput)\n \n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19223879/" ]
74,288,035
<p>enter image description here I need to know what's the problem. I am not getting the message on console for establishment of Mongodb database connection.</p> <p>Here is a link to the error picture. <a href="https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link" rel="nofollow noreferrer">https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link</a></p> <p>server.js file</p> <pre><code>const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); require('dotenv').config(); const app = express(); const port = process.env.port || 5000; app.use(cors()); app.use(express.json()); // debugger var uri; // Define outside if(process.env.ATLAS_URI){ uri = process.env.ATLAS_URI; // Assign inside the block } mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true} ); const connection = mongoose.connection; connection.once('open', () =&gt; { console.log(&quot;MongoDB database connection established successfully&quot;); }) const exercisesRouter = require('./routes/exercises'); const usersRouter = require('./routes/users'); app.use('/exercises', exercisesRouter); app.use('/users', usersRouter); app.listen(port, ()=&gt; { console.log(`Server is running on port: ${port}`); }); </code></pre> <p>.env file</p> <pre><code>ATLAS_URI = mongodb+srv://tripsy25:Mongo@123@cluster0.lwpkrde.mongodb.net/?retryWrites=true&amp;w=majority </code></pre> <p>I tried to debug the code and found that uri was coming as undefined. Do I need to convert the password in ATLAS_URI to some other format?</p>
[ { "answer_id": 74288082, "author": "Tenobaal", "author_id": 18861247, "author_profile": "https://Stackoverflow.com/users/18861247", "pm_score": 0, "selected": false, "text": "dict1={\n \"abc\":sm.xyz.cdd,\n \"def\":sm.acf.fdr,\n \"ghi\":sm.rty.qsd,\n}\ndef fun(key, *args, **vaargs):\n dict1[key](*args, **vaargs)\n" }, { "answer_id": 74288132, "author": "thestarwarsnerd", "author_id": 18931013, "author_profile": "https://Stackoverflow.com/users/18931013", "pm_score": 1, "selected": false, "text": "\ndef fun(dictKey, funInput):\n \n return dict1[dictKey](funInput)\n \n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16161456/" ]
74,288,036
<p>I want to call a function, once the value of dropdown is changed.</p> <p>I have done this without Angular Material. Here's my ts and html files.</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> selected="pending"; getRequests(event: any) { this.selected = event.target.value; if(this.selected=="pending") console.log("Inside Pending Requests") else console.log("Inside Granted Requests") }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="margin-left: 70%;" appearance="fill"&gt; &lt;select (change)="getRequests($event)"&gt; &lt;option value="pending"&gt;Pending&lt;/option&gt; &lt;option value="granted"&gt;Granted&lt;/option&gt; &lt;/select&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Now, I want to implement this with the help of <strong>Angular Material Select Component. Calling the getRequests() function is not working as expected</strong>. Somebody please help me on this one. Thanks in advance.</p> <pre><code>&lt;mat-form-field style=&quot;margin-left: 70%;&quot; appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Status&lt;/mat-label&gt; &lt;mat-select [(value)]=&quot;selected&quot; (change)=&quot;getRequests($event)&quot; &gt; &lt;mat-option value=&quot;pending&quot;&gt;Pending&lt;/mat-option&gt; &lt;mat-option value=&quot;granted&quot;&gt;Granted&lt;/mat-option&gt; &lt;/mat-select&gt; </code></pre>
[ { "answer_id": 74288154, "author": "Andrew Allen", "author_id": 4711754, "author_profile": "https://Stackoverflow.com/users/4711754", "pm_score": 2, "selected": false, "text": "selectionChange" }, { "answer_id": 74288165, "author": "LaCodeM", "author_id": 11746772, "author_profile": "https://Stackoverflow.com/users/11746772", "pm_score": 1, "selected": false, "text": "<mat-form-field style=\"margin-left: 70%;\" appearance=\"fill\">\n<mat-label>Status</mat-label>\n<mat-select [(value)]=\"selected\" (selectionChange)=\"getRequests($event)\" >\n <mat-option value=\"pending\">Pending</mat-option>\n <mat-option value=\"granted\">Granted</mat-option>\n</mat-select>\n\n" }, { "answer_id": 74288168, "author": "Stacks Queue", "author_id": 14820590, "author_profile": "https://Stackoverflow.com/users/14820590", "pm_score": 2, "selected": false, "text": "(change)" }, { "answer_id": 74288180, "author": "Chellappan வ", "author_id": 7790376, "author_profile": "https://Stackoverflow.com/users/7790376", "pm_score": 2, "selected": false, "text": "selectionChange" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13517148/" ]
74,288,080
<p>Working with PySimpleGUI a while before, I found a problem related to how I wanted to handle my program. I wanted my app to have language system, which worked on key system - it simply checked the language in settings file, and headed to respective language file with key provided. In such manner:</p> <p>EN file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;text_field_1&quot;: &quot;Something&quot;, &quot;text_field_2&quot;: &quot;Something else&quot;, &quot;text_field_3&quot;: &quot;Something&quot; } </code></pre> <p>PL file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;text_field_1&quot;: &quot;Coś&quot;, &quot;text_field_2&quot;: &quot;Coś innego&quot;, &quot;text_field_3&quot;: &quot;Coś&quot; } </code></pre> <p>This, however, does not work ideally with PySimpleGUI listboxes, as their event/value system operates on list of single values.<br /> So, whatever you pass onto PSG listbox, is printed out in its literal sense. This works nice for non-language-ambiguous elements (user-created content, directories, and so on), but if there's list of elements which are language-dependent, it suffers from dictionary issue - where keys cannot repeat, but values can.</p> <p>Passing <code>lang_str(key)</code> functions (converting key into respective language-relative string) into the list requested by listbox feature results in, in case of our .json file from above, getting such choice:</p> <ul> <li>&quot;Something&quot;</li> <li>&quot;Something else&quot;</li> <li>&quot;Something&quot;</li> </ul> <p>Which makes two listbox keys capable of having two the same values, because you refer to value, not the dictionary key.</p> <p>Ideally, there would be separate &quot;printed out&quot; value which would not interact with event system, and &quot;event&quot; value which would be used to recognise which element was selected. But I haven't seen anything like that in PySimpleGUI.<br /> How one can call listbox key through always-the-same dictionary key, not the value which can be ambigious?</p>
[ { "answer_id": 74288154, "author": "Andrew Allen", "author_id": 4711754, "author_profile": "https://Stackoverflow.com/users/4711754", "pm_score": 2, "selected": false, "text": "selectionChange" }, { "answer_id": 74288165, "author": "LaCodeM", "author_id": 11746772, "author_profile": "https://Stackoverflow.com/users/11746772", "pm_score": 1, "selected": false, "text": "<mat-form-field style=\"margin-left: 70%;\" appearance=\"fill\">\n<mat-label>Status</mat-label>\n<mat-select [(value)]=\"selected\" (selectionChange)=\"getRequests($event)\" >\n <mat-option value=\"pending\">Pending</mat-option>\n <mat-option value=\"granted\">Granted</mat-option>\n</mat-select>\n\n" }, { "answer_id": 74288168, "author": "Stacks Queue", "author_id": 14820590, "author_profile": "https://Stackoverflow.com/users/14820590", "pm_score": 2, "selected": false, "text": "(change)" }, { "answer_id": 74288180, "author": "Chellappan வ", "author_id": 7790376, "author_profile": "https://Stackoverflow.com/users/7790376", "pm_score": 2, "selected": false, "text": "selectionChange" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9499474/" ]
74,288,088
<p>I am trying to modify the body of GET request. For that I tried this:</p> <pre><code>function modify(req, res, next){ res.body = res.body + &quot;modified&quot;; next(); } </code></pre> <p>then when I try to log res.body it prints nothing</p> <p>Ref: <a href="https://stackoverflow.com/questions/9896628/connect-or-express-middleware-to-modify-the-response-body">Connect or Express middleware to modify the response.body</a></p>
[ { "answer_id": 74331050, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 1, "selected": true, "text": "res.body" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20365724/" ]
74,288,125
<p>I have a User Model and Country Model, and Country belongs to User.</p> <p>I am getting users with country using User model with &quot;with()&quot; method, in different controllers &amp; methods.</p> <pre><code>Users::with('country')-&gt;get(); </code></pre> <p>in different controllers. I want</p> <pre><code>Users::get(); </code></pre> <p>It should automatically call the with('country') even if I dont call it.</p> <p>And if I call any other relation like:</p> <pre><code>User::with('role')-&gt;get() </code></pre> <p>Now it should get role and country both. Not just role.</p> <p>How can I achieve this..?</p>
[ { "answer_id": 74288173, "author": "Techno", "author_id": 2595985, "author_profile": "https://Stackoverflow.com/users/2595985", "pm_score": 3, "selected": true, "text": "$with" }, { "answer_id": 74300141, "author": "Ramil Huseynov", "author_id": 6711823, "author_profile": "https://Stackoverflow.com/users/6711823", "pm_score": 0, "selected": false, "text": "\nprotected $with = ['country' , 'add some reation'];\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11605188/" ]
74,288,133
<p>I would like to calculate the number of partitions in each of my broker. We have a muli-DC distributed architecture; and would like to get the partition count per broker for maintenance and admin tasks</p> <p>This is what was suggested in one of the blogposts; and works fine and this is at cluster level; however I need a similar script for per broker</p> <pre><code>zookeeper=&quot;ZK_SERVER1:2181,ZK_SERVER2:2181,ZK_SERVER3:2181&quot; sum=0 for i in $(/usr/hdp/current/kafka-broker/bin/kafka-topics.sh --list --zookeeper $zookeeper ); do count=$(/usr/hdp/current/kafka-broker/bin/kafka-topics.sh --describe --zookeeper $zookeeper --topic $i |grep Leader | wc -l); sum=`expr $sum + $count` ; echo 'total partitions is ' $sum; done </code></pre>
[ { "answer_id": 74322428, "author": "Adam Kotwasinski", "author_id": 6204612, "author_profile": "https://Stackoverflow.com/users/6204612", "pm_score": 0, "selected": false, "text": "Admin" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8563278/" ]
74,288,134
<pre class="lang-swift prettyprint-override"><code>VStack { .onAppear { for cont in contactsVM.contacts { info = &quot;\(cont.firstName) \(cont.lastName);\(cont.phone);//&quot; } } } </code></pre> <p>If you save the text in the info and print it out, only one text comes out</p> <p><a href="https://i.stack.imgur.com/3IxDz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3IxDz.png" alt="enter image description here" /></a></p> <p>I want to get all the text that appears on the console</p> <p>I'm going to take it and use it as a text editor</p> <hr /> <p>There's an error</p> <p><a href="https://i.stack.imgur.com/oYpAp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oYpAp.png" alt="enter image description here" /></a></p> <p>this is My ViewModel</p> <pre class="lang-swift prettyprint-override"><code> getContacts() { Contact.fetchAll { [weak self] result in guard let self = self else { return } switch result { case .success(let fetchedContacts): DispatchQueue.main.async { self.contacts = fetchedContacts.sorted(by: {$0.lastName &lt; $1.lastName}) } case.failure(let error): self.permissionsError = .fetchError(error) } } } </code></pre> <p>And model <a href="https://i.stack.imgur.com/2cOkq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2cOkq.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74288238, "author": "Aditya Yadav", "author_id": 5460667, "author_profile": "https://Stackoverflow.com/users/5460667", "pm_score": 0, "selected": false, "text": " var info = \"\"\n for contact in contactsVM.contacts {\n info.append(\"\\(cont.firstName) \\(cont.lastName);\\(cont.phone) \\n\")\n }\n" }, { "answer_id": 74288354, "author": "vadian", "author_id": 5044042, "author_profile": "https://Stackoverflow.com/users/5044042", "pm_score": 3, "selected": true, "text": "info" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17990639/" ]
74,288,145
<p>In my google sheet I have some data in it. Later I published my sheet as <strong>.csv</strong> format.</p> <p>Pls find <strong><a href="https://docs.google.com/spreadsheets/d/1R5Wgq4okSWz0d159X5kPvOk8W1T_6eZ2kwoq5kdjO0w/edit?usp=sharing" rel="nofollow noreferrer">my sheet here</a></strong>, below are the <strong>Cell Values</strong></p> <pre><code> C1 = tdsyltt = 'ఈరోజు ( బుధవారం ) క్విజ్ సిలబస్' ; C2 = tdsyl = 'హబక్కూకు 1 &amp; యాకోబు 2, 3' ; C4 = document.getElementById(&quot;tdsyltt).innerHTML = tdsyltt ; C5 = document.getElementById(&quot;tdsyl&quot;).innerHTML = tdsyl ; </code></pre> <p>And using my <strong>published URL</strong> I have developed a <strong>web app</strong></p> <p><strong>code.gs</strong></p> <pre><code>const doGet = _ =&gt; ContentService.createTextOutput(UrlFetchApp.fetch(&quot;https://docs.google.com/spreadsheets/d/e/2PACX-1vReY-tDEwKYjTiSjsfAN42qjFUwMv_OD3_64bFdGrgL-2p3otc13elLcCq3pkb5xqhTA-bW3QXobpqh/pub?gid=1861615717&amp;single=true&amp;range=c1:c5&amp;output=csv&quot;).getContentText()).setMimeType(ContentService.MimeType.JAVASCRIPT); </code></pre> <p>In the web app output 1st line is ok,</p> <p>but for 2nd, 3rd and 4th line there are <strong>Extra 2 Apostrophes</strong> coming at the starting and ending of the lines.</p> <p>Here is <strong><a href="https://script.google.com/macros/s/AKfycbw5ae5_ZLNRiDsgyZlbV5WLEdsHfodP7uhjUUCKHOp4nm1thJVC63sBvP5RhibWWFuXxA/exec" rel="nofollow noreferrer">My Web App</a></strong></p> <p><a href="https://i.stack.imgur.com/6UWBv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6UWBv.jpg" alt="enter image description here" /></a></p> <p>How to fix this ..?</p>
[ { "answer_id": 74288793, "author": "Tanaike", "author_id": 7108653, "author_profile": "https://Stackoverflow.com/users/7108653", "pm_score": 2, "selected": false, "text": "UrlFetchApp.fetch(\"https://docs.google.com/spreadsheets/d/e/2PACX-1vReY-tDEwKYjTiSjsfAN42qjFUwMv_OD3_64bFdGrgL-2p3otc13elLcCq3pkb5xqhTA-bW3QXobpqh/pub?gid=1861615717&single=true&range=c1:c5&output=csv\").getContentText()" }, { "answer_id": 74288945, "author": "Prabhu Paul", "author_id": 20018193, "author_profile": "https://Stackoverflow.com/users/20018193", "pm_score": 3, "selected": true, "text": "csv" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20018193/" ]
74,288,159
<p>I have a dataframe with a column 'queue_ist_dt'. This column contains pandas._libs.tslibs.timestamps.Timestamp values. My requirement is :</p> <p>if time = 10:13:00 then round_off_time = 10:00:00 if time = 23:29:00 then round_off_time = 23:00:00</p> <p>and so on.</p> <p>if time = 10:31:00 then round_off_time = 10:30:00 if time = 23:53:00 then round_off_time = 23:30:00</p> <p>and so on.</p> <p>if time = 10:30:00 then round_off_time = 10:30:00</p> <p>These are the 3 conditions.</p> <p>I tried to write the following logic :</p> <pre><code>for r in range(df.shape[0]): try: if df.loc[r,'queue_ist_dt'].minute&lt;30: timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute) df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- timedelta elif df.loc[r,'queue_ist_dt'].minute&gt;30: ******NEED HELP TO BUILD THIS LOGIC****** except: pass </code></pre> <p>Need help to build logic for the time where minutes is greater than 30 mins and have to be rounded down to 30 mins.</p>
[ { "answer_id": 74288235, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "Series.dt.floor" }, { "answer_id": 74288293, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "df" }, { "answer_id": 74288382, "author": "Devam Sanghvi", "author_id": 16921041, "author_profile": "https://Stackoverflow.com/users/16921041", "pm_score": 1, "selected": false, "text": "for r in range(df.shape[0]):\n try:\n if df.loc[r,'queue_ist_dt'].minute<30:\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- timedelta\n elif df.loc[r,'queue_ist_dt'].minute>30:\n ******THIS LOGIC******\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- (timedelta-30)\n except:\n pass\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12435792/" ]
74,288,162
<p>This is my current situation. I got one parent called &quot;box&quot; which got 15 childrens inside called item. Then I got a loop where I append some text that should be inside the children div. If I append it directly inside the children the code gets messed up and I get the 15 things I want to inside in each children in all of them. So I have to append inside my parent. However I found this smart function called appendChild which at first was not a function because I wanted to insert a string if I understood correctly... Then I found this solution In how to make it a function but in the end it still doesn't gets placed in my children div. How am I supposed to do in my case? I guess</p> <p>This is my code at the moment;</p> <pre><code>&lt;div id = &quot;box&quot;&gt; &lt;div class = &quot;item&quot;&gt;&lt;/div&gt; X15 &lt;/div&gt; </code></pre> <pre><code>$.each() { var element = document.getElementById(&quot;result&quot;); element.appendChild(&quot;coolText&quot;); }); </code></pre> <p>Got this error last check: <code>Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'</code></p>
[ { "answer_id": 74288235, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "Series.dt.floor" }, { "answer_id": 74288293, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "df" }, { "answer_id": 74288382, "author": "Devam Sanghvi", "author_id": 16921041, "author_profile": "https://Stackoverflow.com/users/16921041", "pm_score": 1, "selected": false, "text": "for r in range(df.shape[0]):\n try:\n if df.loc[r,'queue_ist_dt'].minute<30:\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- timedelta\n elif df.loc[r,'queue_ist_dt'].minute>30:\n ******THIS LOGIC******\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- (timedelta-30)\n except:\n pass\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14715325/" ]
74,288,219
<p>I have a DTO class looking like:</p> <pre class="lang-php prettyprint-override"><code>class ParamsDto { #[Assert\Type(ArrayCollection::class)] #[Assert\All([ new Assert\Type('digit'), new Assert\Positive(), ])] private ?ArrayCollection $tagIds = null; public function getTagIds(): ?ArrayCollection { return $this-&gt;tagIds; } public function setTagIds(?ArrayCollection $tagIds): self { $this-&gt;tagIds = $tagIds; return $this; } } </code></pre> <p>Given a request to a url like <code>https://domain.php?tag-ids[]=2</code>, I'd like to parse the <code>tag-ids</code> request param into this DTO's <code>tagIds</code> property.</p> <p>First step I did, I created a name converter, so I can convert between <code>tag-ids</code> and <code>tagIds</code>, so my serializer instantiation looks like:</p> <pre class="lang-php prettyprint-override"><code>$nameConverter = new EducationEntrySearchParamNameConverter(); $serializer = new Serializer([ new ArrayDenormalizer(), new ObjectNormalizer(null, $nameConverter, null, new ReflectionExtractor()), ], [new JsonEncoder()]); $params = $serializer-&gt;denormalize($requestParams, ParamsDto::class); </code></pre> <p>where <code>$params</code> shows as:</p> <pre class="lang-php prettyprint-override"><code> ^ App\DataTransferObject\ParamsDto {#749 -tagIds: Doctrine\Common\Collections\ArrayCollection {#753 -elements: [] } } </code></pre> <p>So it is instantiated but it is empty.<br /> Most likely because my request does not include the <code>elements</code> key in it. If I do a bit of preprocessing, like:</p> <pre class="lang-php prettyprint-override"><code>$requestParams = []; foreach ($request-&gt;query-&gt;all() as $key =&gt; $value) { if (in_array($key, ['tag-ids'])) { $requestParams[$key] = ['elements' =&gt; $value]; } else { $requestParams[$key] = $value; } } $params = $serializer-&gt;denormalize($requestParams, ParamsDto::class); </code></pre> <p>then I get the right output:</p> <pre class="lang-php prettyprint-override"><code>^ App\DataTransferObject\ParamsDto {#749 -tagIds: Doctrine\Common\Collections\ArrayCollection {#757 -elements: array:1 [ 0 =&gt; &quot;2&quot; ] } } </code></pre> <p>How do I do it in a way that the serializer translate the request into the DTO in a way where I don't have to do this pre-processing?</p> <p>L.E: No need for using a custom name converter, I am now using <a href="https://symfony.com/blog/new-in-symfony-4-2-simpler-custom-serialized-names" rel="nofollow noreferrer"><code>SerializedName</code></a></p>
[ { "answer_id": 74288235, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "Series.dt.floor" }, { "answer_id": 74288293, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 0, "selected": false, "text": "df" }, { "answer_id": 74288382, "author": "Devam Sanghvi", "author_id": 16921041, "author_profile": "https://Stackoverflow.com/users/16921041", "pm_score": 1, "selected": false, "text": "for r in range(df.shape[0]):\n try:\n if df.loc[r,'queue_ist_dt'].minute<30:\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- timedelta\n elif df.loc[r,'queue_ist_dt'].minute>30:\n ******THIS LOGIC******\n timedelta = pd.Timedelta(minutes=df.loc[r,'queue_ist_dt'].minute)\n df.loc[r,'queue_placed_interval'] = df.loc[r,'queue_ist_dt']- (timedelta-30)\n except:\n pass\n" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/600061/" ]
74,288,231
<p>So I need to add a mobile operator to Xcode simulator. Currently it looks like this <a href="https://i.stack.imgur.com/ySBKD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ySBKD.png" alt="no mobile operator at all" /></a></p> <p>And i want it to be like this<a href="https://i.stack.imgur.com/ZHo4J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHo4J.png" alt="(the carrier thing)" /></a></p> <p>So my question is if there's a way to do it in the Xcode simulator and if so how?</p>
[ { "answer_id": 74288468, "author": "Naqeeb Ahmed", "author_id": 6737277, "author_profile": "https://Stackoverflow.com/users/6737277", "pm_score": 1, "selected": false, "text": "simctl" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16601458/" ]
74,288,272
<p>I would like to add or remove Reaction Roles from a JSON file on Discord. I would like that when a user clicks on the emoji, the corresponding role is added from a JSON file that links the role and the emoji.</p> <p>For the moment my code works but it's not clean.</p> <p>Here is my code :</p> <pre class="lang-js prettyprint-override"><code>const Discord = require('discord.js'); const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] }); const { token } = require('./config.json'); const Roles = require('/roles.json'); client.on(&quot;ready&quot;, () =&gt; { console.log(&quot;Bot opérationnel&quot;); }); client.on('message', message =&gt; { if (message.content === 'Choisir un rôle :') { const reactionEmoji1 = message.guild.emojis.cache.find(emoji =&gt; emoji.name === 'FR'); const reactionEmoji2 = message.guild.emojis.cache.find(emoji =&gt; emoji.name === 'UK'); message.react(reactionEmoji1); message.react(reactionEmoji2); } }); client.on(&quot;messageReactionAdd&quot;, (reaction, user) =&gt; { if(user.bot) return; console.log(&quot;Réaction ajoutée&quot;); if(reaction.message.id === &quot;1037314191163412573&quot;){ if(reaction.emoji.name === &quot;FR&quot;){ var member = reaction.message.guild.members.cache.find(member =&gt; member.id === user.id); // Va récuperer le membre du serveur member.roles.add(&quot;1036583426620399647&quot;).then (mbr =&gt; { // Assigne le role console.log(&quot;Role attribué avec succès pour&quot; + mbr.displayName); }) .catch(err =&gt; { console.log(&quot;Le role n'a pas pu etre attribué :&quot; + err); }); } if(reaction.emoji.name === &quot;UK&quot;){ var member = reaction.message.guild.members.cache.find(member =&gt; member.id === user.id); // Va récuperer le membre du serveur member.roles.add(&quot;1036583684247134208&quot;).then (mbr =&gt; { // Assigne le role console.log(&quot;Role attribué avec succès pour&quot; + mbr.displayName); }) .catch(err =&gt; { console.log(&quot;Le role n'a pas pu etre attribué :&quot; + err); }); } } }); client.on(&quot;messageReactionRemove&quot;, (reaction, user) =&gt; { if(user.bot) return; console.log(&quot;Réaction supprimée&quot;); if(reaction.message.id === &quot;1037314191163412573&quot;){ if(reaction.emoji.name === &quot;FR&quot;){ var member = reaction.message.guild.members.cache.find(member =&gt; member.id === user.id); // Va récuperer le membre du serveur member.roles.remove(&quot;1036583426620399647&quot;).then (mbr =&gt; { // Assigne le role console.log(&quot;Role supprimé avec succès pour&quot; + mbr.displayName); }).catch(err =&gt; { console.log(&quot;Le role n'a pas pu etre attribué :&quot; + err); }); } if(reaction.emoji.name === &quot;UK&quot;){ var member = reaction.message.guild.members.cache.find(member =&gt; member.id === user.id); // Va récuperer le membre du serveur member.roles.remove(&quot;1036583684247134208&quot;).then (mbr =&gt; { // Assigne le role console.log(&quot;Role supprimé avec succès pour&quot; + mbr.displayName); }).catch(err =&gt; { console.log(&quot;Le role n'a pas pu etre attribué :&quot; + err); }); } } }); client.login(token); </code></pre> <p>And here is the JSON file :</p> <pre class="lang-json prettyprint-override"><code>{ &quot;message&quot;: &quot;1037314191163412573&quot;, &quot;channel&quot;: &quot;1037311658416152616&quot;, &quot;reactions&quot;: [ { &quot;emoji&quot;: &quot;FR&quot;, &quot;role&quot;: &quot;1036583426620399647&quot; }, { &quot;emoji&quot;: &quot;UK&quot;, &quot;role&quot;: &quot;1036583684247134208&quot; } ] } </code></pre>
[ { "answer_id": 74288468, "author": "Naqeeb Ahmed", "author_id": 6737277, "author_profile": "https://Stackoverflow.com/users/6737277", "pm_score": 1, "selected": false, "text": "simctl" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19574385/" ]
74,288,295
<p>I have 5 cards that have the 'data-price' attribute assigned,. I need to output all the values of these attributes via js,. my code outputs only the first value of the card.</p> <p>Why doesn't it work?</p> <p>Here is my code ////////////////////////////////////////////////////////////////////////////////////////////////////////</p> <pre><code>&lt;button class=&quot;sort&quot;&gt;Сортируй!&lt;/button&gt; &lt;div class=&quot;card&quot;&gt; &lt;!-- 1 card --&gt; &lt;div class=&quot;first_card&quot;&gt; &lt;div class=&quot;img_card&quot;&gt; &lt;img src=&quot;1.png&quot; alt=&quot;machine&quot;&gt; &lt;/div&gt; &lt;div class=&quot;text_card&quot;&gt; &lt;div class=&quot;desc&quot;&gt; Foxxx Kitsune Mini Black &lt;br&gt; Vintage RCA &lt;/div&gt; &lt;div class=&quot;price&quot; data-prise=&quot;6000&quot;&gt; 6000 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- 2 card --&gt; &lt;div class=&quot;first_card&quot;&gt; &lt;div class=&quot;img_card&quot;&gt; &lt;img src=&quot;1.png&quot; alt=&quot;machine&quot;&gt; &lt;/div&gt; &lt;div class=&quot;text_card&quot;&gt; &lt;div class=&quot;desc&quot;&gt; Foxxx Kitsune Mini Black &lt;br&gt; Vintage RCA &lt;/div&gt; &lt;div class=&quot;price&quot; data-prise=&quot;5000&quot;&gt; 5000 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- 3 card --&gt; &lt;div class=&quot;first_card&quot;&gt; &lt;div class=&quot;img_card&quot;&gt; &lt;img src=&quot;1.png&quot; alt=&quot;machine&quot;&gt; &lt;/div&gt; &lt;div class=&quot;text_card&quot;&gt; &lt;div class=&quot;desc&quot;&gt; Foxxx Kitsune Mini Black &lt;br&gt; Vintage RCA &lt;/div&gt; &lt;div class=&quot;price&quot; data-prise=&quot;4000&quot;&gt; 4000 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- 4 card --&gt; &lt;div class=&quot;first_card&quot;&gt; &lt;div class=&quot;img_card&quot;&gt; &lt;img src=&quot;1.png&quot; alt=&quot;machine&quot;&gt; &lt;/div&gt; &lt;div class=&quot;text_card&quot;&gt; &lt;div class=&quot;desc&quot;&gt; Foxxx Kitsune Mini Black &lt;br&gt; Vintage RCA &lt;/div&gt; &lt;div class=&quot;price&quot; data-prise=&quot;3000&quot;&gt; 3000 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- 5 card --&gt; &lt;div class=&quot;first_card&quot;&gt; &lt;div class=&quot;img_card&quot;&gt; &lt;img src=&quot;1.png&quot; alt=&quot;machine&quot;&gt; &lt;/div&gt; &lt;div class=&quot;text_card&quot;&gt; &lt;div class=&quot;desc&quot;&gt; Foxxx Kitsune Mini Black &lt;br&gt; Vintage RCA &lt;/div&gt; &lt;div class=&quot;price&quot; data-prise=&quot;2000&quot;&gt; 2000 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>.card { height: 100vh; display: flex; justify-content: center; align-items: center; } .first_card { opacity: 0; margin: 20px; } .field { justify-content: center; display: flex; } </code></pre> <pre><code>const number = document.querySelector(&quot;#tentacles&quot;); const btn = document.querySelector('.sort') const card = document.querySelectorAll('.first_card') const price = document.querySelector('.price').getAttribute('data-prise'); btn.addEventListener('click', () =&gt; { for(let i = 0; i &lt; 6; i++) { console.log(price) } }) </code></pre>
[ { "answer_id": 74288468, "author": "Naqeeb Ahmed", "author_id": 6737277, "author_profile": "https://Stackoverflow.com/users/6737277", "pm_score": 1, "selected": false, "text": "simctl" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20324239/" ]
74,288,296
<p>I have DriveItem that checkedOut by User1 with graph call</p> <pre><code>https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{item-id}?expand=activities </code></pre> <p>I have got my list of activities</p> <pre><code>{... &quot;id&quot;: &quot;01VMODTUDZVXS2MQJORNEYUTEPWOJ7VSB&quot;, ... &quot;activities&quot;: [ { &quot;@sharePoint.localizedRelativeTime&quot;: &quot;1|0|3|38&quot;, &quot;action&quot;: { &quot;checkin&quot;: {}, &quot;edit&quot;: {}, &quot;version&quot;: { &quot;newVersion&quot;: &quot;3.0&quot; } }, &quot;actor&quot;: { &quot;user&quot;: { &quot;email&quot;: &quot;xxx.onmicrosoft.com&quot;, &quot;displayName&quot;: &quot;Administrator)&quot;, &quot;self&quot;: {}, &quot;userPrincipalName&quot;: &quot;csgdeveloper@csgdevelopment.onmicrosoft.com&quot; } }, &quot;id&quot;: &quot;oFlcWLu82kiAeJgJAAAAAA==&quot;, &quot;times&quot;: { &quot;recordedTime&quot;: &quot;2022-11-02T10:16:45Z&quot; } ... } ], ... ... &quot;shared&quot;: { &quot;scope&quot;: &quot;users&quot; } } </code></pre> <p>if I try the same in my project using SDK for C#</p> <pre><code>var activities = await this.GraphServiceClient.Drives[driveId].Items[driveItemId] .Request() .Expand(&quot;activities&quot;) .GetAsync(); </code></pre> <p>I get an exception with message:</p> <p><strong>Parsing OData Select and Expand failed: Could not find a property named 'activities' on type 'microsoft.graph.driveItem'.</strong></p>
[ { "answer_id": 74288468, "author": "Naqeeb Ahmed", "author_id": 6737277, "author_profile": "https://Stackoverflow.com/users/6737277", "pm_score": 1, "selected": false, "text": "simctl" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12747298/" ]
74,288,383
<p>My pandas data frame contains several columns, some of them have missing values which show up as a <code>?</code> sign. I want to run a for loop to print how much <code>?</code> there is in each columns of the data. I'm doing something like this:</p> <pre><code>colnames = ['col_1','col_2','col_3'] for i in colnames: print(f'In the {i} feature, the value - ? - occurs {data.i.value_counts()[&quot;?&quot;]} times') </code></pre> <p>The error I get is :</p> <pre><code>AttributeError: 'DataFrame' object has no attribute 'i' </code></pre> <p>So I think that problem is with this part - <code>data.i.value_counts()</code>, I tried <code>data[i].value_counts()</code> but that didn't work eaither..</p>
[ { "answer_id": 74288428, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "value_counts" }, { "answer_id": 74288469, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 1, "selected": false, "text": "data" } ]
2022/11/02
[ "https://Stackoverflow.com/questions/74288383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17945841/" ]