qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,582,719
<p>I have an xml file that looks something like this:</p> <pre><code>&lt;xml&gt; &lt;trkseg&gt; &lt;note&gt; &lt;to&gt;A&lt;/to&gt; &lt;from&gt;B&lt;/from&gt; &lt;body&gt; keep this &lt;/body&gt; &lt;/trkseg&gt; &lt;trkseg&gt; &lt;/note&gt; ... &lt;/trkseg&gt; &lt;/xml&gt; </code></pre> <p>And I wanted to remove all the following code. This combination of tags can occur more than once in the file:</p> <pre><code>&lt;/trkseg&gt; &lt;trkseg&gt; </code></pre> <p>Any tips on how to fix this?</p> <p>What I expected was this:</p> <pre><code>&lt;xml&gt; &lt;trkseg&gt; &lt;note&gt; &lt;to&gt;A&lt;/to&gt; &lt;from&gt;B&lt;/from&gt; &lt;body&gt; keep this &lt;/body&gt; &lt;/note&gt; ... &lt;/trkseg&gt; &lt;/xml&gt; </code></pre> <p>I tried using this sed command but doesn't work the way I want:</p> <pre><code>sed -i '' -e '/&lt;\/trkseg&gt;/,/&lt;trkseg&gt;/d' my-file.xml </code></pre> <p>I get this result:</p> <pre><code>&lt;xml&gt; &lt;trkseg&gt; &lt;note&gt; &lt;to&gt;A&lt;/to&gt; &lt;from&gt;B&lt;/from&gt; &lt;body&gt; keep this &lt;/body&gt; &lt;/note&gt; ... </code></pre> <pre><code></code></pre>
[ { "answer_id": 74583329, "author": "Roby Raju Oommen", "author_id": 14399782, "author_profile": "https://Stackoverflow.com/users/14399782", "pm_score": 0, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb\\/([^\\/]+)\\/?([^\\/]+)$', 'kb?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n" }, { "answer_id": 74630994, "author": "Moishy", "author_id": 1810810, "author_profile": "https://Stackoverflow.com/users/1810810", "pm_score": 1, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb$', 'index.php?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n function add_query_vars_filter( $vars ){\n $vars[] = \"kb_cat\";\n $vars[] = \"kb_seq\";\n return $vars;\n}\nadd_filter( 'query_vars', 'add_query_vars_filter' );\n function include_custom_template($template){\n\n if(get_query_var('kb_cat') && get_query_var('kb_seq')){\n $template = get_template_directory() .\"/my-custom-template.php\";\n } \n \n return $template; \n}\n\nadd_filter('template_include', 'include_custom_template');\n functions.php" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5376591/" ]
74,582,740
<p>I have this code below which loops <code>rsync</code> several times in different directories:</p> <pre><code>for (( i=0; i&lt;6; i++ )); do rsync /source-${i} /remote-destination done </code></pre> <p>However there is a problem: when it executes the first <code>rsync</code>, it asks me the password of the remove server and then it starts transfering the files. Only after it finishes transfering all the files it executes the loop a second time, asks me the password of the remote server again (no problem, I can afford typing the password every single time) and then I need to wait the transfer to happen so it can continue.</p> <p>I would like the loop to continue, without waiting... I tried using the <code>&amp;</code> char at the end of the command line to send it to background however if I do that, I cant type the password of the remote server!</p> <p>Any idea how I can solve this? I really want to type myself the password every single time, this is not a problem. The problem is that or the loop waits every single <code>rsync</code> to be completed or it sends the password prompt to the background if I use <code>&amp;</code>.</p>
[ { "answer_id": 74583329, "author": "Roby Raju Oommen", "author_id": 14399782, "author_profile": "https://Stackoverflow.com/users/14399782", "pm_score": 0, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb\\/([^\\/]+)\\/?([^\\/]+)$', 'kb?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n" }, { "answer_id": 74630994, "author": "Moishy", "author_id": 1810810, "author_profile": "https://Stackoverflow.com/users/1810810", "pm_score": 1, "selected": false, "text": "function wdm_add_rewrite_rules() {\n add_rewrite_rule( '^kb$', 'index.php?kb_cat=$matches[1]&kb_seq=1', 'top');\n}\nadd_action('init', 'wdm_add_rewrite_rules');\n function add_query_vars_filter( $vars ){\n $vars[] = \"kb_cat\";\n $vars[] = \"kb_seq\";\n return $vars;\n}\nadd_filter( 'query_vars', 'add_query_vars_filter' );\n function include_custom_template($template){\n\n if(get_query_var('kb_cat') && get_query_var('kb_seq')){\n $template = get_template_directory() .\"/my-custom-template.php\";\n } \n \n return $template; \n}\n\nadd_filter('template_include', 'include_custom_template');\n functions.php" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15974517/" ]
74,582,780
<p>I would like to delete a row/column from a 2d DataFrame. Let's assume the DataFrame looks like this:</p> <pre><code>animal cat dog hedgehog time 0 1 1 0 1 2 0 1 </code></pre> <p>How to get rid of let's say the whole dog thingy to get something like that:</p> <pre><code>animal cat hedgehog time 0 1 0 1 2 1 </code></pre> <p>I tried e.g. <code>df.drop()</code> with a lot of variations but haven't fully understood pandas yet.</p>
[ { "answer_id": 74582825, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "df.drop('dog',axis=1)\n inplace df.drop('dog',axis=1,inplace=True)\n df.drop(['dog','cat'],axis=1,inplace=True)\n" }, { "answer_id": 74591724, "author": "k1m2njun", "author_id": 14012812, "author_profile": "https://Stackoverflow.com/users/14012812", "pm_score": 0, "selected": false, "text": "df.drop(columns='dog', inplace=True)\n df.drop(columns=['dog', 'cat'], inplace=True)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974685/" ]
74,582,794
<p>In Open CV or with Pillow library how can we improve below images for tesseract.</p> <p><a href="https://i.stack.imgur.com/qSvIJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qSvIJ.jpg" alt="Images" /></a></p> <p><a href="https://i.stack.imgur.com/IgT77.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IgT77.jpg" alt="Images" /></a></p> <p><a href="https://i.stack.imgur.com/KyUMQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KyUMQ.jpg" alt="Images" /></a></p> <p>I tried below code with multiple options like thresholding, blur, enchance, however not able to improve.</p> <pre><code>img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print(pytesseract.image_to_string(img)) img_medianBlur = cv2.blur(img, (3 , 3)) print(pytesseract.image_to_string(img_medianBlur)) blur = cv2.GaussianBlur(img,(5,5),0) ret3,th3 = cv2.threshold(img,150,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) print(pytesseract.image_to_string(th3)) </code></pre>
[ { "answer_id": 74582825, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "df.drop('dog',axis=1)\n inplace df.drop('dog',axis=1,inplace=True)\n df.drop(['dog','cat'],axis=1,inplace=True)\n" }, { "answer_id": 74591724, "author": "k1m2njun", "author_id": 14012812, "author_profile": "https://Stackoverflow.com/users/14012812", "pm_score": 0, "selected": false, "text": "df.drop(columns='dog', inplace=True)\n df.drop(columns=['dog', 'cat'], inplace=True)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4324496/" ]
74,582,805
<p>Given the jagged Array, we are asked to use a looping statement to display the character based on the position. Display a &quot;*&quot; if the position matched or a &quot; &quot; if it doesn't.</p> <pre><code> int arr [][] = {{0,4,8,12,13,14,15,18,19,20,21,24,28}, {0,4,7,9,12,16,18,22,25,27}, {0,1,2,3,4,6,10,12,16,18,22,26}, {0,4,6,10,12,13,14,15,18,19,20,21,26}, {0,4,6,7,8,9,10,12,18,26}, {0,4,6,10,12,18,26}}; </code></pre> <p>I have created a program, but the output is not what I expected and I am now stuck.</p> <pre><code> for (int i = 0; i &lt; arr.length; i++) { for (int j = 0; j &lt; arr[i].length - 1; j++) { for (int spaces = 1; spaces &lt; arr[i][j + 1]-arr[i][j]; spaces++) { System.out.print(&quot; &quot;); } System.out.print(&quot;*&quot;); } System.out.println(); } </code></pre> <p>The output was suppose to be Happy but I get: <a href="https://i.stack.imgur.com/2dcIl.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74582825, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 2, "selected": false, "text": "df.drop('dog',axis=1)\n inplace df.drop('dog',axis=1,inplace=True)\n df.drop(['dog','cat'],axis=1,inplace=True)\n" }, { "answer_id": 74591724, "author": "k1m2njun", "author_id": 14012812, "author_profile": "https://Stackoverflow.com/users/14012812", "pm_score": 0, "selected": false, "text": "df.drop(columns='dog', inplace=True)\n df.drop(columns=['dog', 'cat'], inplace=True)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607200/" ]
74,582,831
<p>Im learning about else and else if statements and combining them with Try Parse.</p> <p>Basically, I ask the user to tell me the temperature outside and based on the answer I give him the output. If instead of numbers, he uses the words, Try Parse gives out the reply that the value entered is not a number, BUT, in that case, the last ELSE IF statement which is set to &quot;&lt;15&quot; is still executing! Why is it executing when the input is a string and not a number, shouldnt the code just stop at ''Value entered is not a number'' and stop it, instead for some reason the last bit executes as well. Please take a look and share your opinion. Thanks!</p> <pre><code> { Console.WriteLine(&quot;Enter the temperature of today: &quot;); string temperature = Console.ReadLine(); int numTemp; int number; if (int.TryParse(temperature, out number)) { numTemp = number; } else { numTemp = 0; Console.WriteLine(&quot;Value entered, was no number. 0 set as temperature&quot;); } if (numTemp &gt; 15) { Console.WriteLine(&quot;The jacket is completely unncessarry for this temperature.&quot;); } else if (numTemp == 15) { Console.WriteLine(&quot;Just the sweater is gonna be perfectly okay for you.&quot;); } else if (numTemp &lt; 15) { Console.WriteLine(&quot;You need a jacket, my friend&quot;); } else { Console.WriteLine(&quot;The weather is for an apocalypse!&quot;); } Console.Read(); } </code></pre>
[ { "answer_id": 74582976, "author": "Okke Hendriks", "author_id": 811059, "author_profile": "https://Stackoverflow.com/users/811059", "pm_score": 1, "selected": false, "text": "TryParse else\n{\n numTemp = 0;\n Console.WriteLine(\"Value entered, was no number. 0 set as temperature\");\n\n // NO RETURN HERE, THE REMAINDER OF THE FUNCTION IS ALSO EXECUTED.\n}\n else if (numTemp < 15)" }, { "answer_id": 74583168, "author": "Rojhat Sefdin", "author_id": 19958957, "author_profile": "https://Stackoverflow.com/users/19958957", "pm_score": 1, "selected": false, "text": "string temperature = Console.ReadLine();\n\nint num;\n\nif (int.TryParse(temperature, out num))\n{\n\n\n if (num > 15)\n {\n Console.WriteLine(\"The jacket is completely unncessarry for this temperature.\");\n }\n else if (num == 15)\n {\n Console.WriteLine(\"Just the sweater is gonna be perfectly okay for you.\");\n }\n else if (num < 15)\n {\n Console.WriteLine(\"You need a jacket, my friend\");\n }\n else\n {\n Console.WriteLine(\"The weather is for an apocalypse!\");\n }\n\n}\nelse\n{\n\n Console.WriteLine(\"Value entered, was no number. 0 set as temperature\");\n}\n\n\nConsole.Read();\n" }, { "answer_id": 74583514, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "num = 0 else num true" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14076730/" ]
74,582,832
<p>Suppost I have this index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;link rel=&quot;prefetch&quot; as=&quot;image&quot; href=&quot;./assets/footer.jpg&quot; /&gt; &lt;script async type=&quot;text/javascript&quot; src=&quot;https://code.jquery.com/jquery-3.3.1.js&quot; &gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;./style.css&quot; /&gt; &lt;/head&gt; &lt;body&gt; &lt;script src=&quot;./utils.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>According to this <a href="https://docs.google.com/document/d/1bCDuq9H1ih9iNjgzyAL0gpwNFiEP4TZS-YLRp_RuMlc/edit#" rel="nofollow noreferrer">doc</a> async script has <strong>Low</strong> priority, and css has <strong>Highest</strong> priority, so why does the jquery-3.3.1.js was downloaded before style.css downloaded when I Ctrl+F5 to refresh the whole page? (And you can see footer.jpg was at the end due to <strong>Lowest</strong> priority because of <strong>prefetch</strong>, but why async script not works in the same way?)</p> <p><a href="https://i.stack.imgur.com/YP71P.png" rel="nofollow noreferrer">click me to see the result</a></p> <p>Could anyone tell me what's going wrong? My Chrome version: 107.0.5304.107</p> <p>To me, the reasonable order should be:</p> <ul> <li>localhost (Highest)</li> <li>style.css (Highest)</li> <li>utils.js (High)</li> <li>jquery-3.3.1.js (Low)</li> <li>footer.jpg (Lowest)</li> </ul>
[ { "answer_id": 74582976, "author": "Okke Hendriks", "author_id": 811059, "author_profile": "https://Stackoverflow.com/users/811059", "pm_score": 1, "selected": false, "text": "TryParse else\n{\n numTemp = 0;\n Console.WriteLine(\"Value entered, was no number. 0 set as temperature\");\n\n // NO RETURN HERE, THE REMAINDER OF THE FUNCTION IS ALSO EXECUTED.\n}\n else if (numTemp < 15)" }, { "answer_id": 74583168, "author": "Rojhat Sefdin", "author_id": 19958957, "author_profile": "https://Stackoverflow.com/users/19958957", "pm_score": 1, "selected": false, "text": "string temperature = Console.ReadLine();\n\nint num;\n\nif (int.TryParse(temperature, out num))\n{\n\n\n if (num > 15)\n {\n Console.WriteLine(\"The jacket is completely unncessarry for this temperature.\");\n }\n else if (num == 15)\n {\n Console.WriteLine(\"Just the sweater is gonna be perfectly okay for you.\");\n }\n else if (num < 15)\n {\n Console.WriteLine(\"You need a jacket, my friend\");\n }\n else\n {\n Console.WriteLine(\"The weather is for an apocalypse!\");\n }\n\n}\nelse\n{\n\n Console.WriteLine(\"Value entered, was no number. 0 set as temperature\");\n}\n\n\nConsole.Read();\n" }, { "answer_id": 74583514, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "num = 0 else num true" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15308432/" ]
74,582,838
<p>I have many Tasks, that are running asynchronously</p> <pre><code>Task&lt;bool&gt; task1 = Task.Run&lt;bool&gt;(() =&gt; { return this.addGroupStringToDictionary(&quot;IfcPolyline&quot;); }); Task&lt;bool&gt; task2 = Task.Run&lt;bool&gt;(() =&gt; { return this.addGroupStringToDictionary(&quot;IfcPolyLoop&quot;); }); Task&lt;bool&gt; task3 = Task.Run&lt;bool&gt;(() =&gt; { return this.addGroupStringToDictionary(&quot;IfcAxis2Placement2D&quot;); }); Task&lt;bool&gt; task4 = Task.Run&lt;bool&gt;(() =&gt; { return this.addGroupStringToDictionary(&quot;IfcAxis2Placement3D&quot;); }); </code></pre> <p>Now, I would like to execute other tasks, as soon as some of them finish.</p> <p>Let's say I have 3 tasks that need to be executed after that :</p> <ul> <li><p>task5 needs to be executed when Task1 and Task2 finished.</p> </li> <li><p>task6 needs to be executed when Task3 and Task4 finished.</p> </li> <li><p>task7 needs to be executed when Task1 and Task6 finished.</p> </li> </ul> <p>How can I do that, cause if I use <code>await Task.WhenAll(task1,task2)</code> before calling task5, I also block execution of task6 and task7 ?</p>
[ { "answer_id": 74583275, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 3, "selected": true, "text": "Task.Run await var task1 = Task.Run(() => { /*...*/ });\n\nvar task2 = Task.Run(() => { /*...*/ });\n\nvar task3 = Task.Run(() => { /*...*/ });\n\nvar task4 = Task.Run(() => { /*...*/ });\n\nvar task5 = Task.Run(async () =>\n{\n await Task.WhenAll(task1, task2);\n /*...*/ \n});\n\nvar task6 = Task.Run(async () =>\n{\n await Task.WhenAll(task3, task4);\n /*...*/ \n});\n\nvar task7 = Task.Run(async () =>\n{\n await Task.WhenAll(task1, task6);\n /*...*/ \n});\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7310000/" ]
74,582,852
<p>Struggling to open Office files from a C# application, <strong>.NET 6.</strong> Note this works just fine using .NET framework.</p> <p>The official MS nuget package <code>Microsoft.Office.Interop.Word</code> appears to support only up to Office 2016. Adding the Microsoft Word 16.0 Object Library COM reference appears to not add support either.</p> <pre class="lang-cs prettyprint-override"><code>using Microsoft.Office.Interop.Word; private void button2_Click(object sender, EventArgs e) { var ap = new Microsoft.Office.Interop.Word.Application(); Document document = ap.Documents.Open(@&quot;C:\Users\name\Desktop\test.docx&quot;); ap.Visible = true; } </code></pre> <p>When clicking this button, the following exception is thrown:</p> <blockquote> <p>System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'</p> </blockquote> <p>Is there really no support for the current version of 365?</p> <p>I have verified I have <code>Microsoft.Office.Interop.Word</code> in <code>C:\Windows\assembly\GAC_MSIL.</code></p>
[ { "answer_id": 74584185, "author": "jwilo", "author_id": 20595585, "author_profile": "https://Stackoverflow.com/users/20595585", "pm_score": 2, "selected": true, "text": "object Microsoft Word 16.0 Object Library', substituting " }, { "answer_id": 74586013, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": 0, "selected": false, "text": "Office.dll Microsoft.Office.Interop.Word.dll Add References" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20595585/" ]
74,582,868
<p>I need to be able to append multiple values from a <code>CSV</code> file to a dictionary that has three keys. The keys are <code>morning</code>, <code>midday</code>, and <code>night</code>. The values should come from each row of the <code>CSV</code> file.</p> <p>Ideally, it should look like below.</p> <p>I can't use <code>numpy</code> or <code>csv</code> modules, so those options are not available. It has to work with no imports, and I'm unsure with dictionaries and how to approach this to get the output I need.</p> <p>Here is a sample of what the <code>CSV</code> file looks like:</p> <p><img src="https://i.stack.imgur.com/whHIR.png" alt="" /></p> <pre class="lang-py prettyprint-override"><code>{ 'morning': {[5, 5, 10, 17, 20, 21]}, 'midday': {[10, 20, 25, 15, 8, 3]}, 'night': {[3, 5, 2, 7, 15, 29]} } </code></pre> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>time_list = [] time_dict = {} with open('stats.csv', 'r') as data_file: headers = data_file.readline() for line in data_file: Time, VS = line.split(',') time_list.append(int(VS)) time_dict[Time] = time_dict.get(Time, 0) + int(VS) </code></pre> <p>Appending to the list produces each value like it should, i.e.:</p> <pre class="lang-py prettyprint-override"><code>[2, 3, 4, 5, 6, 7, 8] </code></pre> <p>But for the dictionary, it does not show each value individually for the key it is attached to. Instead, it will take all the values for each key and add them together.</p> <p>Printing the dictionary shows the following:</p> <pre class="lang-py prettyprint-override"><code>{'morning': 2097, 'midday': 1240, 'night': 1533} </code></pre> <p>I'm unsure of how to approach this to get the dictionary to look like the following:</p> <pre class="lang-py prettyprint-override"><code>{ 'morning':{[5, 5, 10, 17, 20, 21]}, 'midday': {[10, 20, 25, 15, 8, 3]}, 'night': {[3, 5, 2, 7, 15, 29]} } </code></pre> <p>Note: Many of the answers I have found use the <code>csv</code> module, which I unfortunately cannot use for this. I have to use no imports for this solution.</p> <p>Also keytype of the dictionary must be int so I can peform math operations on the dictionary to find out the max, min, average etc</p>
[ { "answer_id": 74584185, "author": "jwilo", "author_id": 20595585, "author_profile": "https://Stackoverflow.com/users/20595585", "pm_score": 2, "selected": true, "text": "object Microsoft Word 16.0 Object Library', substituting " }, { "answer_id": 74586013, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": 0, "selected": false, "text": "Office.dll Microsoft.Office.Interop.Word.dll Add References" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10733231/" ]
74,582,893
<p>List that contains strings (<a href="https://i.stack.imgur.com/pOzik.png" rel="nofollow noreferrer">https://i.stack.imgur.com/pOzik.png</a>)</p> <p>This is a string list of items and I want to extract the dictionary {} that is from the 6th character and after.</p> <p>Should I convert list to dictionary?</p> <pre class="lang-py prettyprint-override"><code>data= '[\n {\n &quot;registration_number&quot;: &quot;aj13870&quot;,\n &quot;status&quot;: &quot;registreret&quot;,\n &quot;status_date&quot;: &quot;2013-10-07t10:33:46.000+02:00&quot;,\n &quot;type&quot;: &quot;personbil&quot;,\n &quot;use&quot;: &quot;privat personk\\u00f8rsel&quot;,\n &quot;first_registration&quot;: &quot;2013-10-07+02:00&quot;,\n &quot;vin&quot;: &quot;wdd2042021g129692&quot;,\n &quot;own_weight&quot;: null,\n &quot;cerb_weight&quot;: 1655,\n &quot;total_weight&quot;: 2195,\n &quot;axels&quot;: 2,\n &quot;pulling_axels&quot;: 1,\n &quot;seats&quot;: 5,\n &quot;coupling&quot;: false,\n &quot;trailer_maxweight_nobrakes&quot;: 750,\n &quot;trailer_maxweight_withbrakes&quot;: 1800,\n &quot;doors&quot;: 4,\n &quot;make&quot;: &quot;mercedes-benz&quot;,\n &quot;model&quot;: &quot;c-klasse&quot;,\n &quot;variant&quot;: &quot;220 cdi blueefficiency t&quot;,\n &quot;model_type&quot;: &quot;204 k&quot;,\n &quot;model_year&quot;: 2013,\n &quot;color&quot;: &quot;gr\\u00e5&quot;,\n &quot;chassis_type&quot;: &quot;stationcar&quot;,\n &quot;engine_cylinders&quot;: 4,\n &quot;engine_volume&quot;: 2143,\n &quot;engine_power&quot;: 125,\n &quot;fuel_type&quot;: &quot;diesel&quot;,\n &quot;registration_zipcode&quot;: &quot;&quot;,\n &quot;vehicle_id&quot;: 9000000000384590,\n &quot;mot_info&quot;: {\n &quot;type&quot;: &quot;periodisksyn&quot;,\n &quot;date&quot;: &quot;2021-10-06&quot;,\n &quot;result&quot;: &quot;godkendt&quot;,\n &quot;status&quot;: &quot;aktiv&quot;,\n &quot;status_date&quot;: &quot;2021-10-06&quot;,\n &quot;mileage&quot;: 106\n },\n &quot;is_leasing&quot;: false,\n &quot;leasing_from&quot;: null,\n &quot;leasing_to&quot;: null\n }\n]' </code></pre> <p>If I try to find the index of the keys or values but it is a list of strings. I tried to extract the keys and values from the dictionary but it doesn't work.</p>
[ { "answer_id": 74582937, "author": "Amin", "author_id": 10281248, "author_profile": "https://Stackoverflow.com/users/10281248", "pm_score": 1, "selected": false, "text": "list json.loads() import json\n\n\ntext = '[\\n {\\n \"registration_number\": \"aj13870\",\\n \"status\": \"registreret\",\\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\\n \"type\": \"personbil\",\\n \"use\": \"privat personk\\\\u00f8rsel\",\\n \"first_registration\": \"2013-10-07+02:00\",\\n \"vin\": \"wdd2042021g129692\",\\n \"own_weight\": null,\\n \"cerb_weight\": 1655,\\n \"total_weight\": 2195,\\n \"axels\": 2,\\n \"pulling_axels\": 1,\\n \"seats\": 5,\\n \"coupling\": false,\\n \"trailer_maxweight_nobrakes\": 750,\\n \"trailer_maxweight_withbrakes\": 1800,\\n \"doors\": 4,\\n \"make\": \"mercedes-benz\",\\n \"model\": \"c-klasse\",\\n \"variant\": \"220 cdi blueefficiency t\",\\n \"model_type\": \"204 k\",\\n \"model_year\": 2013,\\n \"color\": \"gr\\\\u00e5\",\\n \"chassis_type\": \"stationcar\",\\n \"engine_cylinders\": 4,\\n \"engine_volume\": 2143,\\n \"engine_power\": 125,\\n \"fuel_type\": \"diesel\",\\n \"registration_zipcode\": \"\",\\n \"vehicle_id\": 9000000000384590,\\n \"mot_info\": {\\n \"type\": \"periodisksyn\",\\n \"date\": \"2021-10-06\",\\n \"result\": \"godkendt\",\\n \"status\": \"aktiv\",\\n \"status_date\": \"2021-10-06\",\\n \"mileage\": 106\\n },\\n \"is_leasing\": false,\\n \"leasing_from\": null,\\n \"leasing_to\": null\\n }\\n]'\ntext_list = json.loads(text)\n print(text_list[0])\n" }, { "answer_id": 74582941, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "\njson.loads('[\\n {\\n \"registration_number\": \"aj13870\",\\n \"status\": \"registreret\",\\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\\n \"type\": \"personbil\",\\n \"use\": \"privat personk\\\\u00f8rsel\",\\n \"first_registration\": \"2013-10-07+02:00\",\\n \"vin\": \"wdd2042021g129692\",\\n \"own_weight\": null,\\n \"cerb_weight\": 1655,\\n \"total_weight\": 2195,\\n \"axels\": 2,\\n \"pulling_axels\": 1,\\n \"seats\": 5,\\n \"coupling\": false,\\n \"trailer_maxweight_nobrakes\": 750,\\n \"trailer_maxweight_withbrakes\": 1800,\\n \"doors\": 4,\\n \"make\": \"mercedes-benz\",\\n \"model\": \"c-klasse\",\\n \"variant\": \"220 cdi blueefficiency t\",\\n \"model_type\": \"204 k\",\\n \"model_year\": 2013,\\n \"color\": \"gr\\\\u00e5\",\\n \"chassis_type\": \"stationcar\",\\n \"engine_cylinders\": 4,\\n \"engine_volume\": 2143,\\n \"engine_power\": 125,\\n \"fuel_type\": \"diesel\",\\n \"registration_zipcode\": \"\",\\n \"vehicle_id\": 9000000000384590,\\n \"mot_info\": {\\n \"type\": \"periodisksyn\",\\n \"date\": \"2021-10-06\",\\n \"result\": \"godkendt\",\\n \"status\": \"aktiv\",\\n \"status_date\": \"2021-10-06\",\\n \"mileage\": 106\\n },\\n \"is_leasing\": false,\\n \"leasing_from\": null,\\n \"leasing_to\": null\\n }\\n]')\n" }, { "answer_id": 74582951, "author": "SollyBunny", "author_id": 7483019, "author_profile": "https://Stackoverflow.com/users/7483019", "pm_score": 0, "selected": false, "text": "[\n {\n \"registration_number\": \"aj13870\",\n \"status\": \"registreret\",\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\n \"type\": \"personbil\",\n \"use\": \"privat personk\\u00f8rsel\",\n \"first_registration\": \"2013-10-07+02:00\",\n \"vin\": \"wdd2042021g129692\",\n \"own_weight\": null,\n \"cerb_weight\": 1655,\n \"total_weight\": 2195,\n \"axels\": 2,\n \"pulling_axels\": 1,\n \"seats\": 5,\n \"coupling\": false,\n \"trailer_maxweight_nobrakes\": 750,\n \"trailer_maxweight_withbrakes\": 1800,\n \"doors\": 4,\n \"make\": \"mercedes-benz\",\n \"model\": \"c-klasse\",\n \"variant\": \"220 cdi blueefficiency t\",\n \"model_type\": \"204 k\",\n \"model_year\": 2013,\n \"color\": \"gr\\u00e5\",\n \"chassis_type\": \"stationcar\",\n \"engine_cylinders\": 4,\n \"engine_volume\": 2143,\n \"engine_power\": 125,\n \"fuel_type\": \"diesel\",\n \"registration_zipcode\": \"\",\n \"vehicle_id\": 9000000000384590,\n \"mot_info\": {\n \"type\": \"periodisksyn\",\n \"date\": \"2021-10-06\",\n \"result\": \"godkendt\",\n \"status\": \"aktiv\",\n \"status_date\": \"2021-10-06\",\n \"mileage\": 106\n },\n \"is_leasing\": false,\n \"leasing_from\": null,\n \"leasing_to\": null\n }\n]\n import json\ntext = ...\ndata = json.loads(text)\ndata = data[0] # the data is wrapped in a list\nprint(data)\nprint(data.keys())\nprint(data.items())\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607225/" ]
74,582,909
<p>Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end?</p> <p>Input description: Input a positive integer N. ex.5 / ex.100</p> <p>Output description: The maximum number of sodas that can be drunk, and must have a newline character at the end. ex.7 / ex.149 `</p> <pre><code>n = int(input()) a = n-3 sum = 0 while a &gt; 2 : sum += 1 a -= 3 print(f'{n+sum}') if a == 2 : print(f'{n+sum+1}') </code></pre> <p>`</p> <p>I used while to finish the code which is on above, but I input 5 and output 6,and it is actually to be 7.The other side, I input 100 and output 132. Actually, the correct answer is 149.</p>
[ { "answer_id": 74582990, "author": "kuro", "author_id": 5293112, "author_profile": "https://Stackoverflow.com/users/5293112", "pm_score": 2, "selected": true, "text": "def get_total_cans(n):\n s = n # we can get at least n cans\n while n > 2:\n s += 1\n n -= 3 # 3 exchanged\n n += 1 # got 1 for the exchange\n return s\n\nn = int(input())\nprint(get_total_cans(n))\n a a" }, { "answer_id": 74583062, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "def dr_cans(full, empty=0):\n # if we have at least 3 empty cans, exchange them for a full one\n if empty >=3:\n return dr_cans(full+1,empty-3)\n # no full cans, and not enough empty ones\n if full == 0:\n return 0\n # at least one full can: drink it and gain an empty one\n return 1 + dr_cans(full-1, empty+1)\n" }, { "answer_id": 74583096, "author": "Cpt.Hook", "author_id": 20599896, "author_profile": "https://Stackoverflow.com/users/20599896", "pm_score": 1, "selected": false, "text": "k N N[k] = floor(M/3) M=N[k-1]+R[k-1] R[k] = M%3 % def compute_num_cans(empty_cans: int, exchange: int = 3) -> tuple:\n \"\"\"\n :param empty_cans: The number of cans to exchange\n :return: tuple of (full_cans, empty_cans), where the empty cans are < exchange rate\n \"\"\"\n leftovers = empty_cans % exchange\n full = empty_cans // exchange\n return full, leftovers\n\n\nEXCHANGE = 3\nNUM_CANS = 51\n\nprint(f'Start with {NUM_CANS} and an exchange rate of {EXCHANGE}:1')\ncurrent_cans = NUM_CANS\ndrunk_cans = NUM_CANS\nleftovers = 0\nsteps = 0\nwhile current_cans >= EXCHANGE:\n full, leftovers = compute_num_cans(current_cans, exchange=EXCHANGE)\n current_cans = full + leftovers\n drunk_cans += full\n steps += 1\n\nprint(f'Cans drunk: {drunk_cans}, leftover cans: {leftovers}.')\nprint(f'A total of {steps} exchanges was needed.')\n # Start with 51 and an exchange rate of 3:1\n# Cans drunk: 76, leftover cans: 0.\n# A total of 4 exchanges was needed.\n" }, { "answer_id": 74583129, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 0, "selected": false, "text": "def numWaterBottles(numBottles: int, numExchange: int) -> int:\n ans=numBottles #Initial bottles he/she will drink\n while numBottles>=numExchange: #If numBottles<numExchange exit the while loop\n remainder=numBottles%numExchange #remaining bottles which is not change\n numBottles//=numExchange #The bottles which are changed\n ans+=numBottles #The bottles which are changed added to the answer\n numBottles+=remainder #Remaining bottles==The bottles which is not change+The bottles which are changed\n return ans #Return The answer\n \nprint(numWaterBottles(5,3))\nprint(numWaterBottles(100,3)) \nprint(numWaterBottles(32,4)) #numexchange when different\n 7\n149\n42\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20256456/" ]
74,582,935
<pre class="lang-py prettyprint-override"><code>input=&quot;&quot;&quot; intro: hey,how are you i am fine intro: hey, how are you Hope you are fine &quot;&quot;&quot; output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']] for text in f: text = text.strip() </code></pre>
[ { "answer_id": 74582982, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "input.split(\"intro:\") input.splitlines()" }, { "answer_id": 74582994, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": -1, "selected": false, "text": "re.findall inp = \"\"\"intro: hey,how are you i am fine\n\nintro: hey, how are you Hope you are fine\"\"\"\n\nlines = re.findall(r'^\\w+:\\s*(.*)$', inp, flags=re.M)\nprint(lines)\n ['hey,how are you i am fine', 'hey, how are you Hope you are fine']\n" }, { "answer_id": 74583289, "author": "ukBaz", "author_id": 7721752, "author_profile": "https://Stackoverflow.com/users/7721752", "pm_score": 0, "selected": false, "text": "intro: \\n data = \"\"\"\nintro: hey,how are you\ni am fine\n\nintro:\nhey, how are you\nHope you are fine\n\"\"\"\nonly_intro = []\nfor intro in data.split(\"intro:\"):\n if not intro.isspace():\n only_intro.append(intro.replace('\\n', ' ').lstrip().rstrip())\nprint(only_intro)\n ['hey,how are you i am fine', 'hey, how are you Hope you are fine']\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20476327/" ]
74,582,940
<p>How do I run a C++ program separately in Visual Studio 2022. I used to use python and Visual Studio Code, but because of my current project, I need to learn C++ and every time I organize all my C++ files in a folder, I get an error that says that I cannot have more than 1 main function in the same project. I understand that this is because the Editor is running all programs in a C++ project together, How do I make it run just the one that I am currently working on.</p>
[ { "answer_id": 74582992, "author": "Thomas Weller", "author_id": 480982, "author_profile": "https://Stackoverflow.com/users/480982", "pm_score": 2, "selected": false, "text": ".exe main() main.cpp main()" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15142630/" ]
74,582,952
<p>I have a problem with promised array: I'm calling inside my switch a function which is loading an array from API Example:</p> <pre><code>let sorted = [] let limit = 10 async function loadPage(slcLimit) { let i let filter = document.getElementById(&quot;show-filter&quot;).value if (sorted.length == 0) { switch (filter) { case &quot;1&quot;: let realWoolPromiseAsc = await Promise.resolve(realWool(pagingPouches)) .then((realWoolArr) =&gt; { sorted = realWoolArr.sort((a, b) =&gt; parseFloat(a.realWool) - parseFloat(b.realWool)); return sorted }) break; case &quot;2&quot;: let realWoolPromiseDesc = await Promise.resolve(realWool(pagingPouches)) .then((realWoolArr) =&gt; { sorted = realWoolArr.sort((a, b) =&gt; parseFloat(b.realWool) - parseFloat(a.realWool)); return sorted }) break; } } for (i = startingLimit; i &lt; (startingLimit + limit); i++) { console.log(sorted[i].ID + &quot; - &quot; + sorted[i].price) } } </code></pre> <p>Real wool function</p> <pre><code>window.realWool = async function realWool(pouchArr) { let divider = 1000000000000000000n; let realWoolArray = [] pouchArr.forEach(async pouch =&gt; { let availAmount = await pouchContract.amountAvailable(pouch.pouchID) availAmount = Number(BigInt(availAmount.toString()) * 100n / divider) / 100 availAmount = Math.floor(availAmount * 100) / 100 let rWool = pouch.pouchWool - availAmount realWoolArray.push({pouchID: pouch.pouchID, realWool: rWool, pouchTime: pouch.pouchTime}) //document.getElementById(&quot;lockedText&quot; + pouch.pouchID).innerHTML = &quot;Real WOOL: &lt;span class='black'&gt;&quot; + rWool + &quot;&lt;/span&gt;&quot; }); return realWoolArray } </code></pre> <p>I need to use the <strong>sorting</strong> array inside my for loop but I'm getting undefined. I understand I need to use await or a then block I just have no clue how to use that.</p> <p>Thank you!</p> <p>I've used a <strong>timeout</strong>, but it is not optimal since sometimes the function just return an array of 5 objects and sometimes a hundreds of objects (depends on filters)</p> <pre><code> setTimeout(() =&gt; { for (i = startingLimit; i &lt; (startingLimit + limit); i++) { console.log(sorted[i].ID + &quot; - &quot; + sorted[i].price) } }, 5000); </code></pre>
[ { "answer_id": 74583011, "author": "Steven Spungin", "author_id": 5093961, "author_profile": "https://Stackoverflow.com/users/5093961", "pm_score": 1, "selected": false, "text": "then length sorting then let promisedArray = await Promise.resolve(myFunction())\n .then((realArray) => {\n sorting = realArray.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));\n \n return sorting // <-- return to awaited value\n })\n\n for (let i = 0; i < promisedArray.length; i++) { <-- check spelling\n console.log(promisedArray[i]) //returns the value I need\n }\n await Promise.resolve realWool" }, { "answer_id": 74583673, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 0, "selected": false, "text": "sorted loadPage loadPage let sorted = [] return realWoolPromiseAsc" }, { "answer_id": 74594298, "author": "Thomas", "author_id": 6567275, "author_profile": "https://Stackoverflow.com/users/6567275", "pm_score": 2, "selected": true, "text": "pouchArr.forEach(async pouch => {...}) forEach return realWoolArray loadPage sort window.realWool = async function realWool(pouchArr) {\n const divider = 1000000000000000000n;\n return Promise.all(\n pouchArr.map(async (pouch) => {\n let availAmount = await pouchContract.amountAvailable(pouch.pouchID)\n availAmount = Number(BigInt(availAmount.toString()) * 100n / divider) / 100;\n\n return {\n pouchID: pouch.pouchID, \n realWool: pouch.pouchWool - availAmount, \n pouchTime: pouch.pouchTime\n }\n })\n );\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20206962/" ]
74,582,956
<p>I would like to write simple code to filter records in view based on request information (eg. organization the user belongs to).</p> <p>I started to implemented it as Mixin for Admin views.</p> <pre><code>class OrganizationPermissionMixin: def get_queryset(self, request): query = super().get_queryset(request) if request.user.is_superuser: return query return query.filter( organization__in=request.user.organization_set.all() ) </code></pre> <p>This works fine but when I tried to apply this Mixin on Generic views, I have a signature error as there is no request parameter passed to the <code>get_queryset</code> method:</p> <pre><code>TypeError: OrganizationPermissionMixin.get_queryset() missing 1 required positional argument: 'request' </code></pre> <p>If I adapt the Mixin to:</p> <pre><code>class OrganizationPermissionMixin: def get_queryset(self): query = super().get_queryset() if self.request.user.is_superuser: return query return query.filter( organization__in=self.request.user.organization_set.all() ) </code></pre> <p>It works for generic views such as <code>ListView</code> but now it indeed breaks for <code>ModelAdmin</code> view:</p> <pre><code>OrganizationPermissionMixin.get_queryset() takes 1 positional argument but 2 were given </code></pre> <p>This inconsistency in signature is somehow very frustrating because it requires to duplicate code simply because request passing mechanism is different between Generic and Admin views.</p> <p>My question is: how can I make this Mixin works both for Generic and Admin views. Is there something ready for that in Django? Is it normal it behaves like this or is it an unfortunate design choice?</p>
[ { "answer_id": 74582979, "author": "Amin", "author_id": 10281248, "author_profile": "https://Stackoverflow.com/users/10281248", "pm_score": 1, "selected": false, "text": "...\ndef get_queryset(self, *args, **kwargs):\n request = kwargs.get(\"request\", None)\n if request:\n query = super().get_queryset(request)\n else:\n query = super().get_queryset()\n ...\n" }, { "answer_id": 74582991, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 3, "selected": true, "text": "request ModelAdmin class OrganizationPermissionMixin:\n def get_queryset(self, *args, **kwargs):\n request = args[0] if args else kwargs.get('request') or self.request\n query = super().get_queryset(*args, **kwargs)\n if request.user.is_superuser:\n return query\n return query.filter(organization__user=request.user) kwargs None self.request ModelAdmin" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067485/" ]
74,582,977
<p><a href="https://i.stack.imgur.com/J0yZw.png" rel="nofollow noreferrer">https://i.stack.imgur.com/J0yZw.png</a> This is how it looks for all files with <code>.ts</code>. And in <code>.tsx</code> files it also doesn't work.</p> <p>Other projects in WebStorm work correct but they're written in <code>.js</code> and <code>.jsx</code> only.</p> <p>Also I've tried reinstall WebStorm twice and set all to defaults, that doesn't help at all.</p>
[ { "answer_id": 74582979, "author": "Amin", "author_id": 10281248, "author_profile": "https://Stackoverflow.com/users/10281248", "pm_score": 1, "selected": false, "text": "...\ndef get_queryset(self, *args, **kwargs):\n request = kwargs.get(\"request\", None)\n if request:\n query = super().get_queryset(request)\n else:\n query = super().get_queryset()\n ...\n" }, { "answer_id": 74582991, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 3, "selected": true, "text": "request ModelAdmin class OrganizationPermissionMixin:\n def get_queryset(self, *args, **kwargs):\n request = args[0] if args else kwargs.get('request') or self.request\n query = super().get_queryset(*args, **kwargs)\n if request.user.is_superuser:\n return query\n return query.filter(organization__user=request.user) kwargs None self.request ModelAdmin" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74582977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472862/" ]
74,583,003
<p>I am looking to filter a list according to a predicate and also to filter her child list</p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; class Hotel { private final String city; private final int numberOfStart; private final List&lt;Room&gt; rooms = new ArrayList&lt;&gt;(); public String getCity(){return city;} public int getNumberOfStart(){return numberOfStart;} public List&lt;Room&gt; getRooms(){return rooms;} public Hotel(String city, int numberOfStart) { this.city = city; this.numberOfStart = numberOfStart; } public void creatRooms(String roomNumber ,int numberOfbed,Double price) { Room room = new Room(roomNumber,numberOfbed,price); this.rooms.add(room); } @Override public String toString() { return &quot;Hotel{\n\t&quot; + &quot;city='&quot; + city + '\'' + &quot;, numberOfStart=&quot; + numberOfStart + &quot;, \n\trooms=&quot; + rooms + &quot;}\n\n&quot;; } } class Room { private final double price; private final int numberOfBed; private final String roomNumber; Room (String roomNumber,int numberOfBed, Double price){ this.price=price; this.roomNumber=roomNumber; this.numberOfBed=numberOfBed; } public double getPrice() {return price;} public int getNumberOfBed(){return numberOfBed;} @Override public String toString() { return &quot;\n\t\tRoom{&quot; + &quot;price=&quot; + price +'\'' + &quot;, numberOfBed=&quot; + numberOfBed + &quot;, roomNumber='&quot; + roomNumber + '}'; } } public class Main { /** * @param hotelList List search on a list of hotels. * @param city relates to the location of the hotel, if empty &quot;&quot;, then the predicate will be true, and ignore the city parameter. * @param start concerns the quality of the hotel, if set to 0 then the predicate will be true, and ignore the start parameter. * @param priceMax * @param nbBed concerns the amount beds, ignored if set to 0 * @return */ public static List&lt;Hotel&gt; searchHotelRoom(List&lt;Hotel&gt; hotelList, String city, int start, Double priceMax, int nbBed) { //condition about city location and price on hotel list Predicate&lt;Hotel&gt; byCity = !city.isEmpty()? hotel -&gt; hotel.getCity().equalsIgnoreCase(city) : hotel -&gt; true; Predicate&lt;Hotel&gt; byStart =!(start==0)? hotel -&gt; hotel.getNumberOfStart() == start:hotel -&gt; true; //condition on room list Predicate&lt;Room&gt; byNbBed =!(nbBed==0)? room -&gt; (room.getNumberOfBed()== nbBed) :room -&gt; false; Predicate&lt;Room&gt; byPrice = room -&gt; room.getPrice()&lt;=priceMax; return hotelList.stream() .filter(byStart) .filter(byCity) .filter(room -&gt; room.getRooms().stream().anyMatch(byPrice)) .filter(room -&gt; room.getRooms().stream().anyMatch(byNbBed)) .collect(Collectors.toList()); } public static void main(String[] args) { List&lt;Hotel&gt; hotelList = new ArrayList&lt;&gt;(); //Dummy hotel data Hotel hotelA = new Hotel(&quot;Paris&quot;,4); hotelA.creatRooms(&quot;p12&quot;, 2, 150.); hotelA.creatRooms(&quot;p17&quot;, 1, 200.); hotelA.creatRooms(&quot;p15&quot;, 3, 50.); hotelList.add(hotelA); Hotel hotelB = new Hotel(&quot;Montpellier&quot;,4); hotelB.creatRooms(&quot;b12&quot;, 2, 20.); hotelB.creatRooms(&quot;b17&quot;, 1, 200.); hotelB.creatRooms(&quot;b15&quot;, 1, 40.); hotelB.creatRooms(&quot;b15&quot;, 1, 1.); hotelList.add(hotelB); Hotel hotelC = new Hotel(&quot;Toulouse&quot;,4); hotelC.creatRooms(&quot;c12&quot;, 21, 200.); hotelC.creatRooms(&quot;c17&quot;, 11, 100.); hotelC.creatRooms(&quot;c15&quot;, 21, 50.); hotelC.creatRooms(&quot;c16&quot;, 30, 25.); hotelList.add(hotelC); //System.out.println(&quot;Hotels List\n&quot;); //hotelList.forEach(System.out::println); List&lt;Hotel&gt; result= searchHotelRoom(hotelList,&quot;&quot;,0,200.,2); System.out.println(&quot;Result of search&quot;); result.forEach(System.out::println); } } </code></pre> <p>The search function does not work as i would like there is some inconsistency for example for</p> <pre class="lang-java prettyprint-override"><code>List&lt;Hotel&gt; result= searchHotelRoom(hotelList,&quot;paris&quot;,0,200.,1); </code></pre> <p>i have this result</p> <pre><code>Result of search Hotel{ city='Paris', numberOfStart=4, rooms=[ Room{price=150.0', numberOfBed=2, roomNumber='p12}, Room{price=200.0', numberOfBed=1, roomNumber='p17}, Room{price=50.0', numberOfBed=3, roomNumber='p15}]} </code></pre> <p>but i want something like</p> <pre><code>Result of search Hotel{ city='Paris', numberOfStart=4, rooms=[ Room{price=200.0', numberOfBed=1, roomNumber='p17}} </code></pre> <p>and it seems that I have no <strong>and logic</strong> between the filters</p> <pre class="lang-java prettyprint-override"><code>List&lt;Hotel&gt; result= searchHotelRoom(hotelList,&quot;paris&quot;,0,200.,2); </code></pre> <p>must return nohing , but i have a result</p> <p>And on many hotel</p> <pre class="lang-java prettyprint-override"><code>List&lt;Hotel&gt; result= searchHotelRoom(hotelList,&quot;&quot;,0,200.,1); </code></pre> <p>I have</p> <pre><code>Result of search Hotel{ city='Paris', numberOfStart=4, rooms=[ Room{price=150.0', numberOfBed=2, roomNumber='p12}, Room{price=200.0', numberOfBed=1, roomNumber='p17}, Room{price=50.0', numberOfBed=3, roomNumber='p15}]} Hotel{ city='Montpellier', numberOfStart=4, rooms=[ Room{price=200.0', numberOfBed=1, roomNumber='b17}, </code></pre> <p>but i looking for something like</p> <pre><code>Result of search Hotel{ city='Paris', numberOfStart=4, rooms=[ Room{price=200.0', numberOfBed=1, roomNumber='p17} } Hotel{ city='Montpellier', numberOfStart=4, rooms=[ Room{price=200.0', numberOfBed=1, roomNumber='b17} } </code></pre> <p>in search method anyMatch return a boolean but i want list of room,<br /> so i have trie somme stuff on my searh methode like , but doesn't work</p> <pre class="lang-java prettyprint-override"><code> .filter(room -&gt; room.getRooms().stream().filter(byPrice)) </code></pre> <p>Does anyone have a clue to help me please?</p>
[ { "answer_id": 74583170, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": false, "text": "searchHotelRoom() List<Room> Hotel searchHotelRoom() Hotel Room String hotelName Hotel toString() hashCode() List Room Stream<Hotel> Stream<Room> flatMap() mapMulti() Stream filter() Precate.and() && public static List<Room> searchHotelRoom(List<Hotel> hotelList, String city, int start, Double priceMax, int nbBed) {\n \n //condition about city location and price on hotel list\n Predicate<Hotel> byCity = !city.isEmpty()? hotel -> hotel.getCity().equalsIgnoreCase(city) : hotel -> true;\n Predicate<Hotel> byStart = !(start == 0)? hotel -> hotel.getNumberOfStart() == start:hotel -> true;\n \n //condition on room list\n Predicate<Room> byNbBed = !(nbBed == 0)? room -> (room.getNumberOfBed() == nbBed) :room -> false;\n Predicate<Room> byPrice = room -> room.getPrice() <= priceMax;\n \n return hotelList.stream() // Stream<Hotel>\n .filter(byStart.and(byCity))\n .flatMap(hotel -> hotel.getRooms().stream()) // Stream<Room>\n .filter(byPrice.and(byNbBed))\n .toList(); // for Java 16 or collect(Collectors.toList())\n}\n" }, { "answer_id": 74583174, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 2, "selected": false, "text": "hotelsList.stream()\n .filter(hotelFilter)\n .flatMap(hotel -> hotel.rooms.stream()\n .filter(roomFilter))\n .collect(whatever)\n map A<B> B -> C A<C> A<B> B -> A<C> A<C> Optional None" }, { "answer_id": 74583281, "author": "Ben Anderson", "author_id": 14844306, "author_profile": "https://Stackoverflow.com/users/14844306", "pm_score": 1, "selected": false, "text": "Room List Room Room Hotel Main#searchHotelRoom Collectors.toMap Map<Hotel, List<Room>> Hotel List Room Hotel return hotelList.stream()\n .filter(byStart)\n .filter(byCity)\n .collect(\n Collectors.toMap(Functions.identity(),\n hotel -> hotel.getRooms()\n .stream()\n .filter(byPrice)\n .filter(byNbBed)\n .collect(Collectors.toList())\n )\n );\n" }, { "answer_id": 74587988, "author": "Krysdow", "author_id": 9599666, "author_profile": "https://Stackoverflow.com/users/9599666", "pm_score": 1, "selected": true, "text": "class Hotel {\n private String city;\n private int numberOfStart;\n private List<Room> rooms ;\n \n public Hotel(String city, int numberOfStart,List<Room> rooms) {\n \n rooms.forEach(s->s.setRefHotel(this))\n this.city = city;\n this.numberOfStart = numberOfStart;\n }\n}\n\n\nclass Room {\n private Hotel refHotel;\n\n public void setRefHotel(Hotel refHotel) {\n this.refHotel = refHotel;\n }\n\n public Hotel getRefHotel() {\n return refHotel;\n }\n\n}\n public static List<Room> searchHotelRoom(List<Room> rooms, String city, int start, Double priceMax, int nbBed) {\n//condition about city location and price on hotel list\n Predicate<Room> byCity = !city.isEmpty()? hotel -> hotel.getRefHotel().getCity().equalsIgnoreCase(city) : hotel -> true;\n Predicate<Room> byStart =!(start==0)? hotel -> hotel.getRefHotel().getNumberOfStart() == start:hotel -> true;\n\n //condition on room list\n Predicate<Room> byNbBed =!(nbBed==0)? room -> room.getNumberOfBed() == nbBed:room -> true;\n Predicate<Room> byPrice = room -> room.getPrice()<=priceMax;\n\n return rooms.stream()\n .filter(byStart.and(byCity))\n .filter(byPrice.and(byNbBed))\n .toList();\n }\n //Dummy hotel data\n List<Room> roomsA = new ArrayList<>();\n roomsA.add(new Room(\"p12\", 2, 150.));\n roomsA.add(new Room(\"p12\", 2, 150.));\n roomsA.add(new Room(\"p17\", 1, 200.));\n roomsA.add(new Room(\"p15\", 3, 50.));\n Hotel hotelA = new Hotel(\"Paris\",4,roomsA);\n\n List<Room> roomsB = new ArrayList<>();\n roomsB.add(new Room(\"m12\", 2, 150.));\n roomsB.add(new Room(\"m12\", 2, 150.));\n roomsB.add(new Room(\"m17\", 1, 200.));\n roomsB.add(new Room(\"m15\", 3, 50.));\n Hotel hotelB= new Hotel(\"Montpellier\",4,roomsB);\n\n List<Room> roomsC = new ArrayList<>();\n roomsC.add(new Room(\"c12\", 21, 200.));\n roomsC.add(new Room(\"c17\", 11, 100.));\n roomsC.add(new Room(\"c15\", 21, 50.));\n roomsC.add(new Room(\"c16\", 30, 25.));\n Hotel hotelC = new Hotel(\"Toulouse\",4,roomsC);\n\n List<Room> allRooms = new ArrayList<>();\n Stream.of(roomsA, roomsB,roomsC).forEach(allRooms::addAll);\n\n /*the result concerns\n * roomsB.add(new Room(\"m12\", 2, 150.));\n * roomsB.add(new Room(\"m12\", 2, 150.));\n * roomsB.add(new Room(\"m12\", 2, 150.));\n * roomsB.add(new Room(\"m12\", 2, 150.));\n *\n * * */\n System.out.println(\"Result of search\");\n List<Room> result = searchHotelRoom(allRooms,\"\",4,150.,2);\n result.forEach(System.out::println);\n\n Result of search\n\nRoom{\n price=150.0, numberOfBed=2, roomNumber='p12', \nrefHotel\n Hotel{city='Paris', numberOfStart=4}\n}\n...\n...\n...\nRoom{\n price=150.0, numberOfBed=2, roomNumber='m12', \nrefHotel\n Hotel{city='Montpellier', numberOfStart=4}\n}\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9599666/" ]
74,583,025
<p>The <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types" rel="nofollow noreferrer">documentation</a> for nullable reference types says:</p> <blockquote> <p>The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type. The compiler doesn't add any runtime checking for non-nullable reference types. The benefits are in the compile-time analysis. The compiler generates warnings that help you find and fix potential null errors in your code. You declare your intent, and the compiler warns you when your code violates that intent.</p> </blockquote> <p>What are the potential null errors? What intent do I declare using a nullable reference type? This is not clear to me.</p>
[ { "answer_id": 74583202, "author": "gsharp", "author_id": 150967, "author_profile": "https://Stackoverflow.com/users/150967", "pm_score": 2, "selected": true, "text": "string? myString1 = RemoveDots1(\"Hel.lo\");\nstring myString2 = RemoveDots1(\"Hel.lo\"); // warning: the function might return null, but you declared myString2 as non nullable.\n\n\nmyString1 = null;\nmyString2 = null; // warning: you should not do that, because you declared myString2 as non nullable.\n\nmyString1 = RemoveDots1(myString1);\nmyString1 = RemoveDots2(myString1); // warning: myString1 could be null, but its expecting a non nullable string\n\n\nstring? RemoveDots1(string? myString)\n{\n return myString.Replace(\".\", \"\"); // warning: myString could be null\n}\n\n\nstring RemoveDots2(string myString)\n{\n return myString.Replace(\".\", \"\");\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10807094/" ]
74,583,078
<p>fixed div through position:sticky and after scrolling navbar which is fixed overlaps div. How can this be fixed? Navbar from bootstrap</p> <p>I am new to frontend, so I used only padding, but it does not look nice, everything is not flat in relation to other blocks I am new to frontend, so I used only padding, but it does not look nice, everything is not flat in relation to other blocks</p>
[ { "answer_id": 74583202, "author": "gsharp", "author_id": 150967, "author_profile": "https://Stackoverflow.com/users/150967", "pm_score": 2, "selected": true, "text": "string? myString1 = RemoveDots1(\"Hel.lo\");\nstring myString2 = RemoveDots1(\"Hel.lo\"); // warning: the function might return null, but you declared myString2 as non nullable.\n\n\nmyString1 = null;\nmyString2 = null; // warning: you should not do that, because you declared myString2 as non nullable.\n\nmyString1 = RemoveDots1(myString1);\nmyString1 = RemoveDots2(myString1); // warning: myString1 could be null, but its expecting a non nullable string\n\n\nstring? RemoveDots1(string? myString)\n{\n return myString.Replace(\".\", \"\"); // warning: myString could be null\n}\n\n\nstring RemoveDots2(string myString)\n{\n return myString.Replace(\".\", \"\");\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19554644/" ]
74,583,084
<p>Why does the C code below output &quot;Difference: 0.000000&quot; ? I need to make calculations with many decimals in one of my university tasks and I don't understand this because I'm new to programming in C. Am I using the correct type? Thanks in advance.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; int main() { long double a = 1.00000001; long double b = 1.00000000; long double difference = a-b; printf(&quot;Difference: %Lf&quot;, difference); } </code></pre> <p>I have tried that code and I'm expecting to get the result: &quot;Difference: 0.00000001&quot;</p>
[ { "answer_id": 74583163, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "0.000000 %Lf 0.000000 %Le %Lg %.8Lf #include <stdio.h>\n\nint main(void)\n{\n long double a = 1.00000001;\n long double b = 1.00000000;\n long double difference = a - b;\n\n printf(\"Difference: %Lf\\n\", difference);\n printf(\"Difference: %.8Lf\\n\", difference);\n printf(\"Difference: %Le\\n\", difference);\n printf(\"Difference: %Lg\\n\", difference);\n return 0;\n}\n Difference: 0.000000\nDifference: 0.00000001\nDifference: 1.000000e-08\nDifference: 1e-08\n" }, { "answer_id": 74583231, "author": "Aradhya Singh", "author_id": 20605947, "author_profile": "https://Stackoverflow.com/users/20605947", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n long double a = 1.000000001;\n long double b = 1.000000000;\n long double difference = a-b;\n \n printf(\"Difference: %.9Lf\\n\", difference);\n\n}\n .9" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607214/" ]
74,583,130
<p>I have a command that adds all the current roles of a user to a Database (MongoDB).</p> <p>The code:</p> <pre><code>def add_roles_to_db(self): check = cursor.find_one({&quot;_id&quot;: self.ctx.author.id}) if check is None: cursor.insert_one({&quot;_id&quot;: self.ctx.author.id, &quot;roles&quot;: [str(r) for r in self.ctx.author.roles[1:]]}) else: cursor.update_one({&quot;_id&quot;: self.ctx.author.id}, {&quot;$set&quot;: {&quot;roles&quot;: [str(r) for r in self.ctx.author.roles[1:]]}}) </code></pre> <p>The code to get the roles:</p> <pre><code> def get_roles_from_db(self): return cursor.find_one({&quot;_id&quot;: self.ctx.author.id})[&quot;roles&quot;] </code></pre> <p>When I get the roles from the DB I get a list, everything I've tried led to an error. Error: &quot;AttributeError: 'str' object has no attribute 'id'&quot;</p> <pre><code>if len(roles) != 0: await author.add_roles(*roles) </code></pre> <p>I saw a other post where someone added roles via a list but that didn't work</p>
[ { "answer_id": 74583163, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "0.000000 %Lf 0.000000 %Le %Lg %.8Lf #include <stdio.h>\n\nint main(void)\n{\n long double a = 1.00000001;\n long double b = 1.00000000;\n long double difference = a - b;\n\n printf(\"Difference: %Lf\\n\", difference);\n printf(\"Difference: %.8Lf\\n\", difference);\n printf(\"Difference: %Le\\n\", difference);\n printf(\"Difference: %Lg\\n\", difference);\n return 0;\n}\n Difference: 0.000000\nDifference: 0.00000001\nDifference: 1.000000e-08\nDifference: 1e-08\n" }, { "answer_id": 74583231, "author": "Aradhya Singh", "author_id": 20605947, "author_profile": "https://Stackoverflow.com/users/20605947", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n long double a = 1.000000001;\n long double b = 1.000000000;\n long double difference = a-b;\n \n printf(\"Difference: %.9Lf\\n\", difference);\n\n}\n .9" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18380731/" ]
74,583,138
<p>Getting this null check error, despite having null safety through out the code. I'm attaching a git repo <a href="https://github.com/HidayatBukhari01/Notes-App.git" rel="nofollow noreferrer">https://github.com/HidayatBukhari01/Notes-App.git</a> can someone please check this code and explain why am i having this error<a href="https://i.stack.imgur.com/eag2v.png" rel="nofollow noreferrer">enter image description here</a></p> <p>On clicking + icon data should have been inserted into notes table, instead it's throwing null safety error!.</p>
[ { "answer_id": 74583163, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "0.000000 %Lf 0.000000 %Le %Lg %.8Lf #include <stdio.h>\n\nint main(void)\n{\n long double a = 1.00000001;\n long double b = 1.00000000;\n long double difference = a - b;\n\n printf(\"Difference: %Lf\\n\", difference);\n printf(\"Difference: %.8Lf\\n\", difference);\n printf(\"Difference: %Le\\n\", difference);\n printf(\"Difference: %Lg\\n\", difference);\n return 0;\n}\n Difference: 0.000000\nDifference: 0.00000001\nDifference: 1.000000e-08\nDifference: 1e-08\n" }, { "answer_id": 74583231, "author": "Aradhya Singh", "author_id": 20605947, "author_profile": "https://Stackoverflow.com/users/20605947", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n long double a = 1.000000001;\n long double b = 1.000000000;\n long double difference = a-b;\n \n printf(\"Difference: %.9Lf\\n\", difference);\n\n}\n .9" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607455/" ]
74,583,146
<p>I am plotting a barchart with two quantitative variables (in two separate columns), a and b, per categorical variables on the x axis. The first 9 categ variables are the months in which certain values had been reached, while the last one is the yearly average, I would like to fill the last two columns (those referring to the yearly average) with a different color than the previous ones, the following code colors all of the bars in the same way, how do I change only those referring to the year average? thank you!</p> <p>the two values I want to plot are the following:</p> <pre><code>a= c(10,11,12,13,14,15,16,17,18,14) # (the last one is the average) b= c(20,19,18,17,16,15,14,13,12,16) # (the last one is the average) </code></pre> <p>In scale_fill_manual I put the colors in the order I want them to appear on the graph (starting from the left column), but the output doesn't show the desired result for the last two bars, coloring them as the rest of the bars.</p> <p>Thanks a lot!</p> <pre><code>df &lt;- data.frame(Mon= c(&quot;February&quot;, &quot;February&quot;, &quot;March&quot;, &quot;March&quot;, &quot;April&quot;, &quot;April&quot;, &quot;May&quot;, &quot;May&quot;, &quot;June&quot;, &quot;June&quot;, &quot;July&quot;, &quot;July&quot;, &quot;August&quot;, &quot;August&quot;, &quot;September&quot;, &quot;September&quot;, &quot;October&quot;, &quot;October&quot;, &quot;Year Average to 01/11&quot;, &quot;Year Average to 01/11&quot;), Metrics=c('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'), Values=c(10, 20,11,19,12,18,13,17,14,16,15,15,16,14,17,13,18,12,14,16)) df$Mon &lt;- factor(df$Mon, levels = unique(df$Mon)) # I do this to avoid the re-ordering of the x variables in alphabetical order ggplot(df)+ geom_bar( aes(x=Mon, y=Values, fill=Metrics, group=Metrics), stat='identity', position='dodge' )+ scale_fill_manual(values=c(&quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#9BD4F5&quot;, &quot;#6CC4EE&quot;, &quot;#1D8ECE&quot;, &quot;#2E77BB&quot;) )+ geom_text( aes(x=Mon, y=Values, label=Values, fill=Metrics, group=Metrics), position = position_dodge(width = 1), vjust = 2, size = 3 )+ theme( plot.title = element_text(hjust = 0.5, size = 25), plot.subtitle = element_text(hjust = 0.5, color = &quot;darkgrey&quot;, size = 20), axis.title = element_text(size = 20), axis.text = element_text(size = 15), panel.background = element_rect(fill = &quot;white&quot;, color = &quot;white&quot;), panel.grid.major.y = element_line(color = &quot;grey&quot;), axis.line = element_line(color = &quot;black&quot;) )+ labs( x = &quot;&quot;, y = &quot;Values&quot;, title = &quot;OSAT and RTF Overview&quot;, subtitle = &quot;February to October 2022&quot; ) </code></pre>
[ { "answer_id": 74583163, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "0.000000 %Lf 0.000000 %Le %Lg %.8Lf #include <stdio.h>\n\nint main(void)\n{\n long double a = 1.00000001;\n long double b = 1.00000000;\n long double difference = a - b;\n\n printf(\"Difference: %Lf\\n\", difference);\n printf(\"Difference: %.8Lf\\n\", difference);\n printf(\"Difference: %Le\\n\", difference);\n printf(\"Difference: %Lg\\n\", difference);\n return 0;\n}\n Difference: 0.000000\nDifference: 0.00000001\nDifference: 1.000000e-08\nDifference: 1e-08\n" }, { "answer_id": 74583231, "author": "Aradhya Singh", "author_id": 20605947, "author_profile": "https://Stackoverflow.com/users/20605947", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n long double a = 1.000000001;\n long double b = 1.000000000;\n long double difference = a-b;\n \n printf(\"Difference: %.9Lf\\n\", difference);\n\n}\n .9" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607260/" ]
74,583,150
<p>models.py</p> <pre><code>class Courses(models.Model): course_name=models.CharField(max_length=50) course_price=models.IntegerField() class Exam(models.Model): exam_name=models.CharField(max_length=101) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python') exam_time=models.DateTimeField() </code></pre> <p>views.py</p> <pre><code>def Examadd(request): mycourses = Courses.objects.all() context = {'mycourses': mycourses} if request.method == 'POST': newexam = request.POST.get('examname') course = request.POST.get('courses') examtime = request.POST.get('time') new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime) new.save() messages.success(request, &quot;Course created successfully&quot;) return redirect('Courselist') return render(request,'addexam.html',context) </code></pre> <p>addexam.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Add New Exam&lt;/h1&gt; &lt;form method=&quot;post&quot;&gt; {% csrf_token %} &lt;label&gt;Examname:&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;examname&quot;&gt; &lt;label&gt;Course:&lt;/label&gt; &lt;select name=&quot;courses&quot;&gt; {% for i in mycourses %} &lt;option value={{i.id}}&gt;{{i.course_name}}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;label&gt;Exam time and date:&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;examtime&quot;&gt; &lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign &quot;'1'&quot;: &quot;Exam.course&quot; must be a &quot;Courses&quot; instance.</p>
[ { "answer_id": 74583167, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 1, "selected": false, "text": "course_id def Examadd(request):\n mycourses = Courses.objects.all()\n context = {'mycourses': mycourses}\n if request.method == 'POST':\n newexam = request.POST.get('examname')\n course = request.POST.get('courses')\n examtime = request.POST.get('time')\n new = Exam.objects.create(\n exam_name=newexam, course_id=course, exam_time=examtime\n )\n messages.success(request, \"Course created successfully\")\n return redirect('Courselist')\n return render(request, 'addexam.html', context) ModelForm time Course Courses course_name name" }, { "answer_id": 74585000, "author": "Sunderam Dubey", "author_id": 17562044, "author_profile": "https://Stackoverflow.com/users/17562044", "pm_score": 0, "selected": false, "text": "create() save() Exam def Examadd(request):\n mycourses = Courses.objects.all()\n context = {'mycourses': mycourses}\n if request.method == 'POST':\n newexam = request.POST.get('examname')\n course = request.POST.get('courses')\n examtime = request.POST.get('time')\n new = Exam.objects.create(exam_name=newexam,course__id=course,exam_time=examtime)\n messages.success(request, \"Course created successfully\")\n return redirect('Courselist')\n return render(request,'addexam.html',context)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607296/" ]
74,583,162
<p>Code I try to copy: <a href="https://codesandbox.io/s/knhlr?file=/src/index.tsx:0-691" rel="nofollow noreferrer">https://codesandbox.io/s/knhlr?file=/src/index.tsx:0-691</a></p> <p>Dependencies: &quot;@next/font&quot;: &quot;^13.0.5&quot;, &quot;eslint-config-next&quot;: &quot;13.0.4&quot;, &quot;next&quot;: &quot;13.0.4&quot;, &quot;react&quot;: &quot;18.2.0&quot;, &quot;react-dom&quot;: &quot;18.2.0&quot;, &quot;sharp&quot;: &quot;^0.31.2&quot;, &quot;three&quot;: &quot;0.109.0&quot;, &quot;react-globe&quot;: &quot;5.0.2&quot;, &quot;es6-tween&quot;: &quot;5.5.10&quot;</p> <p>My Next.js (React) code renders a white page and writes in the console: &quot;window is not defined&quot;</p> <pre><code>&quot;use client&quot;; import ReactGlobe from &quot;react-globe&quot;; import markers from &quot;./markers&quot;; import markerRenderer from &quot;./markerRenderer&quot;; const options = { markerRenderer, }; export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;ReactGlobe height=&quot;100vh&quot; globeTexture=&quot;https://raw.githubusercontent.com/chrisrzhou/react-globe/main/textures/globe_dark.jpg&quot; markers={markers} width=&quot;100vw&quot; options={options} /&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74583341, "author": "Farbod Shabani", "author_id": 14712252, "author_profile": "https://Stackoverflow.com/users/14712252", "pm_score": -1, "selected": false, "text": "useEffect" }, { "answer_id": 74593389, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "\"use client\";\n\nimport ReactGlobe from \"react-globe\";\n\nimport markers from \"./markers\";\nimport markerRenderer from \"./markerRenderer\";\n\nconst options = {\n markerRenderer,\n};\n\nexport default function App() {\n return (\n <div className=\"App\">\n {\n typeof window !== undefined ?\n <ReactGlobe\n height=\"100vh\"\n globeTexture=\"https://raw.githubusercontent.com/chrisrzhou/react-globe/main/textures/globe_dark.jpg\"\n markers={markers}\n width=\"100vw\"\n options={options}\n />\n :\n null\n }\n </div>\n );\n}\n import dynamic from 'next/dynamic';\n const ReactGlobe = dynamic(import('react-globe'), { ssr: false });\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18717939/" ]
74,583,176
<p>When i introduce the &quot;try&quot; &quot;catch&quot; statements and read the user input for the &quot;choice&quot; variable, the code executes as it should it does not however continue on to the &quot;switch&quot; &quot;case&quot; statement as the &quot;choice&quot; variable is then said to be an unassigned local variable. Please help.</p> <p>I was expecting the rest of the &quot;switch case&quot; code to execute.</p> <pre class="lang-cs prettyprint-override"><code>int choice; do { Console.Clear(); Console.WriteLine(&quot;1. Load Data&quot;); Console.WriteLine(&quot;2. Add Customer&quot;); Console.WriteLine(&quot;3. Sort Customers&quot;); Console.WriteLine(&quot;4. Display Customers&quot;); Console.WriteLine(&quot;5. Edit Customer&quot;); Console.WriteLine(&quot;6. Exit\n&quot;); Console.WriteLine(&quot;Chose an option 1-6: &quot;); bool valid = true; do { try { choice = Convert.ToInt32(Console.ReadLine()); } catch (Exception) { valid = false; Console.WriteLine(&quot;please enter a number from 1 - 6&quot;); } } while (valid == false); switch (choice) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; default: break; } Console.Clear(); } while (choice != 6); </code></pre>
[ { "answer_id": 74583220, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "catch choice try catch int choice; // Choice is declared here but is not assigned a value.\n\n...\n\ntry\n{\n // When the conversion fails, no assignment to `choice` is made.\n choice = Convert.ToInt32(Console.ReadLine());\n valid = true; // This was also missing.\n}\ncatch (Exception)\n{\n valid = false;\n choice = 0; // <========================================\n Console.WriteLine(\"please enter a number from 1 - 6\");\n}\n\n...\n\n// Now, here `choice` is known to have a value assigned in any case.\n valid choice choice TryParse int choice;\ndo {\n // Console output ...\n while (!Int32.TryParse(Console.ReadLine(), out choice)) {\n Console.Write(\"please enter a number from 1 - 6: \");\n }\n Console.WriteLine();\n switch (choice) {\n ...\n default:\n break;\n }\n Console.Clear();\n} while (choice != 6);\n" }, { "answer_id": 74583406, "author": "noreon", "author_id": 20607495, "author_profile": "https://Stackoverflow.com/users/20607495", "pm_score": 0, "selected": false, "text": " bool valid = true;\n do\n {\n try\n {\n choice = Convert.ToInt32(Console.ReadLine());\n break;\n \n }\n catch (Exception)\n {\n Console.Clear();\n valid = false;\n choice = 0;\n Console.WriteLine(\"please enter a number from 1 - 6\");\n \n\n }\n \n } while (valid == false);\n" }, { "answer_id": 74583506, "author": "Michele Bandini", "author_id": 20602385, "author_profile": "https://Stackoverflow.com/users/20602385", "pm_score": 0, "selected": false, "text": "choice int choice = 0;\n valid true bool valid;\n do\n {\n valid = true;\n try\n {\n choice = Convert.ToInt32(Console.ReadLine());\n }\n catch (Exception)\n {\n valid = false;\n Console.WriteLine(\"please enter a number from 1 - 6\");\n }\n } while (valid == false);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607495/" ]
74,583,181
<p>Hello I have filled a ListView from list on my State Bloc(CustomerGetAllLoadedState) and work fine but now I need to search item from a TextField, I did so:</p> <p>I declare list:</p> <pre><code>List&lt;Customer&gt; _customersFromRepo = []; </code></pre> <p>this is ListView where intercept to List Global:</p> <pre><code> BlocBuilder&lt;CustomerBloc, CustomerState&gt;( builder: (context, state) { if (State is CustomerLoadingState) { return Center( child: CircularProgressIndicator(), ); } if (state is CustomerGetAllLoadedState) { _customersFromRepo = state.customers; // &lt;----------- List for searh method return SizedBox( height: h * 0.5, width: w * 0.5, child: _customersFromRepo.isNotEmpty ? ListView.builder( itemCount: _customersFromRepo.length, itemBuilder: (context, index) =&gt; Card( </code></pre> <p>key: ValueKey( _customersFromRepo[index].id),</p> <p>this is TextField for search items:</p> <pre><code>CustomTextFormField( txtLable: &quot;Nome Cliente&quot;, onChanged: (value) =&gt; _runFilter(value) </code></pre> <p>this is method fo filter:</p> <pre><code> void _runFilter(String enteredKeyword) { List&lt;Customer&gt; results = []; if (enteredKeyword.isEmpty) { // if the search field is empty or only contains white-space, we'll display all users results = _customersFromRepo; } else { results = _customersFromRepo .where( (customer) =&gt; customer.name.toString().toLowerCase().contains(enteredKeyword.toLowerCase())) .toList(); } setState(() { _customersFromRepo = results; }); </code></pre> <p><strong>But the list doesn't change even if _customersFromRepo has only one item, it always keeps the old state. Can I do?</strong></p> <p><a href="https://i.stack.imgur.com/6kENa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6kENa.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74583220, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "catch choice try catch int choice; // Choice is declared here but is not assigned a value.\n\n...\n\ntry\n{\n // When the conversion fails, no assignment to `choice` is made.\n choice = Convert.ToInt32(Console.ReadLine());\n valid = true; // This was also missing.\n}\ncatch (Exception)\n{\n valid = false;\n choice = 0; // <========================================\n Console.WriteLine(\"please enter a number from 1 - 6\");\n}\n\n...\n\n// Now, here `choice` is known to have a value assigned in any case.\n valid choice choice TryParse int choice;\ndo {\n // Console output ...\n while (!Int32.TryParse(Console.ReadLine(), out choice)) {\n Console.Write(\"please enter a number from 1 - 6: \");\n }\n Console.WriteLine();\n switch (choice) {\n ...\n default:\n break;\n }\n Console.Clear();\n} while (choice != 6);\n" }, { "answer_id": 74583406, "author": "noreon", "author_id": 20607495, "author_profile": "https://Stackoverflow.com/users/20607495", "pm_score": 0, "selected": false, "text": " bool valid = true;\n do\n {\n try\n {\n choice = Convert.ToInt32(Console.ReadLine());\n break;\n \n }\n catch (Exception)\n {\n Console.Clear();\n valid = false;\n choice = 0;\n Console.WriteLine(\"please enter a number from 1 - 6\");\n \n\n }\n \n } while (valid == false);\n" }, { "answer_id": 74583506, "author": "Michele Bandini", "author_id": 20602385, "author_profile": "https://Stackoverflow.com/users/20602385", "pm_score": 0, "selected": false, "text": "choice int choice = 0;\n valid true bool valid;\n do\n {\n valid = true;\n try\n {\n choice = Convert.ToInt32(Console.ReadLine());\n }\n catch (Exception)\n {\n valid = false;\n Console.WriteLine(\"please enter a number from 1 - 6\");\n }\n } while (valid == false);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3021708/" ]
74,583,196
<p>I have the following data</p> <pre class="lang-r prettyprint-override"><code>sim_model = &quot; x =~ 1.3*x1 + 1.2*x2 + 1.1*x3 + 1.2*x4 y =~ 1*y1 + 1.2*y2 + 1.3*y3 + 0.9*y4 y ~ 0.6*x &quot; sim_data = lavaan::simulateData(sim_model) model = &quot; x =~ x1 + x2 + x3 + x4 y =~ y1 + y2 + y3 + y4 y ~ x &quot; sd_d = data.frame(sd_d = apply(sim_data, 2, sd)) </code></pre> <p>I need to multiply each column of the <code>sim_data</code> with its corresponding standard deviation which is in <code>sd_d</code>.</p> <p>Any help?</p>
[ { "answer_id": 74583285, "author": "Kensho", "author_id": 19577706, "author_profile": "https://Stackoverflow.com/users/19577706", "pm_score": 1, "selected": false, "text": "\nsim_data |>\n mutate(SDxX1 = sd(x1)*x1,\n SDxX2 = sd(x2)*x2,\n SDxX3 = sd(x3)*x3,\n SDxX4 = sd(x4)*x4,\n SDxY1 = sd(y1)*y1,\n SDxY2 = sd(y2)*y2,\n SDxY3 = sd(y3)*y3,\n SDxY4 = sd(y4)*y4\n)\n\n" }, { "answer_id": 74583298, "author": "DaveArmstrong", "author_id": 8206434, "author_profile": "https://Stackoverflow.com/users/8206434", "pm_score": 1, "selected": false, "text": "library(dplyr)\nsim_model = \"\nx =~ 1.3*x1 + 1.2*x2 + 1.1*x3 + 1.2*x4\ny =~ 1*y1 + 1.2*y2 + 1.3*y3 + 0.9*y4\ny ~ 0.6*x\n\"\nsim_data = lavaan::simulateData(sim_model)\nmodel = \"\nx =~ x1 + x2 + x3 + x4\ny =~ y1 + y2 + y3 + y4\ny ~ x\n\"\nsd_d = data.frame(sd_d = apply(sim_data, 2, sd))\n\nnew_sim_data <- sapply(1:ncol(sim_data), function(i)\n sim_data[[i]]*sd_d$sd_d[i])\nhead(new_sim_data)\n#> [,1] [,2] [,3] [,4] [,5] [,6]\n#> [1,] 3.9817268 4.4529682 1.7882380 2.621278 -0.3147092 0.7048940\n#> [2,] -0.8972617 -0.4562149 -0.1165654 1.318948 0.4359371 0.4220787\n#> [3,] 1.9188604 0.9183960 5.3265835 4.025215 1.6147254 1.8146241\n#> [4,] -4.2811180 -0.4473838 -1.4982330 -1.325111 -2.5972828 -0.7700888\n#> [5,] -2.8633480 2.4930664 1.9927546 -1.186898 3.8177569 4.4855348\n#> [6,] 1.0197316 0.7887374 2.2055450 2.039363 2.8806220 9.2947559\n#> [,7] [,8]\n#> [1,] 2.2355215 -1.3586282\n#> [2,] -1.0632624 -0.6658058\n#> [3,] 0.1758628 0.1879555\n#> [4,] -3.0958775 2.8376086\n#> [5,] 4.5647521 3.5110156\n#> [6,] 7.0123519 1.3295521\n" }, { "answer_id": 74584159, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "tidyverse sd_d library(tidyverse)\n\n#easiest solution\nsim_data |>\n mutate(across(x1:y4, list(sd = \\(x) sd(x)*x)))\n#> # A tibble: 500 x 16\n#> x1 x2 x3 x4 y1 y2 y3 y4 x1_sd x2_sd x3_sd\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 -0.926 0.468 0.476 -0.252 -2.53 -0.374 0.690 0.354 -1.47 0.728 0.697\n#> 2 -0.813 -0.782 -0.820 0.300 0.978 1.48 -0.566 1.45 -1.29 -1.22 -1.20 \n#> 3 -3.28 -2.18 -2.48 -1.12 -0.235 -0.562 0.919 1.78 -5.20 -3.39 -3.63 \n#> 4 1.18 2.49 2.52 2.46 2.97 3.31 0.881 -1.10 1.87 3.87 3.69 \n#> 5 1.33 0.328 1.83 -2.04 0.204 1.40 1.94 1.77 2.10 0.511 2.68 \n#> 6 -0.388 -3.12 -1.03 0.137 -0.333 -0.167 0.482 -0.417 -0.615 -4.85 -1.50 \n#> 7 -1.12 -1.83 0.143 -1.75 0.169 -1.51 -2.40 -0.793 -1.77 -2.84 0.209\n#> 8 -3.04 -0.899 -2.77 -0.586 -1.98 -1.13 -2.97 -1.64 -4.81 -1.40 -4.06 \n#> 9 -0.856 1.46 1.37 -0.617 1.45 -0.149 -0.169 0.842 -1.36 2.26 2.00 \n#> 10 0.492 0.506 0.616 -1.23 -0.841 0.132 -0.528 -1.51 0.779 0.786 0.902\n#> # ... with 490 more rows, and 5 more variables: x4_sd <dbl>, y1_sd <dbl>,\n#> # y2_sd <dbl>, y3_sd <dbl>, y4_sd <dbl>\n\n\n#less easy solution\nmap_dfc(colnames(sim_data), \\(col){\n tibble(!!sym(col) := pull(sim_data, {{col}}),\n !!sym(paste0(col, \"_sd\")) := pull(sim_data, {{col}}) * sd_d[rownames(sd_d) == col,])\n}) |>\n select(colnames(sim_data), contains(\"_sd\"))\n#> # A tibble: 500 x 16\n#> x1 x2 x3 x4 y1 y2 y3 y4 x1_sd x2_sd x3_sd\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 -0.926 0.468 0.476 -0.252 -2.53 -0.374 0.690 0.354 -1.47 0.728 0.697\n#> 2 -0.813 -0.782 -0.820 0.300 0.978 1.48 -0.566 1.45 -1.29 -1.22 -1.20 \n#> 3 -3.28 -2.18 -2.48 -1.12 -0.235 -0.562 0.919 1.78 -5.20 -3.39 -3.63 \n#> 4 1.18 2.49 2.52 2.46 2.97 3.31 0.881 -1.10 1.87 3.87 3.69 \n#> 5 1.33 0.328 1.83 -2.04 0.204 1.40 1.94 1.77 2.10 0.511 2.68 \n#> 6 -0.388 -3.12 -1.03 0.137 -0.333 -0.167 0.482 -0.417 -0.615 -4.85 -1.50 \n#> 7 -1.12 -1.83 0.143 -1.75 0.169 -1.51 -2.40 -0.793 -1.77 -2.84 0.209\n#> 8 -3.04 -0.899 -2.77 -0.586 -1.98 -1.13 -2.97 -1.64 -4.81 -1.40 -4.06 \n#> 9 -0.856 1.46 1.37 -0.617 1.45 -0.149 -0.169 0.842 -1.36 2.26 2.00 \n#> 10 0.492 0.506 0.616 -1.23 -0.841 0.132 -0.528 -1.51 0.779 0.786 0.902\n#> # ... with 490 more rows, and 5 more variables: x4_sd <dbl>, y1_sd <dbl>,\n#> # y2_sd <dbl>, y3_sd <dbl>, y4_sd <dbl>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890129/" ]
74,583,201
<p>I'd like to put images with centered text underneath each image in columns, I'd also like to size the images to a specific width and height each and I also want to make it so that when the text gets too long the text gets split into 2 lines, but I dont want it to move the image up and down at the same time. What code should I use? I used some code I found on the internet which is linked below but that didn't work as I expected it to (the code can be found below). Thanks!</p> <p>So far, I've used this code but it doesn't center the text and also skips spots which I don't want to happen. Please check the image I've attached to see the skipped spots<a href="https://i.stack.imgur.com/A5QqQ.png" rel="nofollow noreferrer">skipped spot</a></p> <pre><code>HTML &lt;div class=&quot;column&quot;&gt; &lt;img src=&quot;extra/road96.jpg&quot; alt=&quot;Road 96&quot;style=&quot;width:180px;height:180px;&quot;/\&gt; &lt;a class='neon-button' href='https://www.mediafire.com/file/4a05b4tkaal5e50/Road_96.zip/file'\&gt;Road 96 &lt;a/&gt; &lt;div/&gt; </code></pre> <pre><code>CSS .column { float: left; width: 13.33%; padding: 5px; } .row::after { content: &quot;&quot;; clear: both; } .sjamg { text-align: justify; width: [width of img]; } .sjamg img { display: block; margin: 0 auto; } </code></pre>
[ { "answer_id": 74583285, "author": "Kensho", "author_id": 19577706, "author_profile": "https://Stackoverflow.com/users/19577706", "pm_score": 1, "selected": false, "text": "\nsim_data |>\n mutate(SDxX1 = sd(x1)*x1,\n SDxX2 = sd(x2)*x2,\n SDxX3 = sd(x3)*x3,\n SDxX4 = sd(x4)*x4,\n SDxY1 = sd(y1)*y1,\n SDxY2 = sd(y2)*y2,\n SDxY3 = sd(y3)*y3,\n SDxY4 = sd(y4)*y4\n)\n\n" }, { "answer_id": 74583298, "author": "DaveArmstrong", "author_id": 8206434, "author_profile": "https://Stackoverflow.com/users/8206434", "pm_score": 1, "selected": false, "text": "library(dplyr)\nsim_model = \"\nx =~ 1.3*x1 + 1.2*x2 + 1.1*x3 + 1.2*x4\ny =~ 1*y1 + 1.2*y2 + 1.3*y3 + 0.9*y4\ny ~ 0.6*x\n\"\nsim_data = lavaan::simulateData(sim_model)\nmodel = \"\nx =~ x1 + x2 + x3 + x4\ny =~ y1 + y2 + y3 + y4\ny ~ x\n\"\nsd_d = data.frame(sd_d = apply(sim_data, 2, sd))\n\nnew_sim_data <- sapply(1:ncol(sim_data), function(i)\n sim_data[[i]]*sd_d$sd_d[i])\nhead(new_sim_data)\n#> [,1] [,2] [,3] [,4] [,5] [,6]\n#> [1,] 3.9817268 4.4529682 1.7882380 2.621278 -0.3147092 0.7048940\n#> [2,] -0.8972617 -0.4562149 -0.1165654 1.318948 0.4359371 0.4220787\n#> [3,] 1.9188604 0.9183960 5.3265835 4.025215 1.6147254 1.8146241\n#> [4,] -4.2811180 -0.4473838 -1.4982330 -1.325111 -2.5972828 -0.7700888\n#> [5,] -2.8633480 2.4930664 1.9927546 -1.186898 3.8177569 4.4855348\n#> [6,] 1.0197316 0.7887374 2.2055450 2.039363 2.8806220 9.2947559\n#> [,7] [,8]\n#> [1,] 2.2355215 -1.3586282\n#> [2,] -1.0632624 -0.6658058\n#> [3,] 0.1758628 0.1879555\n#> [4,] -3.0958775 2.8376086\n#> [5,] 4.5647521 3.5110156\n#> [6,] 7.0123519 1.3295521\n" }, { "answer_id": 74584159, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "tidyverse sd_d library(tidyverse)\n\n#easiest solution\nsim_data |>\n mutate(across(x1:y4, list(sd = \\(x) sd(x)*x)))\n#> # A tibble: 500 x 16\n#> x1 x2 x3 x4 y1 y2 y3 y4 x1_sd x2_sd x3_sd\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 -0.926 0.468 0.476 -0.252 -2.53 -0.374 0.690 0.354 -1.47 0.728 0.697\n#> 2 -0.813 -0.782 -0.820 0.300 0.978 1.48 -0.566 1.45 -1.29 -1.22 -1.20 \n#> 3 -3.28 -2.18 -2.48 -1.12 -0.235 -0.562 0.919 1.78 -5.20 -3.39 -3.63 \n#> 4 1.18 2.49 2.52 2.46 2.97 3.31 0.881 -1.10 1.87 3.87 3.69 \n#> 5 1.33 0.328 1.83 -2.04 0.204 1.40 1.94 1.77 2.10 0.511 2.68 \n#> 6 -0.388 -3.12 -1.03 0.137 -0.333 -0.167 0.482 -0.417 -0.615 -4.85 -1.50 \n#> 7 -1.12 -1.83 0.143 -1.75 0.169 -1.51 -2.40 -0.793 -1.77 -2.84 0.209\n#> 8 -3.04 -0.899 -2.77 -0.586 -1.98 -1.13 -2.97 -1.64 -4.81 -1.40 -4.06 \n#> 9 -0.856 1.46 1.37 -0.617 1.45 -0.149 -0.169 0.842 -1.36 2.26 2.00 \n#> 10 0.492 0.506 0.616 -1.23 -0.841 0.132 -0.528 -1.51 0.779 0.786 0.902\n#> # ... with 490 more rows, and 5 more variables: x4_sd <dbl>, y1_sd <dbl>,\n#> # y2_sd <dbl>, y3_sd <dbl>, y4_sd <dbl>\n\n\n#less easy solution\nmap_dfc(colnames(sim_data), \\(col){\n tibble(!!sym(col) := pull(sim_data, {{col}}),\n !!sym(paste0(col, \"_sd\")) := pull(sim_data, {{col}}) * sd_d[rownames(sd_d) == col,])\n}) |>\n select(colnames(sim_data), contains(\"_sd\"))\n#> # A tibble: 500 x 16\n#> x1 x2 x3 x4 y1 y2 y3 y4 x1_sd x2_sd x3_sd\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 -0.926 0.468 0.476 -0.252 -2.53 -0.374 0.690 0.354 -1.47 0.728 0.697\n#> 2 -0.813 -0.782 -0.820 0.300 0.978 1.48 -0.566 1.45 -1.29 -1.22 -1.20 \n#> 3 -3.28 -2.18 -2.48 -1.12 -0.235 -0.562 0.919 1.78 -5.20 -3.39 -3.63 \n#> 4 1.18 2.49 2.52 2.46 2.97 3.31 0.881 -1.10 1.87 3.87 3.69 \n#> 5 1.33 0.328 1.83 -2.04 0.204 1.40 1.94 1.77 2.10 0.511 2.68 \n#> 6 -0.388 -3.12 -1.03 0.137 -0.333 -0.167 0.482 -0.417 -0.615 -4.85 -1.50 \n#> 7 -1.12 -1.83 0.143 -1.75 0.169 -1.51 -2.40 -0.793 -1.77 -2.84 0.209\n#> 8 -3.04 -0.899 -2.77 -0.586 -1.98 -1.13 -2.97 -1.64 -4.81 -1.40 -4.06 \n#> 9 -0.856 1.46 1.37 -0.617 1.45 -0.149 -0.169 0.842 -1.36 2.26 2.00 \n#> 10 0.492 0.506 0.616 -1.23 -0.841 0.132 -0.528 -1.51 0.779 0.786 0.902\n#> # ... with 490 more rows, and 5 more variables: x4_sd <dbl>, y1_sd <dbl>,\n#> # y2_sd <dbl>, y3_sd <dbl>, y4_sd <dbl>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893803/" ]
74,583,211
<pre><code>import { useEffect } from &quot;react&quot;; import jwtDecode from &quot;jwt-decode&quot;; import { useDispatch } from &quot;react-redux&quot;; import { login } from &quot;../redux/user&quot;; import { setCurrentPath } from &quot;../redux/currentpath&quot;; const Login = () =&gt; { const dispatch = useDispatch(); const google = window.google; function handleCallbackResponse(response) { var user = jwtDecode(response.credential); dispatch(login({ name: user.name, avatar: user.picture })); }; useEffect(() =&gt; { dispatch(setCurrentPath(window.location.pathname)); }, []); useEffect(() =&gt; { /* global google */ google.accounts.id.initialize({ client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com', callback: handleCallbackResponse }); google.accounts.id.renderButton( document.getElementById('signInDiv'), { theme: 'outline', size: 'large' } ); }, []); return ( &lt;div className=&quot;content login&quot;&gt; &lt;div className='greeting-text'&gt; &lt;h1&gt;Welcome to &lt;br className=&quot;br&quot; /&gt; Cat Room!&lt;/h1&gt; &lt;p&gt;Here you can talk about some very interesting topics, like milk, yarn balls, mice and many more. So don't be shy, come and join us! You can log in with Google right below this pharagraph.&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;signInDiv&quot;&gt; &lt;/div&gt; &lt;/div&gt; ); }; export default Login; </code></pre> <p>When I try to load it for first time it throws this error: <code>Uncaught TypeError: google is undefined</code></p> <p>and points to this line: <code>google.accounts.id.initialize({</code></p> <p>If I reload the page it works again. But if I clear browser history and load this page again it throws the same error. Then if I reload it suddenly works...</p> <p>I tried adding google as a dependency to the UseEffect hook where the error uccors. Then the same thing happened but this time it threw an error that said: n is undefined.</p> <p>I have no idea what could be the problem and I would greatly appreciate if somebody could help because I need it for my portfolio and it's quite important to work flawlessly. Thanks in advance!</p> <p>UPDATE:</p> <p>My mistake! n is undefined only occurs if I load the page in github pages. For which I had to change the basename from &quot;/cat-room&quot; to &quot;/cat-room/&quot;. Literally this is the only difference between the local and the github pages version. Not sure if it's important but I felt like I should note it.</p> <p>Either way on both versions the same thing happens. For first load throws error. Then I reload and works flawlessly.</p>
[ { "answer_id": 74583624, "author": "Hassan Baig", "author_id": 11325852, "author_profile": "https://Stackoverflow.com/users/11325852", "pm_score": 1, "selected": false, "text": "useEffect(() => {\n if(window.google){\n /* global google */\n window.google.accounts.id.initialize({\n client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com',\n callback: handleCallbackResponse\n });\n \n window.google.accounts.id.renderButton(\n document.getElementById('signInDiv'),\n { theme: 'outline', size: 'large' }\n );\n }\n }, [window.google]);\n" }, { "answer_id": 74583804, "author": "jr-kick", "author_id": 20306342, "author_profile": "https://Stackoverflow.com/users/20306342", "pm_score": 0, "selected": false, "text": "import { useEffect } from \"react\";\nimport jwtDecode from \"jwt-decode\";\nimport { useDispatch } from \"react-redux\";\nimport { login } from \"../redux/user\";\nimport { setCurrentPath } from \"../redux/currentpath\";\nimport { GoogleLogin } from '@react-oauth/google';\n\nconst Login = () => {\n const dispatch = useDispatch();\n\n useEffect(() => {\n dispatch(setCurrentPath(window.location.pathname));\n }, []);\n \n /* const google = window.google;\n\n function handleCallbackResponse(response) {\n var user = jwtDecode(response.credential);\n dispatch(login({ name: user.name, avatar: user.picture }));\n };\n\n useEffect(() => { */\n /* global google */\n /* google.accounts.id.initialize({\n client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com',\n callback: handleCallbackResponse\n });\n\n google.accounts.id.renderButton(\n document.getElementById('signInDiv'),\n { theme: 'outline', size: 'large' }\n );\n }, []); */\n \n return (\n <div className=\"content login\">\n <div className='greeting-text'>\n <h1>Welcome to <br className=\"br\" /> Cat Room!</h1>\n <p>Here you can talk about some very interesting topics, like milk, yarn balls, mice and many more. So don't be shy, come and join us! You can log in with Google right below this pharagraph.</p>\n </div>\n <div id=\"signInDiv\">\n <GoogleLogin\n onSuccess={credentialResponse => {\n console.log(credentialResponse.credential);\n var user = jwtDecode(credentialResponse.credential);\n dispatch(login({ name: user.name, avatar: user.picture }));\n }}\n onError={() => {\n console.log('Login Failed');\n }}\n />\n </div>\n {/* <div id=\"signInDiv\">\n </div> */}\n </div>\n );\n};\n \nexport default Login;\n import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\nimport reportWebVitals from './reportWebVitals';\nimport store from './redux/store';\nimport { Provider } from 'react-redux';\nimport { GoogleOAuthProvider } from '@react-oauth/google';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n <React.StrictMode>\n <Provider store={store}>\n <GoogleOAuthProvider clientId=\"650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com\"><App /></GoogleOAuthProvider>\n </Provider>\n </React.StrictMode>\n);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20306342/" ]
74,583,212
<p>I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again.</p> <pre><code>coordinates = [ (9, 2, 17), (4, 14, 11), (8, 10, 6), (2, 7, 0) ] cdns = coordinates[0][0:2], coordinates[1][0:2], coordinates[2][0:2], coordinates[3][0:2] newCnds = tuple(cdns) newCnds </code></pre>
[ { "answer_id": 74583229, "author": "SollyBunny", "author_id": 7483019, "author_profile": "https://Stackoverflow.com/users/7483019", "pm_score": 1, "selected": true, "text": "coordinates = [\n (9, 2, 17),\n (4, 14, 11),\n (8, 10, 6),\n (2, 7, 0)\n]\nnewCnds = [i[:2] for i in coordinates]\n" }, { "answer_id": 74583252, "author": "Grzegorz Skibinski", "author_id": 11610186, "author_profile": "https://Stackoverflow.com/users/11610186", "pm_score": 1, "selected": false, "text": "numpy >>> import numpy as np\n>>> coordinates = [\n... (9, 2, 17),\n... (4, 14, 11),\n... (8, 10, 6),\n... (2, 7, 0)\n... ]\n>>> coordinates_np = np.array(coordinates)\n>>> coordinates_np[:, 0:2]\narray([[ 9, 2],\n [ 4, 14],\n [ 8, 10],\n [ 2, 7]])\n numpy" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607509/" ]
74,583,244
<p>I have a dataframe that looks like this:</p> <pre><code> info_version commits commitdates 18558 17.1.3 42 2017-07-14 20783 17.1.3 57 2017-07-14 20782 17.2.2 57 2017-09-27 18557 17.2.2 42 2017-09-27 18556 17.2.3 42 2017-10-30 20781 17.2.3 57 2017-10-30 20780 17.2.4 57 2017-11-27 18555 17.2.4 42 2017-11-27 20779 17.2.5 57 2018-01-10 </code></pre> <p>I have a trivial issue, but somehow I am not able to find the function,I want to count the commits starting from value 42 till the last one, my desired output is something like this:</p> <pre><code> info_version commits commitdates Commit_growth 18558 17.1.3 42 2017-07-14 42 20783 17.1.3 57 2017-07-14 109 20782 17.2.2 57 2017-09-27 166 18557 17.2.2 42 2017-09-27. 208 18556 17.2.3 42 2017-10-30 250 20781 17.2.3 57 2017-10-30 307 20780 17.2.4 57 2017-11-27 364 18555 17.2.4 42 2017-11-27. 406 20779 17.2.5 57 2018-01-10 463 </code></pre> <p>This is what I tried so far:</p> <pre><code>data2 = data1[['info_version', 'commits', 'commitdates']].sort_values(by='info_version', ascending=True) sum_row = data2.sum(axis=0) </code></pre> <p>But this gives me the entire count. This seems to be easy, but I am a bit stuck.</p>
[ { "answer_id": 74583229, "author": "SollyBunny", "author_id": 7483019, "author_profile": "https://Stackoverflow.com/users/7483019", "pm_score": 1, "selected": true, "text": "coordinates = [\n (9, 2, 17),\n (4, 14, 11),\n (8, 10, 6),\n (2, 7, 0)\n]\nnewCnds = [i[:2] for i in coordinates]\n" }, { "answer_id": 74583252, "author": "Grzegorz Skibinski", "author_id": 11610186, "author_profile": "https://Stackoverflow.com/users/11610186", "pm_score": 1, "selected": false, "text": "numpy >>> import numpy as np\n>>> coordinates = [\n... (9, 2, 17),\n... (4, 14, 11),\n... (8, 10, 6),\n... (2, 7, 0)\n... ]\n>>> coordinates_np = np.array(coordinates)\n>>> coordinates_np[:, 0:2]\narray([[ 9, 2],\n [ 4, 14],\n [ 8, 10],\n [ 2, 7]])\n numpy" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17192742/" ]
74,583,263
<p>I am trying to use Shared Preferences and send my data into another activity. When I click on the registration textview the application crashes and I get the error message</p> <pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.EditText com.google.android.material.textfield.TextInputLayout.getEditText()' on a null object reference at com.example.irongym.RegistrationActivity.onCreate(RegistrationActivity.java:45) </code></pre> <p>In other cases where I was using EditText, I used a similar way and it was working. I think that the way I try to get the data is wrong because now I am using TextInputLayout</p> <p>This is my RegistrationActivity.java (onCreate)</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences file = getSharedPreferences(&quot;userData&quot;, MODE_PRIVATE); TextInputLayout nameField = findViewById(R.id.TextInputEditText); TextInputLayout passwordField = findViewById(R.id.PasswordInputEditText); TextInputLayout phoneField = findViewById(R.id.PhoneInputEditText); String na = file.getString(&quot;name&quot;, &quot;&quot;); String pas = file.getString(&quot;password2&quot;, &quot;&quot;); String ph = file.getString(&quot;phone&quot;, &quot;&quot;); nameField.getEditText().setText(na); // This is line 45 from the error i get passwordField.getEditText().setText(pas); phoneField.getEditText().setText(ph); </code></pre> <p>This is my RegistrationActivity.java button onclick</p> <pre><code>public void confirmInput(View v) { SharedPreferences file = getSharedPreferences(&quot;userData&quot;, MODE_PRIVATE); SharedPreferences.Editor editor = file.edit(); TextInputLayout nameField = findViewById(R.id.TextInputEditText); TextInputLayout passwordField = findViewById(R.id.PasswordInputEditText); TextInputLayout phoneField = findViewById(R.id.PhoneInputEditText); String name = nameField.getEditText().getText().toString(); String password2 = passwordField.getEditText().getText().toString(); String phone = phoneField.getEditText().getText().toString(); editor.putString(&quot;name&quot;, name); editor.putString(&quot;password2&quot;, password2); editor.putString(&quot;phone&quot;, phone); editor.commit(); Intent in = new Intent(this, LoginActivity.class); startActivity(in); } </code></pre> <p>This is my ProfileActivity.java where the data will be displayed</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityProfileBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); SharedPreferences file = getSharedPreferences(&quot;userData&quot;, MODE_PRIVATE); String we = file.getString(&quot;weight&quot;, &quot;no-weight&quot;); String he = file.getString(&quot;height&quot;, &quot;no-height&quot;); String na = file.getString(&quot;name&quot;, &quot;no-name&quot;); String ph = file.getString(&quot;phone&quot;, &quot;no-phone&quot;); String ps = file.getString(&quot;password2&quot;, &quot;no-password&quot;); TextView tvWe = findViewById(R.id.tvWeight); TextView tvHe = findViewById(R.id.tvHeight); TextView tvNa = findViewById(R.id.tvName); TextView tvPh = findViewById(R.id.tvPhone); TextView tvPs = findViewById(R.id.tvPassword); tvWe.setText(we); tvHe.setText(he); tvNa.setText(na); tvPh.setText(ph); tvPs.setText(ps); binding.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, &quot;Replace with your own action&quot;, Snackbar.LENGTH_LONG) .setAction(&quot;Action&quot;, null).show(); } }); } </code></pre>
[ { "answer_id": 74583483, "author": "lawrence", "author_id": 1257303, "author_profile": "https://Stackoverflow.com/users/1257303", "pm_score": 2, "selected": false, "text": "setContentView()" }, { "answer_id": 74584763, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "setContentView View TextInputLayout nameField = findViewById(R.id.TextInputEditText);\n View nameField nameField.getEditText() // crashes with a NullPointerException\n Caused by: java.lang.NullPointerException:\nAttempt to invoke virtual method\n'android.widget.EditText com.google.android.material.textfield.TextInputLayout.getEditText()'\non a null object reference\n getEditText() TextInputLayout" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15897853/" ]
74,583,264
<p>When I try to use Axios in serverSideProps I get a strange data value, at first, I thought it was a Redux issue, but no, if I replace Axios with Fetch everything works correctly. Outside of serverSideProps Axios also works well.</p> <pre><code>export async function getServerSideProps() { const res = await axios.get( `https://jsonplaceholder.typicode.com/posts/` ); console.log(res.data); // const res = await fetch(`https://jsonplaceholder.typicode.com/posts/`); // console.log(await res.json()); return { props: {} }; } </code></pre> <p><a href="https://i.stack.imgur.com/VGwXM.png" rel="nofollow noreferrer">value I get</a></p> <p><a href="https://codesandbox.io/p/sandbox/festive-carlos-p2di7t" rel="nofollow noreferrer">codeSandbox example</a></p>
[ { "answer_id": 74583483, "author": "lawrence", "author_id": 1257303, "author_profile": "https://Stackoverflow.com/users/1257303", "pm_score": 2, "selected": false, "text": "setContentView()" }, { "answer_id": 74584763, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "setContentView View TextInputLayout nameField = findViewById(R.id.TextInputEditText);\n View nameField nameField.getEditText() // crashes with a NullPointerException\n Caused by: java.lang.NullPointerException:\nAttempt to invoke virtual method\n'android.widget.EditText com.google.android.material.textfield.TextInputLayout.getEditText()'\non a null object reference\n getEditText() TextInputLayout" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891437/" ]
74,583,273
<p>I want to pass Array of string values to a string literal as follows</p> <p>Code :</p> <pre class="lang-js prettyprint-override"><code>var array = ['1','2556','3','4','5']; ... ... var output = ` &lt;scr`+`ipt&gt; window.stringArray = [`+ array +`] &lt;/scr`+`ipt&gt; ` </code></pre> <p>Output :</p> <pre><code>&lt;script&gt; window.stringArray = [1,2556,3,4,5] &lt;/script&gt; </code></pre> <p>Desired Output:</p> <pre><code>&lt;script&gt; window.stringArray = ['1','2556','3','4','5'] &lt;/script&gt; </code></pre> <p>I've tried to not string the arrays and string it inside the multiline string, but the values are too long for int to handle and it breaks e.g. [888555985744859665555] this will turn into [888555985744859665500] and it's a push on the memory, easy to use string regardless! Next I've tried to use map function within the inline string like this</p> <pre><code>`[`+ array.map(String) +`]` </code></pre> <p>I can't add any more lines to the output string mentioned above, code can be modified within the one line or added above it!</p>
[ { "answer_id": 74583300, "author": "Lakshya Raj", "author_id": 14469685, "author_profile": "https://Stackoverflow.com/users/14469685", "pm_score": 0, "selected": false, "text": "JSON.stringify var array = ['1','2556','3','4','5'];\n\nvar output = `\n<scr`+`ipt>\n window.stringArray = `+ JSON.stringify(array) +`;\n</scr`+`ipt>\n\n`;\n\nconsole.log(output); JSON.stringify" }, { "answer_id": 74583344, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 2, "selected": true, "text": "stringify / const array = ['1','2556','3','4','5'];\n\nconst output = `\n <script>\n window.stringArray = ${JSON.stringify(array)}\n <\\/script>\n`;\n\nconsole.log(output);" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16617567/" ]
74,583,333
<p>I'm trying to create a class method that can run some code after its execution.</p> <p>In <code>pytest</code> we have this functionality with <code>fixtures</code>:</p> <pre class="lang-py prettyprint-override"><code>@pytest.fixture def db_connection(conn_str: str): connection = psycopg2.connect(conn_str) yield connection connection.close() # this code will be executed after the test is done </code></pre> <p>Using this fixture in some test guarantees that connection will be closed soon after the test finishes. This behavior is described <a href="https://docs.pytest.org/en/6.2.x/fixture.html" rel="nofollow noreferrer">here</a>, in the Teardown section.</p> <p>When I try to do it in my own class methods, I didn't get the same result.</p> <pre class="lang-py prettyprint-override"><code>class Database: def __call__(self, conn_str: str): conn = psycopg2.connect(conn_str) yield conn print(&quot;Got here&quot;) conn.close() database = Database() conn = next(database()) cur = conn.cursor() cur.execute(&quot;select * from users&quot;) result = cur.fetchall() conn.commit() result </code></pre> <p>The output is the data in users table, but I never see the &quot;Got here&quot; string, so I'm guessing this code after the <code>yield</code> keyword never runs.</p> <p>Is there a way to achieve this?</p>
[ { "answer_id": 74583385, "author": "Carcigenicate", "author_id": 3000206, "author_profile": "https://Stackoverflow.com/users/3000206", "pm_score": 2, "selected": true, "text": "next database = Database()\ngen = database() # Saved the generator to a variable\nconn = next(gen)\ncur = conn.cursor()\ncur.execute(\"select * from users\")\nresult = cur.fetchall()\nconn.commit()\nnext(gen) # Triggers the latter part of the function\n StopIteration" }, { "answer_id": 74583500, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "contextmanager.contextlib from contextlib import contextmanager\n\n@contextmanager\ndef db_connection(conn_str):\n connection = psycopg2.connect(conn_str)\n yield connection\n connection.close()\n\nwith db_connection(...) as db:\n ...\n Database.__enter__ Database.__exit__ class Database:\n def __init__(self, conn_str: str):\n self.conn_str = conn_str\n\n def __enter__(self):\n self.conn = psycopg2.connect(self.conn_str)\n return self.conn\n\n def __exit__(self, *args):\n print(\"Got here\")\n self.conn.close()\n\nwith Database(...) as db:\n ...\n psycopg2.connect" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14153592/" ]
74,583,353
<p>I have a dataset like:</p> <pre><code>year = c(&quot;2000&quot;, &quot;2000&quot;, &quot;2000&quot;, &quot;2002&quot;, &quot;2000&quot;, &quot;2002&quot;, &quot;2007&quot;) id = c(&quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;Z&quot;, &quot;Z&quot;, &quot;Z&quot;) product = c(&quot;apple&quot;, &quot;orange&quot;, &quot;orange&quot;, &quot;orange&quot;, &quot;cake&quot;, &quot;cake&quot;, &quot;bacon&quot;) market = c(&quot;CHN&quot;, &quot;USA&quot;, &quot;USA&quot;, &quot;USA&quot;, &quot;SPA&quot;, &quot;CHL&quot;, &quot;CHL&quot;) df = data.frame(year, id, product, market) </code></pre> <p>I want to create 3 variables indicating:</p> <ol> <li>FPFM = takes value 1 if it is the first time with this product in this given market</li> <li>FP = takes value 1 if it is the first time with this product</li> <li>FM = takes value 1 if it is the first time in this market:</li> </ol> <p>Therefore, the new data will look like:</p> <pre><code>year = c(&quot;2000&quot;, &quot;2000&quot;, &quot;2000&quot;, &quot;2002&quot;, &quot;2000&quot;, &quot;2002&quot;, &quot;2007&quot;) id = c(&quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;Z&quot;, &quot;Z&quot;, &quot;Z&quot;) product = c(&quot;apple&quot;, &quot;orange&quot;, &quot;orange&quot;, &quot;orange&quot;, &quot;cake&quot;, &quot;cake&quot;, &quot;bacon&quot;) market = c(&quot;CHN&quot;, &quot;USA&quot;, &quot;USA&quot;, &quot;USA&quot;, &quot;SPA&quot;, &quot;CHL&quot;, &quot;CHL&quot;) FPFM = c(1, 1, 1, 0, 1, 1, 1) FP = c(1, 1, 1, 0, 1, 0, 1) FM = c(1, 1, 1, 0, 1, 1, 0) df_desired = data.frame(year, id, product, market, FPFM, FP, FM) </code></pre> <p>I have tried the following <strong>df_new</strong> code without success:</p> <pre><code>df_new &lt;- df %&gt;% arrange(id, year) %&gt;% group_by(id, product, market) %&gt;% mutate(FPFM = row_number(year) == 1) %&gt;% as.data.frame() %&gt;% group_by(id, product) %&gt;% mutate(FP = row_number(year) == 1) %&gt;% as.data.frame() %&gt;% group_by(id, market) %&gt;% mutate(FM = row_number(year) == 1) %&gt;% as.data.frame() </code></pre> <p>It only gives a value for really the first observation. I want to have the value for the FIRST YEAR that product,market or combination of the two is observed.</p> <p>Row 3 should be &quot;TRUE; TRUE; TRUE&quot; instead of &quot;FALSE; FASLE; FALSE&quot; as it belongs to the same year.</p> <p>The other solution that I think about is to summarise df by unique values 3 times and then right join with the original df. However, this will take lot of time and space as I have lots of data.</p> <p>Do you have a most efficient and integrated solution?</p>
[ { "answer_id": 74583385, "author": "Carcigenicate", "author_id": 3000206, "author_profile": "https://Stackoverflow.com/users/3000206", "pm_score": 2, "selected": true, "text": "next database = Database()\ngen = database() # Saved the generator to a variable\nconn = next(gen)\ncur = conn.cursor()\ncur.execute(\"select * from users\")\nresult = cur.fetchall()\nconn.commit()\nnext(gen) # Triggers the latter part of the function\n StopIteration" }, { "answer_id": 74583500, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "contextmanager.contextlib from contextlib import contextmanager\n\n@contextmanager\ndef db_connection(conn_str):\n connection = psycopg2.connect(conn_str)\n yield connection\n connection.close()\n\nwith db_connection(...) as db:\n ...\n Database.__enter__ Database.__exit__ class Database:\n def __init__(self, conn_str: str):\n self.conn_str = conn_str\n\n def __enter__(self):\n self.conn = psycopg2.connect(self.conn_str)\n return self.conn\n\n def __exit__(self, *args):\n print(\"Got here\")\n self.conn.close()\n\nwith Database(...) as db:\n ...\n psycopg2.connect" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13484989/" ]
74,583,373
<p>There is a service is defined as below:</p> <pre><code>export class MyService { doSomething(callbacks: { onSuccess: (data: Object) =&gt; any, onError: (err: any) =&gt; any }) { // This function does something } } </code></pre> <p>It is used in a component as below:</p> <pre><code>export class MyComponent implements OnInit { someFunction(): void { this.myService.doSomething( { onSuccess(data: Object) { onSuccessFunction(data) // Error here }, onError(err: any) { } } ) } onSuccessFunction(data: Object) { } } </code></pre> <p>As can be seen above, the <code>onSuccessFunction</code> which is defined in <code>MyComponent</code> and invoked in the anonymous function <code>onSuccess</code>. But still typescript is giving error as below:</p> <pre><code>Property 'initActiveOrders' does not exist on type '{ onSuccess: (data: Object) =&gt; any; onError: (err: HttpErrorResponse) =&gt; any; }'.ts(2339) </code></pre> <p>What can be the possible reason?</p>
[ { "answer_id": 74583396, "author": "Cheteel", "author_id": 20519869, "author_profile": "https://Stackoverflow.com/users/20519869", "pm_score": 0, "selected": false, "text": "this." }, { "answer_id": 74583487, "author": "pzaenger", "author_id": 2436655, "author_profile": "https://Stackoverflow.com/users/2436655", "pm_score": 2, "selected": true, "text": "someFunction(): void { \n this.myService.doSomething({\n onSuccess: (data: Object) => {\n this.onSuccessFunction(data);\n },\n ...\n });\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3722884/" ]
74,583,390
<p>How to refactor this function to a higher order function?</p> <p>It is meant to return a new array containing the sub-arrays of <strong>characters</strong> that contain the value 'Rambo'.</p> <pre><code>function isRamboCharacter(characters) { const x = []; for (let i = 0; i &lt; characters.length; i++) { if (characters[i].movie.includes('Rambo')) { x.push(characters[i]); } } return x; } </code></pre> <p>I tried:</p> <pre><code>return characters.movie.includes('Rambo'); </code></pre>
[ { "answer_id": 74583396, "author": "Cheteel", "author_id": 20519869, "author_profile": "https://Stackoverflow.com/users/20519869", "pm_score": 0, "selected": false, "text": "this." }, { "answer_id": 74583487, "author": "pzaenger", "author_id": 2436655, "author_profile": "https://Stackoverflow.com/users/2436655", "pm_score": 2, "selected": true, "text": "someFunction(): void { \n this.myService.doSomething({\n onSuccess: (data: Object) => {\n this.onSuccessFunction(data);\n },\n ...\n });\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534662/" ]
74,583,393
<p>I wish to order the columns of a dataset in order of decreasing column variance but I have had no luck in doing so. This is what I have so far:</p> <pre><code>og_data &lt;- og_data[, sort(apply(og_data, 2, var), decreasing=TRUE)] </code></pre> <p>Now, I know this doesn't work since <code>sort(apply(og_data, 2, var), decreasing=TRUE)</code> returns the variance values of the columns in order of decreasing variance. I have no idea how to extract the column indexes from this which is what I would need to use. Any help would be much appreciated.</p>
[ { "answer_id": 74583396, "author": "Cheteel", "author_id": 20519869, "author_profile": "https://Stackoverflow.com/users/20519869", "pm_score": 0, "selected": false, "text": "this." }, { "answer_id": 74583487, "author": "pzaenger", "author_id": 2436655, "author_profile": "https://Stackoverflow.com/users/2436655", "pm_score": 2, "selected": true, "text": "someFunction(): void { \n this.myService.doSomething({\n onSuccess: (data: Object) => {\n this.onSuccessFunction(data);\n },\n ...\n });\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15198024/" ]
74,583,402
<p>I want to print out the average amount of an 2D array column, by filling the matrix with random numbers</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { int m = 0; int n = 0; int array[m][n]; double ran_num = (double)rand() / RAND_MAX; double avg_col[] = {0}; printf(&quot;Enter (m, n &gt; 0): &quot;); scanf(&quot;%d, %d&quot;, &amp;m, &amp;n); for(size_t i = 0; i &lt;= m; ++i){ for(size_t j = 0; j &lt;= n; ++j){ array[i][j] = ran_num; avg_col[j] += array[i][j] / m; } } for(int i = 0; i &lt; n; i++){ printf(&quot;Average of column %d : %.3f\n&quot;, i ,avg_col[i]); } return 0; } </code></pre> <p>But the output is:</p> <pre><code>Average of column 0 : 0.000 Average of column 1 : 0.000 Average of column 2 : 0.000 </code></pre> <p>I can't figure out where the problem is. Maybe you can help me, I would really appreciate it.</p>
[ { "answer_id": 74583396, "author": "Cheteel", "author_id": 20519869, "author_profile": "https://Stackoverflow.com/users/20519869", "pm_score": 0, "selected": false, "text": "this." }, { "answer_id": 74583487, "author": "pzaenger", "author_id": 2436655, "author_profile": "https://Stackoverflow.com/users/2436655", "pm_score": 2, "selected": true, "text": "someFunction(): void { \n this.myService.doSomething({\n onSuccess: (data: Object) => {\n this.onSuccessFunction(data);\n },\n ...\n });\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20385971/" ]
74,583,417
<h4>I need to parse a string, which contains both text content and specific tags.</h4> <p>Expected result must be an array containing items, with separation between texts and tags.</p> <h2>An example of string to parse</h2> <pre><code>There is user [[user-foo]][[/user-foo]] and user [[user-bar]]label[[/user-bar]]. </code></pre> <p>Some informations:</p> <ul> <li><code>user-</code> tag is static.</li> <li>Following part (<code>foo</code> or <code>bar</code>) is dynamic and can be any string.</li> <li>Same for the text parts.</li> <li>Tags can receive some text as child.</li> </ul> <h2>Expected result</h2> <pre><code>[ 'There is user ', '[[user-foo]][[/user-foo]]', ' and user ', '[[user-bar]]label[[/user-bar]]', '.' ] </code></pre> <h2>What I tried</h2> <p>Here is a regex I created:</p> <pre><code>/\[\[user-[^\]]+]][A-Za-z]*\[\[\/user-[^\]]+\]\]/g </code></pre> <p>It's visible/editable here: <a href="https://regex101.com/r/ufwVV1/1" rel="nofollow noreferrer">https://regex101.com/r/ufwVV1/1</a></p> <p>It identifies all tag parts, and returns two matches, related to the two tags I have. But, text content is not included. I don't know if this first approach is correct.</p>
[ { "answer_id": 74583396, "author": "Cheteel", "author_id": 20519869, "author_profile": "https://Stackoverflow.com/users/20519869", "pm_score": 0, "selected": false, "text": "this." }, { "answer_id": 74583487, "author": "pzaenger", "author_id": 2436655, "author_profile": "https://Stackoverflow.com/users/2436655", "pm_score": 2, "selected": true, "text": "someFunction(): void { \n this.myService.doSomething({\n onSuccess: (data: Object) => {\n this.onSuccessFunction(data);\n },\n ...\n });\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5908790/" ]
74,583,419
<p>I am a at the very beginning of learning to code in python and am following a tutorial. I attempted to convert this string into an integer to get it to simply add 5 and 6. Here is what I have</p> <p>No matter what I do, I get 5+6 = 56. Here is what I have:</p> <p>first_num = (input('Please enter a number ')) second_num = (input('Please enter another number '))</p> <p>print int((first_num) + int(second_num))</p> <p>I tried using a comma instead of a plus sign, as a few places suggested. I also tried using int in front of the input line to convert the inputs themselves from strings to integer.</p> <p>I expect it to add 5 + 6 = 11. I keep getting 56.</p> <p>I'm not positive what version of Python I'm using, but I know I'm using VS Code and it is Python 3.X. i just don't know what the X is. <a href="https://i.stack.imgur.com/zMt3C.jpg" rel="nofollow noreferrer">Here is a screenshot</a></p> <p>edit: I have resolved this question. I was not saving the file before I ran it. Therefore every time I tried to change something it was just running the saved, incorrect file. Thanks to those that tried to help me.</p>
[ { "answer_id": 74583457, "author": "Aroune", "author_id": 20521674, "author_profile": "https://Stackoverflow.com/users/20521674", "pm_score": 0, "selected": false, "text": "first_num = int(input('Please enter a number '))\nsecond_num = int(input('Please enter another number '))\nsum=first_num+second_num\nprint (sum)\n" }, { "answer_id": 74583462, "author": "ViaTech", "author_id": 8382028, "author_profile": "https://Stackoverflow.com/users/8382028", "pm_score": 1, "selected": false, "text": "string_one = \"hello\"\nstring_two = \" \"\nstring_three = \"there\"\nfinal = string_one + string_two + string_3\n\nprint(final) # hello there\n one = 1\ntwo = 2\nfinal = one + two\n\nprint(final, type(final)) # 3 int\n first_num = int(input('Please enter a number')) \nsecond_num = int(input('Please enter another number'))\nfinal = first_num + second_num\n\nprint(final) # will give you the numbers added\n hi try:\n first_num = int(input('Please enter a number')) \n second_num = int(input('Please enter another number'))\n\n print(first_num + second_num) # will give you the numbers added, if ints\nexcept ValueError as ex:\n # if any input val is not an int, this will hit\n print(\"Error, not an int\", ex)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607677/" ]
74,583,468
<p>i have an html file with some javascript locally offline on my computer and want to enbed an svg favicon in that html file to show up in the browser without the need of an extra <code>favicon.svg</code> file. is it possible to get this working some how?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;favicon.svg&quot;&gt; ... </code></pre> <p>so instead of <code>&lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;favicon.svg&quot;&gt;</code> i want to embed the <code>favicon.svg</code> in the html page.</p> <p>here an example of favicon.svg</p> <pre><code>&lt;svg width=&quot;256&quot; height=&quot;256&quot; viewBox=&quot;0 0 256 256&quot;&gt; &lt;rect style=&quot;fill:#FF3010;stroke:none&quot; width=&quot;256&quot; height=&quot;256&quot; x=&quot;0&quot; y=&quot;0&quot; /&gt; &lt;/svg&gt; </code></pre> <p>according to <a href="https://stackoverflow.com/questions/53962736/embed-svg-icon-into-html">Embed SVG icon into html</a>, i tried</p> <p>just paste the svg content:</p> <pre><code>&lt;link rel=&quot;icon&quot; href=&quot;data:image/svg+xml,&lt;svg width=&quot;256&quot; height=&quot;256&quot; viewBox=&quot;0 0 256 256&quot;&gt;&lt;rect style=&quot;fill:#FF3010;stroke:none&quot; width=&quot;256&quot; height=&quot;256&quot; x=&quot;0&quot; y=&quot;0&quot; /&gt;&lt;/svg&gt;&quot;&gt; </code></pre> <p>replaced the double quotes (<code>&quot;</code>) by single quotes (<code>'</code>):</p> <pre><code>&lt;link rel=&quot;icon&quot; href=&quot;data:image/svg+xml,&lt;svg width='256' height='256' viewBox='0 0 256 256'&gt;&lt;rect style='fill:#FF3010;stroke:none' width='256' height='256' x='0' y='0' /&gt;&lt;/svg&gt;&quot;&gt; </code></pre> <p>translated special characters to %XX format:</p> <pre><code>&lt;link rel=&quot;icon&quot; href=&quot;data:image/svg+xml,%3Csvg%20width=%22256%22%20height=%22256%22%20viewBox=%220%200%20256%20256%22%3E%3Crect%20style=%22fill:#FF3010;stroke:none%22%20width=%22256%22%20height=%22256%22%20x=%220%22%20y=%220%22%20/%3E%3C/svg%3E&quot;&gt; </code></pre> <p>translated svg content to base64:</p> <pre><code>&lt;link rel=&quot;icon&quot; href=&quot;data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiPjxyZWN0IHN0eWxlPSJmaWxsOiNGRjMwMTA7c3Ryb2tlOm5vbmUiIHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiB4PSIwIiB5PSIwIiAvPjwvc3ZnPg==&quot;&gt; </code></pre> <p>but in non of the cases the favicon showed up in the browser.</p> <p>i tried firefox-esr 102.5.0 and chromium 104.0.5112.105.</p> <p>the favicon as extra <code>favicon.svg</code> file is working, but the embedded data are not working.</p>
[ { "answer_id": 74583854, "author": "chrwahl", "author_id": 322084, "author_profile": "https://Stackoverflow.com/users/322084", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"256\" height=\"256\"\n viewBox=\"0 0 256 256\">\n <rect style=\"fill:#FF3010;stroke:none\" width=\"256\" height=\"256\"\n x=\"0\" y=\"0\" />\n</svg>\n <html>\n <head>\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiB3aWR0aD0iMjU2IgogaGVpZ2h0PSIyNTYiCiB2aWV3Qm94PSIwIDAgMjU2IDI1NiI+CiA8cmVjdAogIHN0eWxlPSJmaWxsOiNGRjMwMTA7c3Ryb2tlOm5vbmUiCiAgd2lkdGg9IjI1NiIKICBoZWlnaHQ9IjI1NiIKICB4PSIwIgogIHk9IjAiIC8+Cjwvc3ZnPgo=\">\n ...\n <meta http-equiv=\"Content-Security-Policy\" content=\"default-src data:\" />\n data:" }, { "answer_id": 74585787, "author": "beta-tester", "author_id": 14533222, "author_profile": "https://Stackoverflow.com/users/14533222", "pm_score": 0, "selected": false, "text": "<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:svg=\"http://www.w3.org/2000/svg\" \n...\n <html>\n <head>\n <link rel=\"icon\" href=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmci...\n...\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14533222/" ]
74,583,505
<p>I have a variable with lists with varied number of elements:</p> <pre><code>['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] ['124', 'M', '19', 'M', '7', 'M'] ['19', 'M', '131', 'M'] ['3', 'M', '19', 'M', '128', 'M'] ['12', 'M', '138', 'M'] </code></pre> <p>Variable is always number, letter and order matters.</p> <p>I would to add the values only of consecutive Ms to be (i.e. if there is a D, skip the sum):</p> <pre><code>['30', 'M', '1', 'D', '120', 'M'] ['150', 'M'] ['150', 'M'] ['150', 'M'] ['150', 'M'] </code></pre> <p>ps. the complete story is that I want to convert soft clips to match in a bam file, but got stuck in that step.</p> <pre><code>#!/usr/bin/python import sys import pysam bamFile = sys.argv[1]; bam = pysam.AlignmentFile(bamFile, 'rb') for read in bam: cigar=read.cigarstring sepa = re.findall('(\d+|[A-Za-z]+)', cigar) for i in range(len(sepa)): if sepa[i] == 'S': sepa[i] = 'M' </code></pre>
[ { "answer_id": 74583528, "author": "Martijn Pieters", "author_id": 100297, "author_profile": "https://Stackoverflow.com/users/100297", "pm_score": 3, "selected": true, "text": ">>> example = ['30', 'M', '1', 'D', '120', 'M']\n>>> example[1::2]\n['M', 'D', 'M']\n [1::2] : [::2] zip() def sum_m_values(values):\n summed = []\n m_sum = 0\n for number, letter in zip(values[::2], values[1::2]):\n if letter != \"M\":\n if m_sum:\n summed += (str(m_sum), \"M\")\n m_sum = 0\n summed += (number, letter)\n else:\n m_sum += int(number)\n if m_sum:\n summed += (str(m_sum), \"M\")\n return summed\n \"M\" \"M\" \"M\" \"M\" >>> def sum_m_values(values):\n... summed = []\n... m_sum = 0\n... for number, letter in zip(values[::2], values[1::2]):\n... if letter != \"M\":\n... if m_sum:\n... summed += (str(m_sum), \"M\")\n... m_sum = 0\n... summed += (number, letter)\n... else:\n... m_sum += int(number)\n... if m_sum:\n... summed += (str(m_sum), \"M\")\n... return summed\n...\n>>> examples = [\n... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n... ['124', 'M', '19', 'M', '7', 'M'],\n... ['19', 'M', '131', 'M'],\n... ['3', 'M', '19', 'M', '128', 'M'],\n... ['12', 'M', '138', 'M'],\n... ]\n>>> for example in examples:\n... print(example, \"->\", sum_m_values(example))\n...\n['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] -> ['30', 'M', '1', 'D', '120', 'M']\n['124', 'M', '19', 'M', '7', 'M'] -> ['150', 'M']\n['19', 'M', '131', 'M'] -> ['150', 'M']\n['3', 'M', '19', 'M', '128', 'M'] -> ['150', 'M']\n['12', 'M', '138', 'M'] -> ['150', 'M']\n iter() zip() it = iter(inputlist)\nfor number, letter in zip(it, it):\n # ...\n zip() \"30\" \"M\" >>> example = ['124', 'M', '19', 'M', '7', 'M']\n>>> it = iter(example)\n>>> for number, letter in zip(it, it):\n... print(number, letter)\n...\n124 M\n19 M\n7 M\n itertools.groupby() zip() lambda pair: pair[1] operator.itemgetter(1) lambda from itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n summed = []\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n if letter == \"M\":\n total = sum(int(number) for number, _ in grouped)\n summed += (str(total), letter)\n else:\n # add the (number, \"D\") as separate elements\n for number, letter in grouped:\n summed += (number, letter)\n \n return summed\n summed += ... yield from ... from itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n if letter == \"M\":\n total = sum(int(number) for number, _ in grouped)\n yield from (str(total), letter)\n else:\n # add the (number, \"D\") as separate elements\n for number, letter in grouped:\n yield from (number, letter)\n\n list(sum_m_values(...)) M D M if from itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n yield str(sum(int(number) for number, _ in grouped))\n yield letter\n number D" }, { "answer_id": 74583713, "author": "Grzegorz Skibinski", "author_id": 11610186, "author_profile": "https://Stackoverflow.com/users/11610186", "pm_score": 0, "selected": false, "text": "itertools >>> from itertools import groupby, chain\n>>> records = [\n... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n... ['124', 'M', '19', 'M', '7', 'M'],\n... ['19', 'M', '131', 'M'],\n... ['3', 'M', '19', 'M', '128', 'M'],\n... ['12', 'M', '138', 'M'],\n... ]\n>>> res = []\n>>> for rec in records:\n... res.append(list(\n... chain.from_iterable(\n... map(\n... lambda x: (\n... str(sum(map(lambda y: y[0], x[1]))),\n... x[0],\n... ),\n... groupby(\n... zip(map(int, rec[::2]), rec[1::2]),\n... lambda k: k[1]\n... )\n... )\n... )\n... ))\n...\n>>> res\n[['30', 'M', '1', 'D', '120', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M']]\n" }, { "answer_id": 74583740, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "LoL=[\n ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n ['20', 'M', '10', 'M', '1', 'D', '2', 'D', '14', 'M', '106', 'M'],\n ['124', 'M', '19', 'M', '7', 'M'],\n ['19', 'M', '131', 'M'],\n ['3', 'M', '19', 'M', '128', 'M'],\n ['12', 'M', '138', 'M'],\n]\n M from itertools import groupby\n\n\nfor l in LoL:\n result=[]\n for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)), \n key=lambda l: l[1]):\n result.extend([sum(int(l[0]) for l in v), k])\n print(result)\n [30, 'M', 1, 'D', 120, 'M']\n[30, 'M', 3, 'D', 120, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n 'M' k for l in LoL:\n result=[]\n for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)), \n key=lambda l: l[1]):\n if k=='M':\n result.extend([sum(int(l[0]) for l in v), k])\n else:\n for e in v:\n result.extend([e[0], k])\n print(result)\n [30, 'M', '1', 'D', 120, 'M']\n[30, 'M', '1', 'D', '2', 'D', 120, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607709/" ]
74,583,527
<p>I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this.</p> <p>such that the following list</p> <pre><code>example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre> <p>becomes:</p> <pre><code>solution = [[0, 0, 0], [1, 1, 1], [2, 2, 2]] </code></pre>
[ { "answer_id": 74583552, "author": "sourin", "author_id": 14912756, "author_profile": "https://Stackoverflow.com/users/14912756", "pm_score": 0, "selected": false, "text": "example = [[1,2,3],[4,5,6],[7,8,9]]\nsolution = [[x for _ in range(len(example[x]))] for x in range(len(example))]\nprint(solution)\n Output\n[[0, 0, 0], [1, 1, 1], [2, 2, 2]]\n" }, { "answer_id": 74583564, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": -1, "selected": false, "text": "map res = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n map" }, { "answer_id": 74583566, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n" }, { "answer_id": 74583587, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "solution = [[i]*len(x) for i, x in enumerate(example)]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20330710/" ]
74,583,565
<p>I need to create a pandas dataframe based on 4 txt files with comments (to skip while reading) based on the following structure:</p> <pre><code># Moteur conçu par le Poly Propulsion Lab (PPL) nom=Tondeuse # Propriétés générales hauteur=0.5 masse=20.0 prix=110.00 # Propriétés du moteur impulsion specifique=80 </code></pre> <p>and</p> <pre><code># Moteur conçu par le Poly Propulsion Lab (PPL) nom=Civic VTEC # Propriétés générales hauteur=2.0 masse=3000.0 prix=2968.00 # Propriétés du moteur impulsion specifique=205 </code></pre> <p>and</p> <pre><code># Moteur conçu par le Poly Propulsion Lab (PPL) nom=VelociRAPTOR # Propriétés générales hauteur=4.0 masse=2000.0 prix=6000.00 # Propriétés du moteur impulsion specifique=250 </code></pre> <p>and</p> <pre><code># Moteur conçu par le Poly Propulsion Lab (PPL) nom=La Puissance # Propriétés générales hauteur=12.0 masse=15000.0 prix=39000.00 # Propriétés du moteur impulsion specifique=295 </code></pre> <p>That's the result I need to have:</p> <pre><code> nom hauteur masse prix impulsion specifique 0 Tondeuse 0.5 20.0 110.0 80 1 Civic VTEC 2.0 3000.0 2968.0 205 2 VelociRAPTOR 4.0 2000.0 6000.0 250 3 La Puissance 12.0 15000.0 39000.0 295 </code></pre> <p>I don't know if it's possible, but that's what i was asked to do</p>
[ { "answer_id": 74583552, "author": "sourin", "author_id": 14912756, "author_profile": "https://Stackoverflow.com/users/14912756", "pm_score": 0, "selected": false, "text": "example = [[1,2,3],[4,5,6],[7,8,9]]\nsolution = [[x for _ in range(len(example[x]))] for x in range(len(example))]\nprint(solution)\n Output\n[[0, 0, 0], [1, 1, 1], [2, 2, 2]]\n" }, { "answer_id": 74583564, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": -1, "selected": false, "text": "map res = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n map" }, { "answer_id": 74583566, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n" }, { "answer_id": 74583587, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "solution = [[i]*len(x) for i, x in enumerate(example)]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607791/" ]
74,583,607
<p>I am training a machine with reinforcements, everything is going well, but the task is to get the number of the game in which 5 victories were won in a row.</p> <p>The algorithm consists of a loop that calculates 10,000 games, in each of which the agent walks on a frozen lake using 100 steps (for each game). If the agent correctly passes the lake, this is considered a victory, and so 10,000 games (iterations). I got 7914 winning games - this is the correct answer.</p> <p><strong>And the next question is: Complete the following code so that as a result of training the model, you can find out the number of wins and the number of the game (game) in which the agent won the fifth win in a row for the first time.</strong></p> <p>Here is my code:</p> <pre><code>for game in tqdm(range(total_games)): //BODY OF CYCLE success += reward # COUNTS WINNING GAMES </code></pre> <p>I need a simple algorithm that will select the first five wins in a row and put it in a variable. Something like this, but it's of course wrong:</p> <pre><code>if success==5: game5Success = game </code></pre>
[ { "answer_id": 74583552, "author": "sourin", "author_id": 14912756, "author_profile": "https://Stackoverflow.com/users/14912756", "pm_score": 0, "selected": false, "text": "example = [[1,2,3],[4,5,6],[7,8,9]]\nsolution = [[x for _ in range(len(example[x]))] for x in range(len(example))]\nprint(solution)\n Output\n[[0, 0, 0], [1, 1, 1], [2, 2, 2]]\n" }, { "answer_id": 74583564, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": -1, "selected": false, "text": "map res = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n map" }, { "answer_id": 74583566, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n" }, { "answer_id": 74583587, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "solution = [[i]*len(x) for i, x in enumerate(example)]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20371531/" ]
74,583,639
<pre><code>char model[10][15] = {&quot;Honda&quot;,&quot;Audi&quot;,&quot;Ferrari&quot;,&quot;Jeep&quot;,&quot;Toyota&quot;,&quot;Bugatti&quot;,&quot;Ford&quot;,&quot;Jensen&quot;,&quot;Porsche&quot;,&quot;Suzuki&quot;}; int price[10][15] = {750000,650000,950000,300000,900000,1000000,400000,750000,300000,800000}; int remain[10][15] = {3,4,5,3,3,7,8,2,1,2,2}; for(i=0;i&lt;11;i++){ printf(&quot;\n%s\t %d\t %d\t&quot;,model[i],price[i],remain[i]); } </code></pre> <p>I tried all sorts of things but nothing worked... I'm a new C programmer (just jumped from JAVA)</p>
[ { "answer_id": 74583552, "author": "sourin", "author_id": 14912756, "author_profile": "https://Stackoverflow.com/users/14912756", "pm_score": 0, "selected": false, "text": "example = [[1,2,3],[4,5,6],[7,8,9]]\nsolution = [[x for _ in range(len(example[x]))] for x in range(len(example))]\nprint(solution)\n Output\n[[0, 0, 0], [1, 1, 1], [2, 2, 2]]\n" }, { "answer_id": 74583564, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": -1, "selected": false, "text": "map res = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n map" }, { "answer_id": 74583566, "author": "Always Sunny", "author_id": 1138192, "author_profile": "https://Stackoverflow.com/users/1138192", "pm_score": 1, "selected": false, "text": "for example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n" }, { "answer_id": 74583587, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "solution = [[i]*len(x) for i, x in enumerate(example)]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607912/" ]
74,583,683
<p>So I get this error when I run the program. The error is supposed to be at line 11 after the 'try' block but that's exactly how the author of the book I use for learning python displayed it. Can someone help me?</p> <pre><code>print(&quot;Give me two number, and I'll divide them.&quot;) print(&quot;Enter 'q' to quit.&quot;) while True: first_number = input(&quot;\nFirst number: &quot;) if first_number == 'q': break second_number = input(&quot;Second number: &quot;) if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print(&quot;You can't divide by zero!&quot;) else: print(answer) </code></pre> <p>I wanted it to work but it didn't.</p>
[ { "answer_id": 74583698, "author": "CreepyRaccoon", "author_id": 18342123, "author_profile": "https://Stackoverflow.com/users/18342123", "pm_score": -1, "selected": false, "text": "try while True:\n first_number = input(\"\\nFirst number: \")\n if first_number == 'q':\n break\n second_number = input(\"Second number: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_number) / int(second_number)\n except ZeroDivisionError:\n print(\"You can't divide by zero!\")\n else:\n print(answer)\n" }, { "answer_id": 74583699, "author": "Riya", "author_id": 19674402, "author_profile": "https://Stackoverflow.com/users/19674402", "pm_score": 0, "selected": false, "text": "print(\"Give me two number, and I'll divide them.\")\nprint(\"Enter 'q' to quit.\")\n\nwhile True:\n first_number = input(\"\\nFirst number: \")\n if first_number == 'q':\n break\n second_number = input(\"Second number: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_number) / int(second_number)\n except ZeroDivisionError:\n print(\"You can't divide by zero!\")\n else:\n print(answer)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607952/" ]
74,583,694
<p>There is a website that stores two videos as a list of thousands of PNGs, 31145 images in total. Is there a way to automate the downloading by generating the URLs? (I have no knowledge in coding.)</p> <ol> <li>Here's the 1st video's <a href="https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/00000ms/match/image.png" rel="nofollow noreferrer">first frame</a> and its <a href="https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/19999ms/match/image.png" rel="nofollow noreferrer">last frame</a>.</li> <li>Here's the 2nd video's <a href="https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/e23d962c-114b-40ed-b934-667f77482f8e/main/1280x720/00000ms/match/image.png" rel="nofollow noreferrer">first frame</a> and its <a href="https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/e23d962c-114b-40ed-b934-667f77482f8e/main/1280x720/11144ms/match/image.png" rel="nofollow noreferrer">last frame</a>.</li> </ol> <hr /> <p>I couldn't access the directory and batch download the files.</p> <p>I took a look at <a href="https://stackoverflow.com/questions/26854036/how-to-download-multiple-numbered-images-from-a-website-in-an-easy-manner">this answer</a> but it doesn't apply to me as I use Windows 10, and also checked <a href="https://stackoverflow.com/questions/2591758/batch-script-loop">this answer</a>; I tried to merge them into <code>for /l %x in (1, 1, 19999) do (wget https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%%xms/match/image.png)</code> which did not work obviously.</p> <p>I then downloaded Python 3.11 to try <a href="https://stackoverflow.com/questions/31324672/downloading-a-list-of-files-from-a-website">this answer</a> but doesn't work, it's probably too old as it tells me urllib2 doesn't exist.</p>
[ { "answer_id": 74583829, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "template = 'xxx/%05dms/match/image.png'\nfor i in range(1,11): # limited for brevity sake, adjust as requires\n print(template % i)\n xxx/00001ms/match/image.png\nxxx/00002ms/match/image.png\nxxx/00003ms/match/image.png\nxxx/00004ms/match/image.png\nxxx/00005ms/match/image.png\nxxx/00006ms/match/image.png\nxxx/00007ms/match/image.png\nxxx/00008ms/match/image.png\nxxx/00009ms/match/image.png\nxxx/00010ms/match/image.png\n %05d urllib.urlretrieve import urllib\ntemplate_url = 'xxx/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(1,11):\n urllib.urlretrieve(template_url % i, template_name % i)\n image00001.png xrange python2 urllib.urlretrieve urllib.request.urlretrieve" }, { "answer_id": 74584571, "author": "OUTEIRAL DIAS Esteban", "author_id": 16950238, "author_profile": "https://Stackoverflow.com/users/16950238", "pm_score": -1, "selected": true, "text": "import urllib\nimport urllib.request\ntemplate_url = 'https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(0,20000):\n f = template_name % i\n urllib.request.urlretrieve(template_url % i, f)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950238/" ]
74,583,711
<p>I am trying to import a class named 'Questions' from my models.py to admin.py <code>from .models import Questions</code> I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to?</p> <p>I tried this combinations but it was no avail <code>from models import Questions</code> <code>from Model.models import Questions</code></p>
[ { "answer_id": 74583829, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "template = 'xxx/%05dms/match/image.png'\nfor i in range(1,11): # limited for brevity sake, adjust as requires\n print(template % i)\n xxx/00001ms/match/image.png\nxxx/00002ms/match/image.png\nxxx/00003ms/match/image.png\nxxx/00004ms/match/image.png\nxxx/00005ms/match/image.png\nxxx/00006ms/match/image.png\nxxx/00007ms/match/image.png\nxxx/00008ms/match/image.png\nxxx/00009ms/match/image.png\nxxx/00010ms/match/image.png\n %05d urllib.urlretrieve import urllib\ntemplate_url = 'xxx/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(1,11):\n urllib.urlretrieve(template_url % i, template_name % i)\n image00001.png xrange python2 urllib.urlretrieve urllib.request.urlretrieve" }, { "answer_id": 74584571, "author": "OUTEIRAL DIAS Esteban", "author_id": 16950238, "author_profile": "https://Stackoverflow.com/users/16950238", "pm_score": -1, "selected": true, "text": "import urllib\nimport urllib.request\ntemplate_url = 'https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(0,20000):\n f = template_name % i\n urllib.request.urlretrieve(template_url % i, f)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16523984/" ]
74,583,735
<p>I have problem with seeders in laravel 9. The problem is when I want to execute all seeders with commands like php artisan db:seed, php artisan db:fresh and similar commands that should execute all seeders. Seeder are only working when I specify exact class with command like php artisan db:seed --class=UserSeeder and similar command that are executing specific seeder. How I can fix this problem and execute all seeders?</p>
[ { "answer_id": 74583829, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "template = 'xxx/%05dms/match/image.png'\nfor i in range(1,11): # limited for brevity sake, adjust as requires\n print(template % i)\n xxx/00001ms/match/image.png\nxxx/00002ms/match/image.png\nxxx/00003ms/match/image.png\nxxx/00004ms/match/image.png\nxxx/00005ms/match/image.png\nxxx/00006ms/match/image.png\nxxx/00007ms/match/image.png\nxxx/00008ms/match/image.png\nxxx/00009ms/match/image.png\nxxx/00010ms/match/image.png\n %05d urllib.urlretrieve import urllib\ntemplate_url = 'xxx/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(1,11):\n urllib.urlretrieve(template_url % i, template_name % i)\n image00001.png xrange python2 urllib.urlretrieve urllib.request.urlretrieve" }, { "answer_id": 74584571, "author": "OUTEIRAL DIAS Esteban", "author_id": 16950238, "author_profile": "https://Stackoverflow.com/users/16950238", "pm_score": -1, "selected": true, "text": "import urllib\nimport urllib.request\ntemplate_url = 'https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(0,20000):\n f = template_name % i\n urllib.request.urlretrieve(template_url % i, f)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17440063/" ]
74,583,737
<p>I need to replace each half of an image with the other half:</p> <p>Starting with this:</p> <p><a href="https://i.stack.imgur.com/PhRI9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PhRI9.png" alt="Original" /></a></p> <p>Ending with this:</p> <p><a href="https://i.stack.imgur.com/aSY0t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aSY0t.png" alt="Desired" /></a></p> <p>I have tried to use crop, but I want the image to keep the same dimensions, and this seems to just cut it.</p> <pre><code> im = Image.open(&quot;image.png&quot;) w, h = im.size im = im.crop((0,0,int(w/2),h)) im.paste(im, (int(w/2),0,w,h)) im.save('test.png') </code></pre>
[ { "answer_id": 74583874, "author": "arsho", "author_id": 3129414, "author_profile": "https://Stackoverflow.com/users/3129414", "pm_score": 2, "selected": false, "text": "from PIL import Image\noutput_image = 'test.png'\nim = Image.open(\"input.png\")\nw, h = im.size\nleft_x = int(w / 2) - 2\nright_x = w - left_x\nleft_portion = im.crop((0, 0, left_x, h))\nright_portion = im.crop((right_x, 0, w, h))\nim.paste(right_portion, (0, 0, left_x, h))\nim.paste(left_portion, (right_x, 0, w, h))\nim.save(output_image)\nprint(f\"saved image {output_image}\")\n input.png output.png left_x = int(w / 2) - 2" }, { "answer_id": 74583943, "author": "Mark Setchell", "author_id": 2836621, "author_profile": "https://Stackoverflow.com/users/2836621", "pm_score": 3, "selected": true, "text": "from PIL import Image, ImageChops\n\n# Open image\nim = Image.open('...')\n\n# Roll image by half its width in x-direction, and not at all in y-direction\nImageChops.offset(im, xoffset=int(im.width/2), yoffset=0).save('result.png')\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20518918/" ]
74,583,758
<p>(Problem solved, I will accept my answer in 2 days when the system allows me to).</p> <p><a href="https://i.stack.imgur.com/SER2B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SER2B.png" alt="enter image description here" /></a></p> <p>I have a background applied to all of my <code>div</code> elements within my <code>.main</code> class. However, I would not like this background to be applied to the <code>.options</code> <code>div</code>. How can I do this? The arrows are pointing to the background I am referring to in the image.</p> <p>I have tried to add <code>background-color: transparent !important</code> in the <code>.options</code> CSS element, but that didn't fix it and nothing happened.</p> <p>(Please view the code snippet in the full page as it shows the problem better) <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>* { padding: 0; margin: 0; font-family: "Roboto", sans-serif; } body { background: url(https://wallpapercave.com/wp/d7W4Xn1.jpg) no-repeat center fixed; background-size: cover; } .btn-select { background-color: #008cba; border-radius: 10px; text-align: center; } .main { margin-top: 100px; background-color: transparent !important; } .main div { background-color: rgba(255, 255, 255, 0.75); border-radius: 25px; width: fit-content; } .big { font-size: 60px; } .btn-game { border-radius: 10px; } .restart { width: 70px; } .new-game { width: 200px; } .score-div { display: none; } .num { display: none; } .options { text-transform: capitalize; margin: auto; width: 100%; background-color: transparent !important; } ul { list-style-type: none; } li { list-style-type: none; } .option { background-color: cyan !important; border-radius: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;body&gt; &lt;main class="text-justify text-center main"&gt; &lt;div class="container"&gt; &lt;h1 class="big"&gt;&lt;span&gt;All Flags&lt;/span&gt;&lt;/h1&gt; &lt;div class="container"&gt; &lt;h2 class="score"&gt;Score: &lt;span&gt;&lt;/span&gt;/251&lt;/h2&gt; &lt;/div&gt; &lt;h2 class="num"&gt;Question: &lt;span&gt;&lt;/span&gt;&lt;/h2&gt; &lt;div class="flag-img"&gt; &lt;img src="https://flagcdn.com/h240/jm.png" /&gt; &lt;/div&gt; &lt;div class="container options"&gt; &lt;div class="text-justify text-center"&gt; &lt;p class="option"&gt;Scotland&lt;/p&gt; &lt;p class="option"&gt;Guyana&lt;/p&gt; &lt;p class="option"&gt;Jamaica&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;button onclick="restart()" class="btn-game restart"&gt;Restart&lt;/button&gt; &lt;button onclick="newGame()" class="btn-game new-game"&gt; Try a different gamemode &lt;/button&gt; &lt;div class="score-div"&gt; &lt;h3 class="correct"&gt;Correct Answers: &lt;span&gt;&lt;/span&gt;/251&lt;/h3&gt; &lt;button onclick="restart()" class="btn-game restart"&gt;Restart&lt;/button&gt; &lt;button onclick="newGame()" class="btn-game new-game"&gt; Try a different gamemode &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;script src="all.js"&gt;&lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74583960, "author": "kushagra-aa", "author_id": 14001385, "author_profile": "https://Stackoverflow.com/users/14001385", "pm_score": 0, "selected": false, "text": "background-color: transparent !important; .options background-color: cyan !important; .options cyan * {\n padding: 0;\n margin: 0;\n font-family: \"Roboto\", sans-serif;\n}\n\nbody {\n background: url(http://ndquiz.epizy.com/flags/img/worldPersonalProject.png)\n no-repeat center fixed;\n background-size: cover;\n}\n\n.btn-select {\n background-color: #008cba;\n border-radius: 10px;\n text-align: center;\n}\n\n.main {\n margin-top: 100px;\n background-color: transparent !important;\n}\n\n.main div {\n background-color: rgba(255, 255, 255, 0.75);\n border-radius: 25px;\n width: fit-content;\n}\n\n.big {\n font-size: 60px;\n}\n\n.btn-game {\n border-radius: 10px;\n}\n\n.restart {\n width: 70px;\n}\n\n.new-game {\n width: 200px;\n}\n\n.score-div {\n display: none;\n}\n\n.num {\n display: none;\n}\n\n.options {\n text-transform: capitalize;\n margin: auto;\n width: 100%;\nbackground-color: cyan !important;\n border-radius: 10px;\n}\n\nul {\n list-style-type: none;\n}\n\nli {\n list-style-type: none;\n}\n\n.option {\n background-color: transparent !important;\n} <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <body>\n <main class=\"text-justify text-center main\">\n <div class=\"container\">\n <h1 class=\"big\"><span>All Flags</span></h1>\n <div class=\"container\">\n <h2 class=\"score\">Score: <span></span>/251</h2>\n </div>\n <h2 class=\"num\">Question: <span></span></h2>\n <div class=\"flag-img\">\n <img src=\"https://flagcdn.com/h240/jm.png\" />\n </div>\n <div class=\"container options\">\n <div class=\"text-justify text-center\">\n <p class=\"option\">Scotland</p>\n <p class=\"option\">Guyana</p>\n <p class=\"option\">Jamaica</p>\n </div>\n </div>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n <div class=\"score-div\">\n <h3 class=\"correct\">Correct Answers: <span></span>/251</h3>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n </div>\n </div>\n </main>\n <script src=\"all.js\"></script>\n </body> !important" }, { "answer_id": 74584036, "author": "nd03", "author_id": 18884489, "author_profile": "https://Stackoverflow.com/users/18884489", "pm_score": 2, "selected": true, "text": ".main div:not(.options) { background-color: rgba(255, 255, 255, 0.75) !important; } .options div * {\n padding: 0;\n margin: 0;\n font-family: \"Roboto\", sans-serif;\n}\n\nbody {\n background: url(https://wallpapercave.com/wp/d7W4Xn1.jpg)\n no-repeat center fixed;\n background-size: cover;\n}\n\n.btn-select {\n background-color: #008cba;\n border-radius: 10px;\n text-align: center;\n}\n\n.main {\n margin-top: 100px;\n background-color: transparent !important;\n}\n\n.main div {\n border-radius: 25px;\n width: fit-content;\n}\n\n.main div:not(.options) {\n background-color: rgba(255, 255, 255, 0.75) !important;\n}\n\n.big {\n font-size: 60px;\n}\n\n.btn-game {\n border-radius: 10px;\n margin-bottom: 10px;\n}\n\n.restart {\n width: 70px;\n}\n\n.new-game {\n width: 200px;\n}\n\n.score-div {\n display: none;\n}\n\n.num {\n display: none;\n}\n\n.options {\n text-transform: capitalize;\n margin: auto;\n width: 100%;\n background-color: transparent !important;\n}\n\nul {\n list-style-type: none;\n}\n\nli {\n list-style-type: none;\n}\n\n.option {\n background-color: cyan !important;\n border-radius: 10px;\n cursor: pointer;\n} <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <body>\n <main class=\"text-justify text-center main\">\n <div class=\"container\">\n <h1 class=\"big\"><span>All Flags</span></h1>\n <div class=\"container\">\n <h2 class=\"score\">Score: <span></span>/251</h2>\n </div>\n <h2 class=\"num\">Question: <span></span></h2>\n <div class=\"flag-img\">\n <img src=\"https://flagcdn.com/h240/jm.png\" />\n </div>\n <div class=\"container options\">\n <div class=\"text-justify text-center options\">\n <p class=\"bg-none option\">Scotland</p>\n <p class=\"option\">Guyana</p>\n <p class=\"bg-none option\">Jamaica</p>\n </div>\n </div>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n <div class=\"score-div\">\n <h3 class=\"correct\">Correct Answers: <span></span>/251</h3>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n </div>\n </div>\n </main>\n <script src=\"all.js\"></script>\n </body>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18884489/" ]
74,583,770
<p>Those are the array models:</p> <pre><code>struct UserModel: Codable { var userid: Int var nickname: String } struct UserModelSplit: Codable { var usr: [UserModel] } </code></pre> <p>Initialising them:</p> <pre><code>@State private var users = [UserModel]() @State private var userSplit = [UserModelSplit]() </code></pre> <p>Getting the first array:</p> <pre><code>for bla in userReceived{ users.append(UserModel(userid: bla.userid, nickname: bla.nickname)) } </code></pre> <p>Now I want to split it to the multidimensional array so the result should be:</p> <pre><code>userSplit[0][0] // 1th user userSplit[0][1] // 2th user userSplit[0][2] // 3th user userSplit[0][3] // 4th user userSplit[1][0] // 5th user userSplit[1][1] // 6th user userSplit[1][2] // 7th user userSplit[1][3] // 8th user </code></pre> <p>I tried all kind of syntaxes and looked up how it could be done without finding anythi useful.</p> <p>This is the pseudo code which sums up what I've tried:</p> <pre><code>var current = 0 var added = 0 for val in users{ userSplit[current][added] = val added += 1 if(added == 3){ current += 1 added = 0 } } </code></pre> <p>This pseudo code is similar to how it would actually work in PHP</p> <p>I hope it's understandable :D</p>
[ { "answer_id": 74583960, "author": "kushagra-aa", "author_id": 14001385, "author_profile": "https://Stackoverflow.com/users/14001385", "pm_score": 0, "selected": false, "text": "background-color: transparent !important; .options background-color: cyan !important; .options cyan * {\n padding: 0;\n margin: 0;\n font-family: \"Roboto\", sans-serif;\n}\n\nbody {\n background: url(http://ndquiz.epizy.com/flags/img/worldPersonalProject.png)\n no-repeat center fixed;\n background-size: cover;\n}\n\n.btn-select {\n background-color: #008cba;\n border-radius: 10px;\n text-align: center;\n}\n\n.main {\n margin-top: 100px;\n background-color: transparent !important;\n}\n\n.main div {\n background-color: rgba(255, 255, 255, 0.75);\n border-radius: 25px;\n width: fit-content;\n}\n\n.big {\n font-size: 60px;\n}\n\n.btn-game {\n border-radius: 10px;\n}\n\n.restart {\n width: 70px;\n}\n\n.new-game {\n width: 200px;\n}\n\n.score-div {\n display: none;\n}\n\n.num {\n display: none;\n}\n\n.options {\n text-transform: capitalize;\n margin: auto;\n width: 100%;\nbackground-color: cyan !important;\n border-radius: 10px;\n}\n\nul {\n list-style-type: none;\n}\n\nli {\n list-style-type: none;\n}\n\n.option {\n background-color: transparent !important;\n} <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <body>\n <main class=\"text-justify text-center main\">\n <div class=\"container\">\n <h1 class=\"big\"><span>All Flags</span></h1>\n <div class=\"container\">\n <h2 class=\"score\">Score: <span></span>/251</h2>\n </div>\n <h2 class=\"num\">Question: <span></span></h2>\n <div class=\"flag-img\">\n <img src=\"https://flagcdn.com/h240/jm.png\" />\n </div>\n <div class=\"container options\">\n <div class=\"text-justify text-center\">\n <p class=\"option\">Scotland</p>\n <p class=\"option\">Guyana</p>\n <p class=\"option\">Jamaica</p>\n </div>\n </div>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n <div class=\"score-div\">\n <h3 class=\"correct\">Correct Answers: <span></span>/251</h3>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n </div>\n </div>\n </main>\n <script src=\"all.js\"></script>\n </body> !important" }, { "answer_id": 74584036, "author": "nd03", "author_id": 18884489, "author_profile": "https://Stackoverflow.com/users/18884489", "pm_score": 2, "selected": true, "text": ".main div:not(.options) { background-color: rgba(255, 255, 255, 0.75) !important; } .options div * {\n padding: 0;\n margin: 0;\n font-family: \"Roboto\", sans-serif;\n}\n\nbody {\n background: url(https://wallpapercave.com/wp/d7W4Xn1.jpg)\n no-repeat center fixed;\n background-size: cover;\n}\n\n.btn-select {\n background-color: #008cba;\n border-radius: 10px;\n text-align: center;\n}\n\n.main {\n margin-top: 100px;\n background-color: transparent !important;\n}\n\n.main div {\n border-radius: 25px;\n width: fit-content;\n}\n\n.main div:not(.options) {\n background-color: rgba(255, 255, 255, 0.75) !important;\n}\n\n.big {\n font-size: 60px;\n}\n\n.btn-game {\n border-radius: 10px;\n margin-bottom: 10px;\n}\n\n.restart {\n width: 70px;\n}\n\n.new-game {\n width: 200px;\n}\n\n.score-div {\n display: none;\n}\n\n.num {\n display: none;\n}\n\n.options {\n text-transform: capitalize;\n margin: auto;\n width: 100%;\n background-color: transparent !important;\n}\n\nul {\n list-style-type: none;\n}\n\nli {\n list-style-type: none;\n}\n\n.option {\n background-color: cyan !important;\n border-radius: 10px;\n cursor: pointer;\n} <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <body>\n <main class=\"text-justify text-center main\">\n <div class=\"container\">\n <h1 class=\"big\"><span>All Flags</span></h1>\n <div class=\"container\">\n <h2 class=\"score\">Score: <span></span>/251</h2>\n </div>\n <h2 class=\"num\">Question: <span></span></h2>\n <div class=\"flag-img\">\n <img src=\"https://flagcdn.com/h240/jm.png\" />\n </div>\n <div class=\"container options\">\n <div class=\"text-justify text-center options\">\n <p class=\"bg-none option\">Scotland</p>\n <p class=\"option\">Guyana</p>\n <p class=\"bg-none option\">Jamaica</p>\n </div>\n </div>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n <div class=\"score-div\">\n <h3 class=\"correct\">Correct Answers: <span></span>/251</h3>\n <button onclick=\"restart()\" class=\"btn-game restart\">Restart</button>\n <button onclick=\"newGame()\" class=\"btn-game new-game\">\n Try a different gamemode\n </button>\n </div>\n </div>\n </main>\n <script src=\"all.js\"></script>\n </body>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19559647/" ]
74,583,787
<p>I have been through many similar QnAs on StackOverflow but I am still confused about why it does not work for me. I understand that state update is not synchronous. Also I am not performing any DOM manipulation.</p> <p>The full working demo here which demonstrates the issue - <a href="https://codesandbox.io/s/falling-pine-kljujf?file=/src/Tabs.js" rel="nofollow noreferrer">https://codesandbox.io/s/falling-pine-kljujf?file=/src/Tabs.js</a></p> <p>In this example I am rendering few tabs. A new tab initially presents a list of DB &quot;table&quot; names (which is fixed for this demo). On selecting the table name, the list is replaced by table's content.</p> <p><a href="https://i.stack.imgur.com/t5weL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t5weL.png" alt="Initial state" /></a></p> <p>The issue is when you close an open tab the <code>currentTab</code> state does not update to the (open) tab I am setting to. Because of which the tab's detail area remains blank until I manually click on an open tab's name.</p> <p><a href="https://i.stack.imgur.com/cCdJx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cCdJx.png" alt="After closing the third tab" /></a></p> <p>In the above picture I closed the third tab. The expectation was that the tab selection should have auto changed to second tab, but it did not. The code for that same is as below.</p> <pre><code> function removeTab(id) { const ntl = tabsList; const idx = ntl.findIndex((v) =&gt; v.id === id); if (idx !== -1) { ntl.splice(idx, 1); if (ntl.length) { let t = ntl[idx]; console.log(&quot;------&quot;, t, idx); if (!t) { t = ntl[0]; } console.log(&quot;++++++1&quot;, t, t.id); setCurrentTab(t.id); setTabsList([...ntl]); } else { const t = newTab(); console.log(&quot;++++++2&quot;, t, t.id); setCurrentTab(t.id); setTabsList([t]); } } } </code></pre> <p>Above the passed <code>id</code> was that of the third tab. The <code>tabsList</code> state contains an array with data of each tab. <code>currentTab</code> contains only the <code>id</code> of the current tab. As per the <code>console.log</code> statements above the correct tab's <code>id</code> is passed, but the currentTab never updates. Even if I put a code like below.</p> <pre><code>useEffect(() =&gt; { console.log('------------&gt;', currentTab) }, [currentTab]); </code></pre> <p>It never fires in this case.</p> <p>The <code>removeTab</code> method is invoked from JSX like below.</p> <pre><code>{tabsList.map((t) =&gt; ( &lt;a key={t.id + &quot;&quot;} className={ &quot;tab tab-bordered &quot; + (currentTab === t.id ? &quot;tab-active&quot; : &quot;&quot;) } onClick={() =&gt; { setCurrentTab(t.id); }} &gt; {t.name} &lt;button onClick={() =&gt; { removeTab(t.id); // On clicking X button we remove tab }} &gt; X &lt;/button&gt; &lt;/a&gt; ))} </code></pre>
[ { "answer_id": 74584411, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 0, "selected": false, "text": "let tabId = 1;\n\nconst DisplayTable = ({ isNewMode, name, ...rest }) => {\n return (\n <div>\n {isNewMode ? (\n <TableSelection {...rest} />\n ) : (\n <div>Contents of table: {name}</div>\n )}\n </div>\n );\n};\n\nexport default function Tabs() {\n const [tabsList, setTabsList] = useState([\n {\n id: tabId,\n name: \"Select table\",\n isNewMode: true\n }\n ]);\n const [currentTab, setCurrentTab] = useState(tabId);\n\n function newTab() {\n tabId = tabId + 1; // unique id check\n return {\n id: tabId,\n name: \"Select table\",\n isNewMode: true\n };\n }\n\n function addTab() {\n const t = newTab();\n setTabsList((tabs) => [...tabs, t]);\n console.log(\"++++++3\", t, t.id);\n setCurrentTab(t.id);\n }\n\n async function removeTab(id) {\n\n // functional updaters are simpler\n // setTabsList(tabs => [...tabs.filter((a) => a.id !== id)])\n\n\n // need better logic to select the right tab, this seems simeple enough to understand\n const deleteIndex = tabsList.findIndex((v) => v.id === id);\n // \n if (deleteIndex !== -1) {\n const filteredItems = tabsList.filter((a) => a.id !== id);\n\n if (deleteIndex > 0) {\n const prevId = filteredItems[deleteIndex - 1];\n console.log(\"prevId\", prevId);\n\n setTabsList([...filteredItems]);\n await Promise.resolve();\n setCurrentTab(prevId.id);\n }\n }\n }\n\n const selectedItem = tabsList?.find((item) => item.id === currentTab);\n\n // console.log(\"Rendering......\", currentTab, tabsList);\n return (\n <div className=\"p-8 h-full flex flex-col\">\n <div className=\"tabs\">\n {tabsList.map((t) => (\n <a\n href=\"#\"\n key={t.id}\n className={\n \"tab tab-bordered \" + (currentTab === t.id ? \"tab-active\" : \"\")\n }\n onClick={(e) => {\n e.preventDefault();\n setCurrentTab(t.id);\n }}\n >\n {t.name}\n <button\n className=\"ml-2 btn btn-ghost btn-square btn-xs\"\n onClick={(e) => {\n e.preventDefault();\n removeTab(t.id);\n }}\n >\n X\n </button>\n </a>\n ))}\n <a href=\"#\" className=\"tab\">\n <button\n className=\"btn btn-ghost btn-square btn-xs\"\n onClick={(e) => {\n e.preventDefault();\n addTab();\n }}\n >\n +\n </button>\n </a>\n </div>\n {selectedItem ? (\n <DisplayTable\n onTableSelection={(item) => {\n tabId = tabId + 1;\n const d = { ...item, id: tabId, isNewMode: false };\n setTabsList((t) => [...t, d]);\n console.log(\"table select\", d);\n setCurrentTab(d.id);\n }}\n {...selectedItem}\n />\n ) : null}\n {/* {tabsList.map((t) => (\n <div key={t.id}>\n <TableSelection />\n </div>\n ))} */}\n </div>\n );\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137893/" ]
74,583,788
<p>I made multiple v-model binding in vue 3. but got some probel in code quality when i must code emit value function repeating with 90% the function code is same. Is this possible to refactoring this code</p> <pre class="lang-js prettyprint-override"><code>&lt;script lang=&quot;ts&quot; setup&gt; const props = defineProps({ firstName: String, lastName: String, firstNameModifiers: { default: { default: () =&gt; ({}), capitalize: () =&gt; ({}), }, }, lastNameModifiers: { default: { default: () =&gt; ({}), capitalize: () =&gt; ({}), }, }, }); const emit = defineEmits([&quot;update:firstName&quot;, &quot;update:lastName&quot;]); // ! TODO: Make Function to handle modifiers - its repeating below function firstNameEmitValue(e: Event) { const target = e.target as HTMLInputElement; let value = target.value; if (props.firstNameModifiers[&quot;capitalize&quot;]) { value = value.charAt(0).toUpperCase() + value.slice(1); } emit(`update:firstName`, value); } function lastNameEmitValue(e: Event) { const target = e.target as HTMLInputElement; let value = target.value; if (props.firstNameModifiers[&quot;capitalize&quot;]) { value = value.charAt(0).toUpperCase() + value.slice(1); } emit(`update:lastName`, value); } &lt;/script&gt; &lt;template&gt; &lt;input type=&quot;text&quot; :value=&quot;firstName&quot; @input=&quot;firstNameEmitValue&quot; /&gt; &lt;input type=&quot;text&quot; :value=&quot;lastName&quot; @input=&quot;lastNameEmitValue&quot; /&gt; &lt;/template&gt; </code></pre> <p>Its ok when just using 1 modifiers. But its will become annoying if i want to add other modifiers. for example toUppercase, toLowerCase etch. Maybe the solution is just separate the component for firstname input and lastname input and make it as single v-model and emit.</p> <p>But i just want to try this approach bcause vue put it in, in their documentation.</p> <p><a href="https://vuejs.org/guide/components/events.html#usage-with-v-model" rel="nofollow noreferrer">Events Documentation</a></p>
[ { "answer_id": 74586519, "author": "anas laaroussi", "author_id": 12469248, "author_profile": "https://Stackoverflow.com/users/12469248", "pm_score": 0, "selected": false, "text": "<script lang=\"ts\" setup>\nconst props = defineProps({\n firstName: String,\n lastName: String,\n firstNameModifiers: {\n default: {\n default: () => ({}),\n capitalize: () => ({}),\n },\n },\n lastNameModifiers: {\n default: {\n default: () => ({}),\n capitalize: () => ({}),\n },\n },\n});\nconst emit = defineEmits([\"update:firstName\", \"update:lastName\"]);\n\n// ! TODO: Make Function to handle modifiers - its repeating below\nfunction EmitValue(e: Event, type: String) {\n const target = e.target as HTMLInputElement;\n let value = target.value;\n if (type === \"first\") {\n if (props.firstNameModifiers[\"capitalize\"]) {\n value = value.charAt(0).toUpperCase() + value.slice(1);\n }\n emit(`update:firstName`, value);\n } else {\n if (props.lastNameModifiers[\"capitalize\"]) {\n value = value.charAt(0).toUpperCase() + value.slice(1);\n }\n emit(`update:lastName`, value);\n }\n}\n\n</script>\n\n<template>\n <input type=\"text\" :value=\"firstName\" @input=\"EmitValue($event, 'first')\" />\n <input type=\"text\" :value=\"lastName\" @input=\"EmitValue($event, 'last')\" />\n</template>\n" }, { "answer_id": 74586881, "author": "tao", "author_id": 1891677, "author_profile": "https://Stackoverflow.com/users/1891677", "pm_score": 3, "selected": true, "text": "export const names = [\"first\", \"last\"]\n <script lang=\"ts\" setup>\n import { reactive, computed } from \"vue\"\n import { names } from '../path/to/helpers'\n\n const modifiers = {\n default: {\n default: () => ({}),\n capitalize: () => ({})\n }\n }\n\n const props = defineProps(\n Object.assign(\n {},\n ...names.map((name) => ({\n [name + \"Name\"]: String,\n [name + \"NameModifiers\"]: modifiers\n }))\n )\n )\n const emit = defineEmits(names.map((name) => `update:${name}Name`))\n const emitValue = ({ target }: Event, name: string) => {\n if (target instanceof HTMLInputElement) {\n let { value } = target\n if (props[`${name}NameModifiers`][\"capitalize\"]) {\n value = value.charAt(0).toUpperCase() + value.slice(1)\n }\n emit(`update:${name}Name`, value)\n }\n }\n const state = reactive(\n Object.assign(\n {},\n ...names.map((name) => ({ [name]: computed(() => props[name]) }))\n )\n )\n</script>\n\n<template>\n <input\n type=\"text\"\n v-for=\"name in names\"\n :key=\"name\"\n :value=\"state[name]\"\n @input=\"emitValue($event, name)\"\n />\n</template>\n 'middle' names @input :value v-model <script lang=\"ts\" setup>\n import { reactive, computed } from \"vue\"\n import { names } from '../path/to/helpers'\n\n const modifiers = {\n default: {\n default: () => ({}),\n capitalize: () => ({})\n }\n }\n\n const props = defineProps(\n Object.assign(\n {},\n ...names.map((name) => ({\n [name + \"Name\"]: String,\n [name + \"NameModifiers\"]: modifiers\n }))\n )\n )\n const emit = defineEmits(names.map((name) => `update:${name}Name`))\n const state = reactive(\n Object.assign(\n {},\n ...names.map((name) => ({\n [name]: computed({\n get: () => props[name],\n set: (val) =>\n emit(\n `update:${name}Name`,\n props[`${name}NameModifiers`][\"capitalize\"]\n ? val.charAt(0).toUpperCase() + val.slice(1)\n : val\n )\n })\n }))\n )\n )\n</script>\n\n<template>\n <input type=\"text\" v-for=\"name in names\" :key=\"name\" v-model=\"state[name]\" />\n</template>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12871038/" ]
74,583,790
<p>So basically I am trying to compare two lists to see if they hold the same value at the same index at any point. If they do I return the index, if they do not, I return -1.</p> <p>When I had first done this as a test I was having no issues however adding in the text has made it more difficult and my main issue is with the if else statement. I seem to be able to only get one message to work, either yes or no, not both based on the case.</p>
[ { "answer_id": 74583931, "author": "ep742", "author_id": 13441010, "author_profile": "https://Stackoverflow.com/users/13441010", "pm_score": 1, "selected": true, "text": "enumerate zip Dlist = [17,13,10,6,2]\nIlist = [5,9,10,15,18]\n\ndef seqsearch(DS,IS):\n for idx, (d, s) in enumerate(zip(DS, IS)):\n if d == s:\n return f\"Yes! Found at index = {idx}\"\n\n return \"No!\\n-1\"\n\n\nprint(seqsearch(Dlist,Ilist))\n" }, { "answer_id": 74583991, "author": "Riya", "author_id": 19674402, "author_profile": "https://Stackoverflow.com/users/19674402", "pm_score": 0, "selected": false, "text": "Dlist = [17, 13, 10, 6, 2]\nIlist = [5, 9, 10, 15, 18]\n\n\ndef seqsearch(DS, IS):\n\n for index_1, element_1 in enumerate(DS):\n for index_2, element_2 in enumerate(IS):\n\n if (element_1 == element_2) and (index_1 == index_2):\n print(f\"Yes! Found at index ={index_1}\")\n return index_1\n print(\"No!\")\n return -1\n\n\nprint(seqsearch(Dlist, Ilist))\n zip() return print -1" }, { "answer_id": 74584060, "author": "ali", "author_id": 18280463, "author_profile": "https://Stackoverflow.com/users/18280463", "pm_score": -1, "selected": false, "text": "Dlist = [17, 13, 10, 6, 2]\nIlist = [5, 9, 10, 15, 18]\n\n\ndef seqsearch_with_print(DS, IS):\n \"\"\"this function only print not return!!!\n if you use return your function ended!\"\"\"\n for i in range(len(DS) - 1):\n if DS[i] == IS[i]:\n print(f\"Yes! Found at index {i}\")\n else:\n print(f\"No not equal in {i} index\")\n\n\ndef seqsearch_with_list(DS, IS):\n \"\"\"this function save history of (equal index or not: as 1, -1)\"\"\"\n temp_list = []\n for i in range(len(DS) - 1):\n if DS[i] == IS[i]:\n temp_list.append(1)\n else:\n temp_list.append(-1)\n return temp_list\n\n\ndef seqsearch_with_list_dict(DS, IS):\n \"\"\"this function save history of (equal index or not: as 1, -1)\n as key, value (key== index, value==list item)\"\"\"\n temp_list = []\n for i in range(len(DS) - 1):\n if DS[i] == IS[i]:\n temp_list.append({i: 1})\n else:\n temp_list.append({i: -1})\n return temp_list\n\n\n# no need print(in function we used print)\nseqsearch_with_print(Dlist, Ilist)\n\"\"\"\nreturn of function: \n No not equal in 0 index\n No not equal in 1 index\n Yes! Found at index 2\n No not equal in 3 index\"\"\"\n\n# save history of search index in list\nprint(seqsearch_with_list(Dlist, Ilist))\n\"\"\"\nreturn of function with print:\n [-1, -1, 1, -1]\n\"\"\"\n# save history as dict key value\nprint(seqsearch_with_list_dict(Dlist, Ilist))\n\"\"\"\nreturn of function with print\n [{0: -1}, {1: -1}, {2: 1}, {3: -1}]\n\"\"\"\n\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15346274/" ]
74,583,792
<p>Is it possible to create a dynamic C array which works for all types. In this instance the dynamicArr would have to work for both struct1 and struct. What should the type of <code>structuretype</code> be to work for both struct1 and struct2 depending on the user initialization?</p> <pre class="lang-c prettyprint-override"><code>typedef struct dynamicArr { structuretype *arr; int capacity; int size; }dynamicArr; </code></pre> <pre class="lang-c prettyprint-override"><code>typedef struct struct1 { int id; char *field1; char *field2; int num; }struct1; </code></pre> <pre class="lang-c prettyprint-override"><code>typedef struct struct2 { char *field; int num1; int num2; }struct2; </code></pre>
[ { "answer_id": 74583872, "author": "Monique Shaqiri", "author_id": 20414674, "author_profile": "https://Stackoverflow.com/users/20414674", "pm_score": 1, "selected": false, "text": "typedef struct { \n void *dataStructure; \n int size; \n int numElements; \n} dynamicArray; \n \ndynamicArray *init(int initialSize); \n \nvoid push(dynamicArray *A, void *element); \n \nvoid *pop(dynamicArray *A); \n \nvoid setElement(dynamicArray *A, int position, void *element); \n \nvoid *getElement(dynamicArray *A, int position); \n" }, { "answer_id": 74583907, "author": "Kompetenzbolzen", "author_id": 10986134, "author_profile": "https://Stackoverflow.com/users/10986134", "pm_score": 0, "selected": false, "text": "void* void* void malloc() void* char* int* void* #include <stdint.h>\n#include <stdio.h>\n\nint main() {\n uint8_t number = 42;\n void* ptr = &number;\n uint32_t* new_number = ptr;\n\n printf(\"%i\\n\", *new_number);\n}\n" }, { "answer_id": 74583910, "author": "UBoiii", "author_id": 19380261, "author_profile": "https://Stackoverflow.com/users/19380261", "pm_score": 0, "selected": false, "text": "void*" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13787037/" ]
74,583,876
<p>I would like to delete all the elements from list of lists that appear more than once and am looking for a smoother solution than this: <a href="https://stackoverflow.com/questions/46018429/removing-duplicate-elements-from-list-of-lists-in-prolog">Removing Duplicate Elements from List of Lists in Prolog</a></p> <p>I am not trying to remove duplicated lists inside of the parent list like here: <a href="https://stackoverflow.com/questions/55349986/how-to-remove-duplicates-from-nested-lists">How to remove duplicates from nested lists</a></p> <p>Consider this Int:</p> <pre><code>list = [ [1, 3, 4, 5, 77], [1, 5, 10, 3, 4], [1, 5, 100, 3, 4], [1, 3, 4, 5, 89], [1, 3, 5, 47, 48]] </code></pre> <p>Desired output:</p> <pre><code>new_list= [ [77], [10], [100], [89], [47, 48]] </code></pre> <p>Thanks. I am going to use this in Pandas: the new_list will serve as a new column with unique values on each row compare to the original column.</p>
[ { "answer_id": 74584145, "author": "user19077881", "author_id": 19077881, "author_profile": "https://Stackoverflow.com/users/19077881", "pm_score": 3, "selected": true, "text": "from collections import Counter\n\nmylist = [\n[1, 3, 4, 5, 77],\n[1, 5, 10, 3, 4],\n[1, 5, 100, 3, 4], \n[1, 3, 4, 5, 89], \n[1, 3, 5, 47, 48]]\n\n\nflat = [y for x in mylist for y in x] \ncount = Counter(flat)\nuniq = [x for x,y in count.items() if y == 1]\nnew_list = [[x for x in y if x in uniq] for y in mylist]\n [[77], [10], [100], [89], [47, 48]]\n" }, { "answer_id": 74584302, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 1, "selected": false, "text": "for bi,lst in enumerate(l):\n for el in lst:\n for i in range(len(l)):\n if bi != i:\n if el in l[i]:\n print(f'element:{el}')\n print(f'passing over list:{l[i]}')\n l[i].remove(el)\n try: l[bi].remove(el)\n except: continue\n" }, { "answer_id": 74597566, "author": "Mr.Slow", "author_id": 20051041, "author_profile": "https://Stackoverflow.com/users/20051041", "pm_score": 0, "selected": false, "text": "list1 = [1,3,4,5]\n\nfor list_of_numbers in numbers:\n for number in list_of_numbers:\n while number in list_of_numbers and list1:\n list_of_numbers.remove(number)\n \n\n\n[[77], [10], [100], [89], [47, 48]]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20051041/" ]
74,583,954
<p>I have a large dataset in which I want to group similar resistance patterns together. A plot to visualize similarity of resistance pattern is needed.</p> <pre><code> dat &lt;- read.table(text=&quot;Id Resistance.Pattern A SSRRSSSSR B SSSRSSSSR C RRRRSSRRR D SSSSSSSSS E SSRSSSSSR F SSSRRSSRR G SSSSR H SSSSSSRRR I RRSSRRRSS&quot;, header=TRUE) </code></pre>
[ { "answer_id": 74584345, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\np <- strsplit(dat$Resistance.Pattern, \"\")\n\ndo.call(rbind, lapply(p, \\(x) c(x, rep(NA, max(lengths(p)) - length(x))))) %>%\n as.data.frame() %>%\n cbind(Id = dat$Id) %>%\n mutate(Id = factor(Id, rev(Id))) %>%\n pivot_longer(V1:V9) %>%\n ggplot(aes(name, Id, fill = value)) +\n geom_tile(col = \"white\", size = 2) +\n coord_equal() +\n scale_fill_manual(values = c(\"#e02430\", \"#d8d848\"), \n labels = c(\"Resistant\", \"Sensitive\"),\n na.value = \"gray95\") +\n scale_x_discrete(name = \"Antibiotic\", position = \"top\",\n labels = 1:9) +\n labs(fill = \"Resistance\", y = \"ID\") +\n theme_minimal(base_size = 20) +\n theme(text = element_text(color = \"gray30\"))\n" }, { "answer_id": 74584386, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 2, "selected": false, "text": "library(tidyverse)\nlibrary(ggdendro)\n\n\nrecode_dat <- dat |>\n mutate(pat = str_split(Resistance.Pattern, \"\")) |>\n unnest_wider(pat, names_sep = \"_\") |>\n select(starts_with(\"pat_\")) |>\n mutate(across(everything(), ~case_when(. == \"S\" ~ 1, . == \"R\" ~ 2, is.na(.) ~0)))\n\nrownames(recode_dat) <- dat$Id\n\ndendro <- as.dendrogram(hclust(d = dist(x = scale(recode_dat))))\ndendro_plot <- ggdendrogram(data = dendro, rotate = TRUE)\n\n\nheatmap_plot <- dat |>\n mutate(pat = str_split(Resistance.Pattern, \"\")) |>\n unnest_wider(pat, names_sep = \"_\") |>\n pivot_longer(cols = starts_with(\"pat_\"), names_to = \"pattern_position\") |>\n mutate(Id = factor(Id, levels = dat$Id[order.dendrogram(dendro)])) |>\n ggplot(aes(pattern_position, Id))+\n geom_tile(aes(fill = value))+\n scale_x_discrete(labels = \\(x) sub(\".*_(\\\\d+$)\", \"\\\\1\", x))+\n theme(legend.position = \"top\")\n\n\ncowplot::plot_grid(heatmap_plot, dendro_plot,nrow = 1, align = \"h\", axis = \"tb\")\n" }, { "answer_id": 74584920, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "heatmap library(dplyr)\nlibrary(tidyr) # for unnest_wider\nlibrary(gplots) # for heatmap.2\n\nmm <- \ndat %>%\n group_by(Resistance.Pattern) %>%\n summarize(Id, Resistance.Pattern) %>%\n mutate(binary = strsplit(Resistance.Pattern, \"\")) %>%\n unnest_wider(binary, names_sep=\"\") %>%\n mutate(across(starts_with(\"binary\"), ~ as.numeric(c(R = 1, S = 0)[.x])))\n\nmm2 <- as.matrix(mm[, -c(1,2)]) |> unname() # the numeric part\n\nrownames(mm2) <- apply(as.matrix(mm[,1:2]), 1, paste, collapse=\" \")\n\nheatmap.2(mm2, trace=\"none\", Colv=\"none\", dendrogram=\"row\", \n col=c(\"green\", \"darkgreen\"), margins=c(10,10))\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19965337/" ]
74,583,974
<p>I'm trying to create a carousel component that has n amount of child components based on whatever size list it will get. I want the parent (carousel) to control the styling for children as it manipulates the size of the list and track the indexes to rotate items around the carousel and style accordingly. There will buttons to control this behaviour. <a href="https://i.stack.imgur.com/R01IS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R01IS.png" alt="example of the carousel" /></a></p> <p>I'm trying to apply styles and get the functionality working but cannot seem to access the styles by getting a query list of element refs using view children and template refs (I also tried with content children initially, with the template set up properly). I can change them if I inject the element ref and renderer at the child level, but I don't want to do this here. I get the error: <code>TypeError: Cannot read properties of undefined (reading 'style')</code> But not when I do the exact same thing doing it from the child level.</p> <p>Am I going about this incorrectly? How do I change children styles in a list from @ViewChildren() from a parent?</p> <p>Parent component (carousel.component.html)</p> <pre><code> &lt;div class=&quot;caro-body&quot;&gt; &lt;h3 class=&quot;caro-body__title&quot;&gt;Carousel Title&lt;/h3&gt; &lt;div class=&quot;caro-body__items&quot;&gt; &lt;app-upcoming-card #caroItem *ngFor=&quot;let card of list; let i = index&quot; &gt;&lt;/app-upcoming-card&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>(carousel.component.ts)</p> <pre><code>import { Component, OnInit, AfterViewInit, Renderer2, ViewChildren, QueryList, ElementRef, } from '@angular/core'; import { UpcomingCardComponent } from '../upcoming-card/upcoming-card.component'; @Component({ selector: 'app-carousel', templateUrl: './carousel.component.html', styleUrls: ['./carousel.component.scss'], }) export class CarouselComponent implements OnInit, AfterViewInit { @ViewChildren('caroItem') caroItems: QueryList&lt;ElementRef&lt;UpcomingCardComponent&gt;&gt; list = [ { billName: 'Rent', billAmount: 850, billDate: Date.now() }, { billName: 'Groceries', billAmount: 250, billDate: Date.now() }, { billName: 'Internet', billAmount: 80, billDate: Date.now() }, { billName: 'Phone', billAmount: 45, billDate: Date.now() }, { billName: 'Loan', billAmount: 50, billDate: Date.now() }, { billName: 'Transit', billAmount: 20, billDate: Date.now() }, { billName: 'Dining Out', billAmount: 50, billDate: Date.now() }, ]; constructor(private renderer: Renderer2) {} ngOnInit(): void {} ngAfterViewInit() { this.caroItems.forEach(item =&gt; { this.renderer.setStyle(item.nativeElement, 'background-color', 'red') }) } } </code></pre> <p>Child component (upcoming-card.component.html)</p> <pre><code>&lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card__title&quot;&gt;{{ card.billName }}&lt;/div&gt; &lt;div class=&quot;card__amount&quot;&gt;{{ card.billAmount | currency }}&lt;/div&gt; &lt;div class=&quot;card__date&quot;&gt;{{ card.billDate | date }}&lt;/div&gt; &lt;/div&gt; </code></pre> <p>(upcoming-card.component.ts)</p> <pre><code>import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-upcoming-card', templateUrl: './upcoming-card.component.html', styleUrls: ['./upcoming-card.component.scss'] }) export class UpcomingCardComponent implements OnInit { constructor() { } ngOnInit(): void { } } </code></pre> <p>I've tried accessing the list using @ContentChildren, having the template structure properly for this case as well as using the proper lifecycle hook, but it results in the same. I can update styles by injecting the element ref and renderer into the child, but I want to do it at the parent level.</p>
[ { "answer_id": 74584345, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n\np <- strsplit(dat$Resistance.Pattern, \"\")\n\ndo.call(rbind, lapply(p, \\(x) c(x, rep(NA, max(lengths(p)) - length(x))))) %>%\n as.data.frame() %>%\n cbind(Id = dat$Id) %>%\n mutate(Id = factor(Id, rev(Id))) %>%\n pivot_longer(V1:V9) %>%\n ggplot(aes(name, Id, fill = value)) +\n geom_tile(col = \"white\", size = 2) +\n coord_equal() +\n scale_fill_manual(values = c(\"#e02430\", \"#d8d848\"), \n labels = c(\"Resistant\", \"Sensitive\"),\n na.value = \"gray95\") +\n scale_x_discrete(name = \"Antibiotic\", position = \"top\",\n labels = 1:9) +\n labs(fill = \"Resistance\", y = \"ID\") +\n theme_minimal(base_size = 20) +\n theme(text = element_text(color = \"gray30\"))\n" }, { "answer_id": 74584386, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 2, "selected": false, "text": "library(tidyverse)\nlibrary(ggdendro)\n\n\nrecode_dat <- dat |>\n mutate(pat = str_split(Resistance.Pattern, \"\")) |>\n unnest_wider(pat, names_sep = \"_\") |>\n select(starts_with(\"pat_\")) |>\n mutate(across(everything(), ~case_when(. == \"S\" ~ 1, . == \"R\" ~ 2, is.na(.) ~0)))\n\nrownames(recode_dat) <- dat$Id\n\ndendro <- as.dendrogram(hclust(d = dist(x = scale(recode_dat))))\ndendro_plot <- ggdendrogram(data = dendro, rotate = TRUE)\n\n\nheatmap_plot <- dat |>\n mutate(pat = str_split(Resistance.Pattern, \"\")) |>\n unnest_wider(pat, names_sep = \"_\") |>\n pivot_longer(cols = starts_with(\"pat_\"), names_to = \"pattern_position\") |>\n mutate(Id = factor(Id, levels = dat$Id[order.dendrogram(dendro)])) |>\n ggplot(aes(pattern_position, Id))+\n geom_tile(aes(fill = value))+\n scale_x_discrete(labels = \\(x) sub(\".*_(\\\\d+$)\", \"\\\\1\", x))+\n theme(legend.position = \"top\")\n\n\ncowplot::plot_grid(heatmap_plot, dendro_plot,nrow = 1, align = \"h\", axis = \"tb\")\n" }, { "answer_id": 74584920, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "heatmap library(dplyr)\nlibrary(tidyr) # for unnest_wider\nlibrary(gplots) # for heatmap.2\n\nmm <- \ndat %>%\n group_by(Resistance.Pattern) %>%\n summarize(Id, Resistance.Pattern) %>%\n mutate(binary = strsplit(Resistance.Pattern, \"\")) %>%\n unnest_wider(binary, names_sep=\"\") %>%\n mutate(across(starts_with(\"binary\"), ~ as.numeric(c(R = 1, S = 0)[.x])))\n\nmm2 <- as.matrix(mm[, -c(1,2)]) |> unname() # the numeric part\n\nrownames(mm2) <- apply(as.matrix(mm[,1:2]), 1, paste, collapse=\" \")\n\nheatmap.2(mm2, trace=\"none\", Colv=\"none\", dendrogram=\"row\", \n col=c(\"green\", \"darkgreen\"), margins=c(10,10))\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13059486/" ]
74,583,998
<p>I have a simple question in python. How can I store arrays inside a tuple in Python. For example:</p> <p>I want the output of my code to be like this:</p> <pre><code>bnds = ((0, 1), (0, 1), (0, 1), (0, 1)) </code></pre> <p>So I want <code>(0, 1)</code> to be repeated for a specific number of times inside a tuple!</p> <p>I have tried to use the following code to loop over a tuple:</p> <pre><code>g = (()) for i in range(4): b1 = (0,1) * (i) g = (g) + (b1) print(g) </code></pre> <p>However, the output is :</p> <pre><code>(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1) </code></pre> <p>Maybe this is a simple question but I am still beginner in python!</p> <p>Any help!</p>
[ { "answer_id": 74584026, "author": "Riya", "author_id": 19674402, "author_profile": "https://Stackoverflow.com/users/19674402", "pm_score": 2, "selected": true, "text": "g = []\nb1 = (0, 1)\n\nfor i in range(4):\n g.append(b1)\ng = tuple(g)\nprint(g)\n" }, { "answer_id": 74584046, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": -1, "selected": false, "text": "g = []\nfor i in range(4):\n b1 = (0,1) * (i)\n g .append(b1)\ng = tuple(g)\n g = tuple([(0,1)*i for i in range(4)])\n g = tuple([(0,1) for i in range(4)])\n" }, { "answer_id": 74584087, "author": "sahasrara62", "author_id": 5086255, "author_profile": "https://Stackoverflow.com/users/5086255", "pm_score": 0, "selected": false, "text": ">>> result =tuple((0,1) for _ in range(4))\n>>> result \n((0, 1), (0, 1), (0, 1), (0, 1))\n" }, { "answer_id": 74584101, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 0, "selected": false, "text": "g = tuple((0,1) for i in range(4))" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74583998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19585524/" ]
74,584,045
<p>I'm following the <a href="https://firebase.google.com/docs/storage/web/download-files?hl=es-419" rel="nofollow noreferrer">firebase documentation</a> for web to download the files related to a document in firestore. I practically pasted the code to achieve this, but when I click the element is not showing anything on console.</p> <pre><code>import { ref, getDownloadURL } from 'firebase/storage' export const downloadMethod = (path) =&gt; { getDownloadURL(ref(storage, path)) .then(url =&gt; { const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = (event) =&gt; { const blob = xhr.response; }; xhr.open('GET', url); xhr.send(); }) .catch(error =&gt; { throw error }) } </code></pre> <p>Before this I was having cors error but I solved it using</p> <pre><code>[ { &quot;origin&quot;: [&quot;*&quot;], &quot;method&quot;: [&quot;GET&quot;], &quot;maxAgeSeconds&quot;: 3600 } ] </code></pre> <p>I want the website to download the requested file when I hit the button.</p>
[ { "answer_id": 74584026, "author": "Riya", "author_id": 19674402, "author_profile": "https://Stackoverflow.com/users/19674402", "pm_score": 2, "selected": true, "text": "g = []\nb1 = (0, 1)\n\nfor i in range(4):\n g.append(b1)\ng = tuple(g)\nprint(g)\n" }, { "answer_id": 74584046, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": -1, "selected": false, "text": "g = []\nfor i in range(4):\n b1 = (0,1) * (i)\n g .append(b1)\ng = tuple(g)\n g = tuple([(0,1)*i for i in range(4)])\n g = tuple([(0,1) for i in range(4)])\n" }, { "answer_id": 74584087, "author": "sahasrara62", "author_id": 5086255, "author_profile": "https://Stackoverflow.com/users/5086255", "pm_score": 0, "selected": false, "text": ">>> result =tuple((0,1) for _ in range(4))\n>>> result \n((0, 1), (0, 1), (0, 1), (0, 1))\n" }, { "answer_id": 74584101, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 0, "selected": false, "text": "g = tuple((0,1) for i in range(4))" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14598570/" ]
74,584,070
<p>I want to save canvas image as a bitmap to be able to later use it in drawImage.</p> <p>Goal is to be able to change (eg. resize) canvas and keep it's contents (eg. scaled - canvas is always a square).</p> <p>I tried: <code>var tmp = createImageBitmap(canvas)</code> <code>ctx.drawImage(tmp,0,0)</code></p> <p>What I got was an error that said 'tmp' is not a bitmap.</p>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20085898/" ]
74,584,077
<p>I am trying to write two logic for <code>WG_SHIP_ADDR_TYPE</code> key in my input. if the value was <code>2</code>, I want add <code>shipToAddress</code> object and otherwise I want add <code>WG_SHIP_ADDR_TYPE</code> value to <code>shipToAddressType</code> key.</p> <p>So how do I use both the logic in JOLT?</p> <p>Any idea on how I can make it work successfully?</p> <p><a href="https://i.stack.imgur.com/5Z1zv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Z1zv.png" alt="enter image description here" /></a></p> <p>Input-</p> <pre><code>{ &quot;PURCHASE_ORDER_DISPATCH&quot;: { &quot;MsgData&quot;: { &quot;Transaction&quot;: { &quot;PO_POD_HDR_EVW1&quot;: { &quot;WG_ADDR_SEQ_NUM&quot;: 1, &quot;WG_PO_CNTCT_EMAIL&quot;: &quot;PeggyMeincke@westfieldgrp.com&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;WG_REQ_FIRST_NAME&quot;: &quot;Zachary&quot;, &quot;WG_REQ_LAST_NAME&quot;: &quot;Engels&quot;, &quot;WG_DELIVER_TO&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;PO_DT&quot;: &quot;2020-01-24&quot;, &quot;DB_NUMBER_BU&quot;: &quot;&quot;, &quot;DESCR_BU&quot;: &quot;OhioFarmersInsuranceCo&quot;, &quot;ADDRESS1_BU&quot;: &quot;WESTFIELDCOMPANIES&quot;, &quot;ADDRESS2_BU&quot;: &quot;HOMEOFFICE&quot;, &quot;ADDRESS3_BU&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS4_BU&quot;: &quot;&quot;, &quot;CITY_BU&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_BU&quot;: &quot;OH&quot;, &quot;POSTAL_BU&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_BU&quot;: &quot;USA&quot;, &quot;ADDRESS1_BILL&quot;: &quot;&quot;, &quot;ADDRESS2_BILL&quot;: &quot;&quot;, &quot;ADDRESS3_BILL&quot;: &quot;&quot;, &quot;ADDRESS4_BILL&quot;: &quot;&quot;, &quot;CITY_BILL&quot;: &quot;&quot;, &quot;STATE_BILL&quot;: &quot;&quot;, &quot;POSTAL_BILL&quot;: &quot;&quot;, &quot;COUNTRY_BILL&quot;: &quot;&quot;, &quot;CURRENCY_CD&quot;: &quot;USD&quot;, &quot;TAX_EXEMPT_ID&quot;: &quot;&quot;, &quot;STD_ID_NUM_VNDR&quot;: &quot;&quot;, &quot;NAME1_VNDR&quot;: &quot;AMAZONCAPITALSERVICESINC&quot;, &quot;ADDRESS1_VNDR&quot;: &quot;410TERRYAVEN&quot;, &quot;ADDRESS2_VNDR&quot;: &quot;&quot;, &quot;ADDRESS3_VNDR&quot;: &quot;&quot;, &quot;ADDRESS4_VNDR&quot;: &quot;&quot;, &quot;CITY_VNDR&quot;: &quot;SEATTLE&quot;, &quot;STATE_VNDR&quot;: &quot;WA&quot;, &quot;POSTAL_VNDR&quot;: 98109, &quot;COUNTRY_VNDR&quot;: &quot;USA&quot;, &quot;PYMNT_TERMS_CD&quot;: &quot;NET30&quot;, &quot;DESCR50_PAY&quot;: &quot;Net30&quot;, &quot;BUYER_ID&quot;: 1083, &quot;PO_AMT_TTL&quot;: 14.99, &quot;TEXT254_CC1&quot;: &quot;&quot;, &quot;TEXT254_CC2&quot;: &quot;&quot;, &quot;VNDR_UPN_FLG&quot;: &quot;N&quot;, &quot;STD_ID_NUM_VNDRGLN&quot;: &quot;&quot;, &quot;STD_ID_NUM_BILLTO&quot;: &quot;&quot;, &quot;ATTN_TO&quot;: &quot;ZacharyEngels&quot;, &quot;PO_POD_LN_EVW1&quot;: { &quot;WG_REQ_ID&quot;: 25694, &quot;WG_CATEGORY_CD&quot;: &quot;FSSUP&quot;, &quot;WG_ITEM_TYPE&quot;: 0, &quot;WG_ACCOUNT&quot;: 641100, &quot;WG_DEPT_ID&quot;: 30400, &quot;WG_PRODUCT&quot;: &quot;&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;WG_ASSET_GROUP&quot;: &quot;&quot;, &quot;WG_CAPITALIZE&quot;: &quot;NO&quot;, &quot;WG_PROFILE_ID&quot;: &quot;&quot;, &quot;WG_SPLIT_TYPE&quot;: 1, &quot;WG_ASSET_LOC&quot;: &quot;HOME&quot;, &quot;WG_PROJECT&quot;: &quot;&quot;, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;INV_ITEM_ID&quot;: &quot;&quot;, &quot;DESCR254_MIXED&quot;: &quot;147-1518156-3620845,1GreenMountainCoffeeRoastersCaramelVanillaCreamKeurigSingle-ServeK-CupPods,LightRoastCoffee,32Count&quot;, &quot;UNIT_OF_MEASURE&quot;: &quot;EA&quot;, &quot;ITM_ID_VNDR&quot;: &quot;B0798CX2Q9&quot;, &quot;INV_ITEM_WEIGHT&quot;: 0, &quot;INV_ITEM_HEIGHT&quot;: 0, &quot;INV_ITEM_VOLUME&quot;: 0, &quot;INV_ITEM_LENGTH&quot;: 0, &quot;INV_ITEM_WIDTH&quot;: 0, &quot;VNDR_CATALOG_ID&quot;: &quot;&quot;, &quot;MFG_ID&quot;: &quot;&quot;, &quot;MFG_ITM_ID&quot;: 5000196305, &quot;CNTRCT_ID&quot;: &quot;&quot;, &quot;VERSION_NBR&quot;: 0, &quot;CNTRCT_LINE_NBR&quot;: 0, &quot;CAT_LINE_NBR&quot;: 0, &quot;RELEASE_NBR&quot;: 0, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;UPN_ID&quot;: &quot;&quot;, &quot;PO_POD_SHP_EVW1&quot;: { &quot;WG_SHIP_ADDR_TYPE&quot;: 0, &quot;WG_CUST_ADDR_CODE&quot;: &quot;OFIC&quot;, &quot;BUSINESS_UNIT&quot;: &quot;OFIC&quot;, &quot;PO_ID&quot;: 25052, &quot;VENDOR_SETID&quot;: &quot;WCOS&quot;, &quot;VENDOR_ID&quot;: 35958, &quot;VNDR_LOC&quot;: 1, &quot;LINE_NBR&quot;: 1, &quot;SCHED_NBR&quot;: 1, &quot;DUE_DT&quot;: &quot;2020-01-29&quot;, &quot;SHIPTO_ID&quot;: &quot;OFIC&quot;, &quot;DESCR_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS1_SHIPTO&quot;: &quot;OHIOFARMERSINSURANCECOMPANY&quot;, &quot;ADDRESS2_SHIPTO&quot;: &quot;1PARKCIRCLE&quot;, &quot;ADDRESS3_SHIPTO&quot;: &quot;POBOX5001&quot;, &quot;ADDRESS4_SHIPTO&quot;: &quot;&quot;, &quot;CITY_SHIPTO&quot;: &quot;WESTFIELDCENTER&quot;, &quot;STATE_SHIPTO&quot;: &quot;OH&quot;, &quot;POSTAL_SHIPTO&quot;: &quot;44251-5001&quot;, &quot;COUNTRY_SHIPTO&quot;: &quot;USA&quot;, &quot;PRICE_PO&quot;: 14.99, &quot;FREIGHT_TERMS&quot;: &quot;FOBDEST&quot;, &quot;QTY_PO&quot;: 1, &quot;SHIP_TYPE_ID&quot;: &quot;BEST_WAY&quot;, &quot;CANCEL_STATUS&quot;: &quot;A&quot;, &quot;ATTN_TO&quot;: &quot;&quot;, &quot;STD_ID_NUM_SHIPTO&quot;: &quot;&quot; }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;AUDIT_ACTN&quot;: &quot;A&quot; } }, &quot;PSCAMA&quot;: { &quot;LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;AUDIT_ACTN&quot;: &quot;A&quot;, &quot;BASE_LANGUAGE_CD&quot;: &quot;ENG&quot;, &quot;MSG_SEQ_FLG&quot;: &quot;&quot;, &quot;PROCESS_INSTANCE&quot;: 1199010, &quot;PUBLISH_RULE_ID&quot;: &quot;WG_MAIN_RULE&quot;, &quot;MSGNODENAME&quot;: &quot;&quot; } } } } } </code></pre> <p>JOLT Spec-</p> <pre><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;#UPSERT&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityHeader.action&quot;, &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;PO_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId&quot;, &quot;#APPROVED&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.status&quot;, &quot;PO_AMT_TTL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.grossTotalAmount&quot;, &quot;FREIGHT_TERMS&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode&quot;, &quot;WG_REQUESTOR_EMAIL&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userEmailId&quot;, &quot;WG_DELIVER_TO&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.deliverToUser.userEmailId&quot;, &quot;*&quot;: { &quot;WG_REQ_ID&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription&quot;, &quot;#STANDARD&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType&quot;, &quot;*&quot;: { &quot;WG_SHIP_ADDR_TYPE&quot;:&quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddressType&quot;, &quot;WG_SHIP_ADDR_TYPE&quot;: { &quot;2&quot;: { &quot;@(2,DESCR_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressName&quot;, &quot;@(2,ADDRESS1_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine1&quot;, &quot;@(2,ADDRESS2_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine2&quot;, &quot;@(2,ADDRESS3_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine3&quot;, &quot;@(2,ADDRESS4_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine4&quot;, &quot;@(2,CITY_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.city&quot;, &quot;@(2,POSTAL_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.zip&quot;, &quot;@(2,STATE_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.state&quot;, &quot;@(2,COUNTRY_SHIPTO)&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.country&quot; } }, &quot;WG_CUST_ADDR_CODE&quot;:&quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressCode&quot;, &quot;FREIGHT_TERMS&quot;: &quot;integration-inbound:IntegrationDetails.integrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode&quot; } } } } } } } }, { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;integrationEntityHeader&quot;: &quot;&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;integrationEntityDetails&quot;: { &quot;*&quot;: { &quot;externalId&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;status&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poHeader&quot;: { &quot;poDescription&quot;: &quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;poType&quot;: &quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;grossTotalAmount&quot;: &quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;deliveryTermCode&quot;: &quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;shipToAddressType&quot;:&quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot;, &quot;shipToAddress&quot;:&quot;&amp;6.&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot; }, &quot;items&quot;: &quot;&amp;5.&amp;4.&amp;3.&amp;2.&amp;1.&amp;&quot; } } } } } } }, { &quot;operation&quot;: &quot;cardinality&quot;, &quot;spec&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;*&quot;: { &quot;status&quot;: &quot;ONE&quot;, &quot;poHeader&quot;: { &quot;*&quot;: &quot;ONE&quot; } } } } } } } } ] </code></pre> <p>Output-</p> <pre><code>{ &quot;integration-inbound:IntegrationDetails&quot;: { &quot;integrationEntities&quot;: { &quot;integrationEntity&quot;: { &quot;integrationEntityHeader&quot;: { &quot;action&quot;: &quot;UPSERT&quot; }, &quot;integrationEntityDetails&quot;: { &quot;poDetails&quot;: { &quot;externalId&quot;: 25052, &quot;status&quot;: &quot;APPROVED&quot;, &quot;poHeader&quot;: { &quot;poDescription&quot;: 25694, &quot;poType&quot;: &quot;STANDARD&quot;, &quot;grossTotalAmount&quot;: 14.99, &quot;deliveryTermCode&quot;: &quot;FOBDEST&quot;, &quot;shipToAddress&quot;: { &quot;addressCode&quot;: &quot;OFIC&quot; } }, &quot;items&quot;: { &quot;item&quot;: { &quot;requesterDetails&quot;: { &quot;userEmailId&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot; }, &quot;deliverToUser&quot;: { &quot;userEmailId&quot;: &quot;ZacharyEngels@westfieldgrp.com&quot; } } } } } } } } } </code></pre>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20530341/" ]
74,584,078
<p>Having the following problem. I'm reading the data from stdin and save it in list that I convert to tuple the following way:</p> <pre><code>x = int(input()) f = [] for i in range(x): a, b = map(int, input().split()) f.append([a,b]) def to_tuple(lst): return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst) </code></pre> <p>After this I receive two tuples of tuples looking something like that:</p> <pre><code>f = ((0, 1), (1, 2), (0, 2), (0, 3)) s = (((0,), (1, 2, 3)), ((0, 1), (2, 3)), ((0, 1, 2), (3,))) </code></pre> <p>What I'm trying to do is to find the number of intersections between all inner tuples of <code>f</code> and each tuple of <code>s</code>. In my case &quot;intersection&quot; should be considered as an &quot;edges&quot; between tuples (so in <code>f</code> we have all possible &quot;edges&quot; and checking if there will be an edge between inner tuples in particular tuple of <code>s</code>). So for the example it should print <code>[3,3,1]</code>.</p> <p>Basically, I know how to do in the simple case of intersection - so one can just use <code>set()</code> and then apply <code>a.intersection(b)</code> But how should I proceed in my case?</p> <p>Many thanks and sorry if the question was already asked before :=)</p>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3079439/" ]
74,584,083
<p>can someone teach me on how to auto fill an select box based on the selection from the other select box?</p> <p>this is my first selection wherein the user will select in Orderlist Code.</p> <pre><code> &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;gross_amount&quot; class=&quot;col-sm-2 control-label&quot; style=&quot;text-align:left;&quot;&gt;OL Code&lt;/label&gt; &lt;div class=&quot;col-sm-6&quot;&gt; &lt;select class=&quot;form-control&quot; id=&quot;table_name&quot; name=&quot;table_name&quot;&gt; &lt;?php foreach ($orderlist_data as $key =&gt; $value): ?&gt; &lt;option value=&quot;&lt;?php echo $value['id'] ?&gt;&quot;&gt;&lt;?php echo $value['ol_code'] ?&gt;&lt;/option&gt; &lt;?php endforeach ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>after the selection base on the Order list code i hope to auto fill this selection base on the selection in the orderlist code.</p> <p>create.php</p> <pre><code>&lt;select class=&quot;form-control select_group product&quot; data-row-id=&quot;row_1&quot; id=&quot;product_1&quot; name=&quot;product[]&quot; style=&quot;width:100%;&quot; onchange=&quot;getProductData(1)&quot; required&gt; &lt;option value='maincat' selected&gt;--Select Products--&lt;/option&gt; &lt;?php foreach ($products as $k =&gt; $v): ?&gt; &lt;option value=&quot;&lt;?php echo $v['id'] ?&gt;&quot;&gt;&lt;?php echo $v['name'] ?&gt;&lt;/option&gt; &lt;?php endforeach ?&gt; &lt;/select&gt; </code></pre> <p>edit.php</p> <pre><code>&lt;select class=&quot;form-control select_group product&quot; data-row-id=&quot;row_&lt;?php echo $x; ?&gt;&quot; id=&quot;product_&lt;?php echo $x; ?&gt;&quot; name=&quot;product[]&quot; style=&quot;width:100%;&quot; onchange=&quot;getProductData(&lt;?php echo $x; ?&gt;)&quot; required&gt; &lt;option value=&quot;&quot;&gt;&lt;/option&gt; &lt;?php foreach ($products as $k =&gt; $v): ?&gt; &lt;option value=&quot;&lt;?php echo $v['id'] ?&gt;&quot; &lt;?php if($val['product_id'] == $v['id']) { echo &quot;selected='selected'&quot;; } ?&gt;&gt;&lt;?php echo $v['name'] ?&gt;&lt;/option&gt; &lt;?php endforeach ?&gt; &lt;/select&gt; </code></pre> <p>here is an photo on the orderlist module <a href="https://i.stack.imgur.com/6YkYn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6YkYn.png" alt="enter image description here" /></a></p> <p>then i hope someone can teach me how to auto-fill the product selection based in the orderlist selection <a href="https://i.stack.imgur.com/pSBpJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pSBpJ.png" alt="enter image description here" /></a> if i press the &quot;OLCODE-1E6E&quot; in the orderlist code selection i want to automate my product selection and display the 2 items i set in the orderlist but does not have knowledge from it i hope someone can teach.</p> <pre><code> function getProd(row_id) { var orderlist_id = $(&quot;#olcode_&quot;+row_id).val(); if(orderlist_id == &quot;&quot;) { //i don't know the correct way } else { $.ajax({ url: base_url + 'orderlist/getOrderListById', type: 'post', data: {orderlist_id : orderlist_id}, dataType: 'json', success:function(response) { //i don't know the correct way } }); } } </code></pre>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14393948/" ]
74,584,137
<p>I got a dataframe with a date/time in seconds, which I changed by:</p> <pre><code>df[&quot;start&quot;] = pd.to_datetime(df[&quot;start&quot;], unit='s') df[&quot;time&quot;] = df[&quot;start&quot;].dt.time </code></pre> <p>Now I would like to add a column df[&quot;timeofday&quot;], which include the time of day string.</p> <blockquote> <p>0:00 - 5:59 night</p> </blockquote> <blockquote> <p>6:00 - 11:59 morning</p> </blockquote> <blockquote> <p>12:00 - 17:59 afternoon</p> </blockquote> <blockquote> <p>18:00 - 21:59 evening</p> </blockquote> <blockquote> <p>22:00 - 23:59 night</p> </blockquote> <p>I assume that I need to use a for loop with between_time() on df.time. However, this does not work because I seem to need to use the column time as the index column of the dataframe. However, the dataframe has an index that I don't want to lose. Even if I could add a second index and then filter on each time period, it would not be clear to me how to insert the respective string into the new column timeofday.</p> <p>I tried to filter like</p> <pre><code>df.time.between_time('02:00', '03:30') </code></pre> <p>Which leads to</p> <blockquote> <p>TypeError: Index must be DatetimeIndex</p> </blockquote> <p>So I assumed I need to set the time column as new index</p> <pre><code>df.set_index(&quot;time&quot;, inplace=True) df[&quot;timeofday&quot;] = 'night' df[&quot;timeofday&quot;][df.time.between_time('06:00', '11:59')] = &quot;morning&quot; </code></pre> <p>which leads to the same</p> <blockquote> <p>TypeError: Index must be DatetimeIndex</p> </blockquote> <p>After that I tried</p> <pre><code>df.set_index(&quot;start&quot;, inplace=True) df[&quot;timeofday&quot;] = 'night' df[&quot;timeofday&quot;][df.between_time('06:00', '11:59')] = &quot;morning&quot; </code></pre> <p>Leads to</p> <blockquote> <p>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame InvalidIndexError</p> </blockquote>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15215291/" ]
74,584,181
<p>i have problem with onClick function on element in React.</p> <pre><code> const [selectedGenre, updateSelectedGenre] = React.useState(&quot;s&quot;); function update(genre) { updateSelectedGenre(genre); console.log(selectedGenre); } const Genres = (genreIds) =&gt; { return genreIds.map((genreId, index) =&gt; ( &lt;span style={{ cursor: &quot;pointer&quot;, }} onClick={() =&gt; { update(genreId); }} &gt; {genreId}{&quot; &quot;} &lt;/span&gt; )); }; </code></pre> <p>When i click on span first time, console log of <code>selectedGenre</code> is &quot;s&quot;,which is default. WHen i click second time, its updated. Why is it like that ? my <code>updateSelectedGenre</code> is before console.log. Thank you very much.</p>
[ { "answer_id": 74584148, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 3, "selected": true, "text": "await const img = await createImageBitmap(canvas);\nctx.drawImage(img, 0, 0);\n await createImageBitmap(canvas).then(img => {\n ctx.drawImage(img, 0, 0);\n});\n" }, { "answer_id": 74588584, "author": "Kaiido", "author_id": 3702797, "author_profile": "https://Stackoverflow.com/users/3702797", "pm_score": 1, "selected": false, "text": "HTMLCanvasElement CanvasImageSource drawImage() const [canvas1, canvas2] = document.querySelectorAll(\"canvas\");\nconst ctx1 = canvas1.getContext(\"2d\");\nconst ctx2 = canvas2.getContext(\"2d\");\n\nctx1.fillStyle = \"green\"\nctx1.fillRect(0, 0, 50, 50);\n\nctx2.fillStyle = \"red\"\nctx2.fillRect(0, 0, 50, 50);\n// draw canvas1 at (60, 0), with a 2x scale\nctx2.drawImage(canvas1, 60, 0, 600, 300); canvas { border: 1px solid } <canvas></canvas>\n<canvas></canvas>" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7744142/" ]
74,584,190
<p>This is one of those questions where there are so many answers, and yet none do the specific thing.</p> <p>I tried to look at all of these posts — <a href="https://stackoverflow.com/questions/54244461/dynamically-allocating-memory-for-2d-char-array">1</a> <a href="https://stackoverflow.com/questions/17389009/a-different-way-to-malloc-a-2d-array">2</a> <a href="https://stackoverflow.com/questions/36794202/freaky-way-of-allocating-two-dimensional-array">3</a> <a href="https://stackoverflow.com/questions/23534293/how-to-malloc-2d-arrays">4</a> <a href="https://stackoverflow.com/questions/2842135/c-programming-malloc-for-a-2d-array-using-pointer-to-pointer">5</a> <a href="https://stackoverflow.com/questions/20807493/multi-dimensional-2d-array-dynamically-using-malloc">6</a> <a href="https://stackoverflow.com/questions/74388772/allocate-2d-array-with-only-one-malloc-in-c">7</a> <a href="https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays">8</a> <a href="https://stackoverflow.com/questions/1970698/using-malloc-for-allocation-of-multi-dimensional-arrays-with-different-row-lengt">9</a> — and every time the solution would be either using VLAs, using normal arrays with fixed dimensions, or using pointer to pointer.</p> <p>What I want is to allocate:</p> <ul> <li>dynamically (using a variable set at runtime)</li> <li>rectangular (&quot;2d array&quot;) (I don't need a jagged one. And I guess it would be impossible to do it anyway.)</li> <li>contiguous memory (in #8 and some other posts, people say that pointer to pointer is bad because of heap stuff and fragmentation)</li> <li>no VLAs (I heard they are the devil and to always avoid them and not to talk to people who suggest using them in any scenario).</li> </ul> <p>So please, if there is a post I skipped, or didn't read thoroughly enough, that fulfils these requirements, point me to it.<br /> Otherwise, I would ask of you to educate me about this and tell me if this is possible, and if so, how to do it.</p>
[ { "answer_id": 74584274, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 1, "selected": false, "text": "W H int H W int * a = malloc(W * H * sizeof(int));\n int val = a[j * W + i];\na[j * W + i] = val;\n W" }, { "answer_id": 74584437, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 3, "selected": false, "text": "int (*arr)[cols] = malloc( rows * sizeof (int [cols]) );\n arr[i][j] cols" }, { "answer_id": 74584594, "author": "user3121023", "author_id": 3121023, "author_profile": "https://Stackoverflow.com/users/3121023", "pm_score": 3, "selected": true, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint **contiguous ( int rows, int cols, int **memory, int **pointers) {\n int *temp = NULL;\n int **ptrtemp = NULL;\n // allocate a large block of memory\n if ( NULL == ( temp = realloc ( *memory, sizeof **memory * rows * cols))) {\n fprintf ( stderr, \"problem memory malloc\\n\");\n return pointers;\n }\n\n *memory = temp;\n // allocate pointers\n if ( NULL == ( ptrtemp = realloc ( pointers, sizeof *pointers * rows))) {\n fprintf ( stderr, \"problem memory malloc\\n\");\n return pointers;\n }\n\n pointers = ptrtemp;\n\n for ( int rw = 0; rw < rows; ++rw) {\n pointers[rw] = &(*memory)[rw * cols]; // assign addresses to pointers\n }\n\n // assign some values\n for ( int rw = 0; rw < rows; ++rw) {\n for ( int cl = 0; cl < cols; ++cl) {\n pointers[rw][cl] = rw * cols + cl;\n }\n }\n return pointers;\n}\n\nint main ( void) {\n int *memory = NULL;\n int **ptrs = NULL;\n int rows = 20;\n int cols = 17;\n\n if ( ( ptrs = contiguous ( rows, cols, &memory, ptrs))) {\n for ( int rw = 0; rw < rows; ++rw) {\n for ( int cl = 0; cl < cols; ++cl) {\n printf ( \"%3d \", ptrs[rw][cl]);\n }\n printf ( \"\\n\");\n }\n\n free ( memory);\n free ( ptrs);\n }\n return 0;\n}\n" }, { "answer_id": 74584962, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 2, "selected": false, "text": "void do_something(size_t rows, size_t columns) {\n int (*my_array)[columns]; // pointer to VLA\n\n my_array = malloc(rows * sizeof(*my_array));\n\n // ... access elements as my_array[row][col] ...\n}\n #define ELEMENT_2D(a, dim2, row, col) ((a)[(row) * (dim2) + (col)])\n\nvoid do_something(size_t rows, size_t columns) {\n int *my_array;\n\n my_array = malloc(rows * columns * sizeof(*my_array));\n\n // ... access elements as ELEMENT_2D(my_array, columns, row, col) ..\n}\n" }, { "answer_id": 74592941, "author": "iloveclang", "author_id": 20314114, "author_profile": "https://Stackoverflow.com/users/20314114", "pm_score": 1, "selected": false, "text": "a[x * COLS + y] #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define ROWS 100\n#define COLS 100\n#define LOOPS 100\n#define NORMAL 0\n#define SINGLE 1\n#define HYBRID 2\n\nint **x_normal; /* global vars to make it more equal */\nint *y_single;\nint *z_hybrid_memory;\nint **z_hybrid_pointers;\nint copy_array[ROWS][COLS];\n\nvoid x_normal_write(int magic) { /* magic number to prevent compiler from optimizing it */\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n x_normal[i][ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid y_single_write(int magic) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n y_single[i * COLS + ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid z_hybrid_write(int magic) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n z_hybrid_pointers[i][ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid x_normal_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = x_normal[i][ii];\n }\n }\n}\n\nvoid y_single_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = y_single[i * COLS + ii];\n }\n }\n}\n\nvoid z_hybrid_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = z_hybrid_pointers[i][ii];\n }\n }\n}\n\nint main() {\n int i;\n clock_t start, end;\n double times_read[3][LOOPS];\n double times_write[3][LOOPS];\n\n /* MALLOC X_NORMAL 1/2 */\n x_normal = malloc(ROWS * sizeof(int*)); /* rows */\n for (i = 0; i < ROWS; i+=2) { /* malloc every other row to ensure memory isn't contignuous */\n x_normal[i] = malloc(COLS * sizeof(int)); /* columns for each row (1/2) */\n }\n \n /* MALLOC Y_SINGLE */\n y_single = malloc(ROWS * COLS * sizeof(int)); /* all in one contignuous memory */\n\n /* MALLOC Z_HYBRID */\n z_hybrid_memory = malloc(ROWS * COLS * sizeof(int)); /* memory part - with a big chunk of contignuous memory */\n z_hybrid_pointers = malloc(ROWS * sizeof(int*)); /* pointer part - like in normal */\n for (i = 0; i < ROWS; i++) { /* assign addresses to pointers from \"memory\", spaced out by COLS */\n z_hybrid_pointers[i] = &z_hybrid_memory[(i * COLS)]; \n }\n\n /* MALLOC X_NORMAL 2/2 */\n for (i = 1; i < ROWS; i+=2) { /* malloc every other row to ensure memory isn't contignuous */\n x_normal[i] = malloc(COLS * sizeof(int)); /* columns for each row (2/2) */\n }\n\n /* TEST */\n for (i = 0; i < LOOPS; i++) {\n /* NORMAL WRITE */\n start = clock();\n x_normal_write(i);\n end = clock();\n times_write[NORMAL][i] = (double)(end - start);\n\n /* SINGLE WRITE */\n start = clock();\n y_single_write(i);\n end = clock();\n times_write[SINGLE][i] = (double)(end - start);\n\n /* HYBRID WRITE */\n start = clock();\n z_hybrid_write(i);\n end = clock();\n times_write[HYBRID][i] = (double)(end - start);\n\n /* NORMAL READ */\n start = clock();\n x_normal_copy();\n end = clock();\n times_read[NORMAL][i] = (double)(end - start);\n\n /* SINGLE READ */\n start = clock();\n y_single_copy();\n end = clock();\n times_read[SINGLE][i] = (double)(end - start);\n\n /* HYBRID READ */\n start = clock();\n z_hybrid_copy();\n end = clock();\n times_read[HYBRID][i] = (double)(end - start);\n }\n\n /* REPORT FINDINGS */\n printf(\"CLOCKS NEEDED FOR:\\n\\nREAD\\tNORMAL\\tSINGLE\\tHYBRID\\tWRITE\\tNORMAL\\tSINGLE\\tHYBRID\\n\\n\");\n for (i = 0; i < LOOPS; i++) {\n printf(\n \"\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\", \n times_read[NORMAL][i], times_read[SINGLE][i], times_read[HYBRID][i],\n times_write[NORMAL][i], times_write[SINGLE][i], times_write[HYBRID][i]\n );\n /* USE [0] to get totals */\n times_read[NORMAL][0] += times_read[NORMAL][i];\n times_read[SINGLE][0] += times_read[SINGLE][i];\n times_read[HYBRID][0] += times_read[HYBRID][i];\n times_write[NORMAL][0] += times_write[NORMAL][i];\n times_write[SINGLE][0] += times_write[SINGLE][i];\n times_write[HYBRID][0] += times_write[HYBRID][i];\n }\n printf(\"TOTAL:\\n\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\",\n times_read[NORMAL][0], times_read[SINGLE][0], times_read[HYBRID][0],\n times_write[NORMAL][0], times_write[SINGLE][0], times_write[HYBRID][0]\n );\n printf(\"AVERAGE:\\n\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\",\n (times_read[NORMAL][0] / LOOPS), (times_read[SINGLE][0] / LOOPS), (times_read[HYBRID][0] / LOOPS),\n (times_write[NORMAL][0] / LOOPS), (times_write[SINGLE][0] / LOOPS), (times_write[HYBRID][0] / LOOPS)\n );\n\n return 0;\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20314114/" ]
74,584,195
<p>I am facing a problem, I can't extract data from just one array - temperature. I tried to put it into another array, but all I managed to do was put there all the data. Any advice? Thank you in advance!</p> <blockquote> <p>Console output of the function I use: { latitude: 51.75, longitude: 19.5, generationtime_ms: 0.28395652770996094, utc_offset_seconds: 0, timezone: 'GMT', timezone_abbreviation: 'GMT', elevation: 218, hourly_units: { time: 'iso8601', temperature_2m: '°C' }, hourly: { time: [ '2022-11-26T00:00', '2022-11-26T01:00', '2022-11-26T02:00', '2022-11-26T03:00', '2022-11-26T04:00', '2022-11-26T05:00', '2022-11-26T06:00', '2022-11-26T07:00', '2022-11-26T08:00', '2022-11-26T09:00', '2022-11-26T10:00', '2022-11-26T11:00', '2022-11-26T12:00', '2022-11-26T13:00', '2022-11-26T14:00', '2022-11-26T15:00', '2022-11-26T16:00', '2022-11-26T17:00', '2022-11-26T18:00', '2022-11-26T19:00', '2022-11-26T20:00', '2022-11-26T21:00', '2022-11-26T22:00', '2022-11-26T23:00', '2022-11-27T00:00', '2022-11-27T01:00', '2022-11-27T02:00', '2022-11-27T03:00', '2022-11-27T04:00', '2022-11-27T05:00', '2022-11-27T06:00', '2022-11-27T07:00', '2022-11-27T08:00', '2022-11-27T09:00', '2022-11-27T10:00', '2022-11-27T11:00', '2022-11-27T12:00', '2022-11-27T13:00', '2022-11-27T14:00', '2022-11-27T15:00', '2022-11-27T16:00', '2022-11-27T17:00', '2022-11-27T18:00', '2022-11-27T19:00', '2022-11-27T20:00', '2022-11-27T21:00', '2022-11-27T22:00', '2022-11-27T23:00', '2022-11-28T00:00', '2022-11-28T01:00', '2022-11-28T02:00', '2022-11-28T03:00', '2022-11-28T04:00', '2022-11-28T05:00', '2022-11-28T06:00', '2022-11-28T07:00', '2022-11-28T08:00', '2022-11-28T09:00', '2022-11-28T10:00', '2022-11-28T11:00', '2022-11-28T12:00', '2022-11-28T13:00', '2022-11-28T14:00', '2022-11-28T15:00', '2022-11-28T16:00', '2022-11-28T17:00', '2022-11-28T18:00', '2022-11-28T19:00', '2022-11-28T20:00', '2022-11-28T21:00', '2022-11-28T22:00', '2022-11-28T23:00', '2022-11-29T00:00', '2022-11-29T01:00', '2022-11-29T02:00', '2022-11-29T03:00', '2022-11-29T04:00', '2022-11-29T05:00', '2022-11-29T06:00', '2022-11-29T07:00', '2022-11-29T08:00', '2022-11-29T09:00', '2022-11-29T10:00', '2022-11-29T11:00', '2022-11-29T12:00', '2022-11-29T13:00', '2022-11-29T14:00', '2022-11-29T15:00', '2022-11-29T16:00', '2022-11-29T17:00', '2022-11-29T18:00', '2022-11-29T19:00', '2022-11-29T20:00', '2022-11-29T21:00', '2022-11-29T22:00', '2022-11-29T23:00', '2022-11-30T00:00', '2022-11-30T01:00', '2022-11-30T02:00', '2022-11-30T03:00', 68 more items ], temperature_2m: [ 2.4, 2.3, 2.1, 1.9, 1.8, 1.7, 1.8, 1.7, 1.9, 2.3, 2.5, 2.6, 2.1, 1.1, 0.7, 0.5, 0.2, 0, 0.1, 0.1, -0.1, -0.1, -0.1, -0.1, -0.2, -0.2, -0, 0.1, 0, -0.1, -0.1, -0.1, 0.2, 1, 1.5, 2, 2.1, 2.1, 2, 1.7, 1.5, 1.3, 1.2, 0.9, 0.9, 0.9, 0.7, 0.6, 0.2, -0.1, -0.1, -0.1, -0.1, -0.2, -0.3, -0.4, -0.3, 0.4, 1.4, 1.8, 1.5, 1.4, 1.4, 0.9, 0.3, -0, -0.1, -0.2, -0.3, -0.3, -0.3, -0.5, -0.8, -0.9, -1, -1.1, -1.3, -0.3, -0.3, -0.4, -0.5, -0.6, -0.8, -0.8, -0.8, -0.8, -0.8, -0.9, -1,</p> </blockquote> <p>As posted above, tried to extract one array from whole data asset</p>
[ { "answer_id": 74584274, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 1, "selected": false, "text": "W H int H W int * a = malloc(W * H * sizeof(int));\n int val = a[j * W + i];\na[j * W + i] = val;\n W" }, { "answer_id": 74584437, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 3, "selected": false, "text": "int (*arr)[cols] = malloc( rows * sizeof (int [cols]) );\n arr[i][j] cols" }, { "answer_id": 74584594, "author": "user3121023", "author_id": 3121023, "author_profile": "https://Stackoverflow.com/users/3121023", "pm_score": 3, "selected": true, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint **contiguous ( int rows, int cols, int **memory, int **pointers) {\n int *temp = NULL;\n int **ptrtemp = NULL;\n // allocate a large block of memory\n if ( NULL == ( temp = realloc ( *memory, sizeof **memory * rows * cols))) {\n fprintf ( stderr, \"problem memory malloc\\n\");\n return pointers;\n }\n\n *memory = temp;\n // allocate pointers\n if ( NULL == ( ptrtemp = realloc ( pointers, sizeof *pointers * rows))) {\n fprintf ( stderr, \"problem memory malloc\\n\");\n return pointers;\n }\n\n pointers = ptrtemp;\n\n for ( int rw = 0; rw < rows; ++rw) {\n pointers[rw] = &(*memory)[rw * cols]; // assign addresses to pointers\n }\n\n // assign some values\n for ( int rw = 0; rw < rows; ++rw) {\n for ( int cl = 0; cl < cols; ++cl) {\n pointers[rw][cl] = rw * cols + cl;\n }\n }\n return pointers;\n}\n\nint main ( void) {\n int *memory = NULL;\n int **ptrs = NULL;\n int rows = 20;\n int cols = 17;\n\n if ( ( ptrs = contiguous ( rows, cols, &memory, ptrs))) {\n for ( int rw = 0; rw < rows; ++rw) {\n for ( int cl = 0; cl < cols; ++cl) {\n printf ( \"%3d \", ptrs[rw][cl]);\n }\n printf ( \"\\n\");\n }\n\n free ( memory);\n free ( ptrs);\n }\n return 0;\n}\n" }, { "answer_id": 74584962, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 2, "selected": false, "text": "void do_something(size_t rows, size_t columns) {\n int (*my_array)[columns]; // pointer to VLA\n\n my_array = malloc(rows * sizeof(*my_array));\n\n // ... access elements as my_array[row][col] ...\n}\n #define ELEMENT_2D(a, dim2, row, col) ((a)[(row) * (dim2) + (col)])\n\nvoid do_something(size_t rows, size_t columns) {\n int *my_array;\n\n my_array = malloc(rows * columns * sizeof(*my_array));\n\n // ... access elements as ELEMENT_2D(my_array, columns, row, col) ..\n}\n" }, { "answer_id": 74592941, "author": "iloveclang", "author_id": 20314114, "author_profile": "https://Stackoverflow.com/users/20314114", "pm_score": 1, "selected": false, "text": "a[x * COLS + y] #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define ROWS 100\n#define COLS 100\n#define LOOPS 100\n#define NORMAL 0\n#define SINGLE 1\n#define HYBRID 2\n\nint **x_normal; /* global vars to make it more equal */\nint *y_single;\nint *z_hybrid_memory;\nint **z_hybrid_pointers;\nint copy_array[ROWS][COLS];\n\nvoid x_normal_write(int magic) { /* magic number to prevent compiler from optimizing it */\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n x_normal[i][ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid y_single_write(int magic) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n y_single[i * COLS + ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid z_hybrid_write(int magic) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n z_hybrid_pointers[i][ii] = (i * COLS + ii + magic);\n }\n }\n}\n\nvoid x_normal_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = x_normal[i][ii];\n }\n }\n}\n\nvoid y_single_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = y_single[i * COLS + ii];\n }\n }\n}\n\nvoid z_hybrid_copy(void) {\n int i, ii;\n for (i = 0; i < ROWS; i++) {\n for (ii = 0; ii < COLS; ii++) {\n copy_array[i][ii] = z_hybrid_pointers[i][ii];\n }\n }\n}\n\nint main() {\n int i;\n clock_t start, end;\n double times_read[3][LOOPS];\n double times_write[3][LOOPS];\n\n /* MALLOC X_NORMAL 1/2 */\n x_normal = malloc(ROWS * sizeof(int*)); /* rows */\n for (i = 0; i < ROWS; i+=2) { /* malloc every other row to ensure memory isn't contignuous */\n x_normal[i] = malloc(COLS * sizeof(int)); /* columns for each row (1/2) */\n }\n \n /* MALLOC Y_SINGLE */\n y_single = malloc(ROWS * COLS * sizeof(int)); /* all in one contignuous memory */\n\n /* MALLOC Z_HYBRID */\n z_hybrid_memory = malloc(ROWS * COLS * sizeof(int)); /* memory part - with a big chunk of contignuous memory */\n z_hybrid_pointers = malloc(ROWS * sizeof(int*)); /* pointer part - like in normal */\n for (i = 0; i < ROWS; i++) { /* assign addresses to pointers from \"memory\", spaced out by COLS */\n z_hybrid_pointers[i] = &z_hybrid_memory[(i * COLS)]; \n }\n\n /* MALLOC X_NORMAL 2/2 */\n for (i = 1; i < ROWS; i+=2) { /* malloc every other row to ensure memory isn't contignuous */\n x_normal[i] = malloc(COLS * sizeof(int)); /* columns for each row (2/2) */\n }\n\n /* TEST */\n for (i = 0; i < LOOPS; i++) {\n /* NORMAL WRITE */\n start = clock();\n x_normal_write(i);\n end = clock();\n times_write[NORMAL][i] = (double)(end - start);\n\n /* SINGLE WRITE */\n start = clock();\n y_single_write(i);\n end = clock();\n times_write[SINGLE][i] = (double)(end - start);\n\n /* HYBRID WRITE */\n start = clock();\n z_hybrid_write(i);\n end = clock();\n times_write[HYBRID][i] = (double)(end - start);\n\n /* NORMAL READ */\n start = clock();\n x_normal_copy();\n end = clock();\n times_read[NORMAL][i] = (double)(end - start);\n\n /* SINGLE READ */\n start = clock();\n y_single_copy();\n end = clock();\n times_read[SINGLE][i] = (double)(end - start);\n\n /* HYBRID READ */\n start = clock();\n z_hybrid_copy();\n end = clock();\n times_read[HYBRID][i] = (double)(end - start);\n }\n\n /* REPORT FINDINGS */\n printf(\"CLOCKS NEEDED FOR:\\n\\nREAD\\tNORMAL\\tSINGLE\\tHYBRID\\tWRITE\\tNORMAL\\tSINGLE\\tHYBRID\\n\\n\");\n for (i = 0; i < LOOPS; i++) {\n printf(\n \"\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\", \n times_read[NORMAL][i], times_read[SINGLE][i], times_read[HYBRID][i],\n times_write[NORMAL][i], times_write[SINGLE][i], times_write[HYBRID][i]\n );\n /* USE [0] to get totals */\n times_read[NORMAL][0] += times_read[NORMAL][i];\n times_read[SINGLE][0] += times_read[SINGLE][i];\n times_read[HYBRID][0] += times_read[HYBRID][i];\n times_write[NORMAL][0] += times_write[NORMAL][i];\n times_write[SINGLE][0] += times_write[SINGLE][i];\n times_write[HYBRID][0] += times_write[HYBRID][i];\n }\n printf(\"TOTAL:\\n\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\",\n times_read[NORMAL][0], times_read[SINGLE][0], times_read[HYBRID][0],\n times_write[NORMAL][0], times_write[SINGLE][0], times_write[HYBRID][0]\n );\n printf(\"AVERAGE:\\n\\t%.1f\\t%.1f\\t%.1f\\t\\t%.1f\\t%.1f\\t%.1f\\n\",\n (times_read[NORMAL][0] / LOOPS), (times_read[SINGLE][0] / LOOPS), (times_read[HYBRID][0] / LOOPS),\n (times_write[NORMAL][0] / LOOPS), (times_write[SINGLE][0] / LOOPS), (times_write[HYBRID][0] / LOOPS)\n );\n\n return 0;\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20608333/" ]
74,584,304
<p>As per the Headless service definition:</p> <blockquote> <p>Kubernetes allows clients to discover pod IPs through DNS lookups. Usually, when you perform a DNS lookup for a service, the DNS server returns a single IP which is the service’s cluster IP. But if you don’t need the cluster IP for your service, you can set ClusterIP to None , then the DNS server will return the individual pod IPs instead of the service IP.Then client can connect to any of them</p> </blockquote> <p>Looks like its similar to creating a clusterIP with one backend pod. If so why should we use clusterIP with one backend pod?</p>
[ { "answer_id": 74590161, "author": "David Maze", "author_id": 10008173, "author_profile": "https://Stackoverflow.com/users/10008173", "pm_score": 1, "selected": false, "text": "deployment-name-12345678-abcde replicas:" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425757/" ]
74,584,324
<p>i have this table that has some data, but i want to get the row where a paticular coluom <code>votecount</code> has the highest value:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>votecount</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> </tr> <tr> <td>2</td> <td>1</td> </tr> <tr> <td>3</td> <td>1</td> </tr> <tr> <td>4</td> <td>13</td> </tr> </tbody> </table> </div> <p>i tried this sql statement:</p> <pre><code>$selectr = &quot;SELECT *, MAX(`votecount`) from `audio`&quot;; $stmt = $conn-&gt;prepare($selectr); $stmt-&gt;execute([]); while($row = $stmt-&gt;fetch()) { $userid = $row[&quot;id&quot;]; $votecount = $row[&quot;votecount&quot;]; echo $userid; echo $votecount; } </code></pre> <p>but it echos out 10 which means it got the first item in the table and the value is 0, which is wrong, its not getting the highest column</p> <p>so how do i fix this</p>
[ { "answer_id": 74584384, "author": "Roby Raju Oommen", "author_id": 14399782, "author_profile": "https://Stackoverflow.com/users/14399782", "pm_score": 1, "selected": true, "text": "$selectr = \"SELECT * from `audio` where `votecount` = ( SELECT MAX(`votecount`) from `audio`)\"; \n$stmt = $conn->prepare($selectr);\n$stmt->execute([]);\nwhile($row = $stmt->fetch())\n{\n $userid = $row[\"id\"];\n $votecount = $row[\"votecount\"];\n echo $userid;\n echo $votecount;\n}\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19138572/" ]
74,584,329
<p>I want to create a random <code>Matrix</code> with values of zeros and ones. With this presumption, there will be more zeros instead of ones! So I guess there should be something like a weighted Bernoulli distribution to choose between 0 or 1 each time (and more probability for choosing 0). I prefer not to limit it to just nxn matrices! I can try in an utterly not standard way like this:</p> <pre><code>julia&gt; let mat = Matrix{Int64}(undef, 3, 5) zero_or_one(shift) = rand()+shift&gt;0.5 ? 0 : 1 foreach(x-&gt;mat[x]=zero_or_one(0.3), eachindex(mat)) end julia&gt; mat 3×5 Matrix{Int64}: 1 1 1 0 1 0 1 1 1 1 0 1 1 0 1 </code></pre> <p>Note that this doesn't do the job. Because as you can see, I get more ones instead of zeros in the result. Is there any more optimal or at least creative way? Or any module to do it?</p> <p>Update:<br /> It seems the result of this code will never change whether I change the value of <code>shift</code> or not .</p>
[ { "answer_id": 74584464, "author": "Alexander L. Hayes", "author_id": 12439119, "author_profile": "https://Stackoverflow.com/users/12439119", "pm_score": 3, "selected": false, "text": "p = 0.5 julia> using Distributions\n\njulia> rand(Binomial(), 3, 5)\n3×5 Matrix{Int64}:\n 1 1 1 1 1\n 1 0 1 0 0\n 0 0 0 1 1\n p 1 0 Binomial(1, 0.1) julia> rand(Binomial(1, 0.1), 3, 5)\n3×5 Matrix{Int64}:\n 0 0 1 0 0\n 0 0 0 0 0\n 0 0 0 1 1\n Distributions.Binomial" }, { "answer_id": 74584480, "author": "tamasgal", "author_id": 531222, "author_profile": "https://Stackoverflow.com/users/531222", "pm_score": 3, "selected": false, "text": "BitMatrix julia> onesandzeros(shape...; threshold=0.5) = rand(shape...) .< threshold\nonesandzeros (generic function with 1 method)\n\njulia> onesandzeros(5, 8; threshold=0.2)\n5×8 BitMatrix:\n 0 0 0 0 0 0 1 1\n 0 0 0 0 1 1 1 0\n 0 1 1 0 0 0 0 0\n 0 0 0 0 1 0 1 0\n 0 0 0 0 0 0 0 0\n" }, { "answer_id": 74584610, "author": "AboAmmar", "author_id": 3943170, "author_profile": "https://Stackoverflow.com/users/3943170", "pm_score": 3, "selected": false, "text": "p 1 p 0 1-p using Distributions\n\nmat = rand(Bernoulli(0.1), 3, 4)\n3×4 Matrix{Bool}:\n 1 0 0 0\n 0 0 0 0\n 0 0 0 0\n rand()+shift>0.5 ? 0 : 1 zero_or_one(0.3) 0.2 0.8" }, { "answer_id": 74585101, "author": "Shayan", "author_id": 11747148, "author_profile": "https://Stackoverflow.com/users/11747148", "pm_score": 1, "selected": false, "text": "let mat julia> let mat = Matrix{Int64}(undef, 3, 5)\n zero_or_one(shift) = rand()+shift>0.5 ? 0 : 1\n foreach(x->mat[x]=zero_or_one(0.3), eachindex(mat))\n return mat\n end\n3×5 Matrix{Int64}:\n 0 0 0 0 1\n 0 0 0 0 0\n 1 0 0 1 0\n begin julia> begin mat = Matrix{Int64}(undef, 3, 5)\n zero_or_one(shift) = rand()+shift>0.5 ? 0 : 1\n foreach(x->mat[x]=zero_or_one(0.3), eachindex(mat))\n end\n\njulia> mat\n3×5 Matrix{Int64}:\n 0 1 0 0 1\n 0 0 0 0 0\n 1 0 0 1 0\n" }, { "answer_id": 74586501, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 4, "selected": true, "text": "using SparseArrays julia> sprand(Bool, 1_000_000,1_000_000, 1e-9)\n1000000×1000000 SparseMatrixCSC{Bool, Int64} with 969 stored entries:\n⠀⠀⠁⠀⠢⠀⠂⠆⡄⠀⠀⠀⡈⠀⠐⠀⠁⠐⠂⠀⠀⢀⠤⠀⠀⠀⠄⠐⢀⠘⠈⠀⢂⠐⠀⠀⠆⠀⠠⠀⠀⠀⠀⢀⠈⠁⠀⠑⠀⢀⠐⠀\n⠄⠀⡀⠀⠒⠠⠨⢀⣀⠀⠀⠀⠐⠤⠈⠀⠀⠀⠀⠀⠁⠁⠄⠐⠑⠅⢄⠠⠐⠀⠀⠀⠁⢀⠋⠂⠂⠂⠀⠀⠀⠀⠀⠀⠈⠄⠀⠀⠀⠄⠈⠀\n⠠⠄⠀⢀⠀⢁⠐⠀⠁⠂⢂⠂⠀⠀⠠⠀⠀⠀⠁⠀⠈⠀⠀⠂⠀⠀⢀⠂⠀⠈⠀⠀⠀⠠⠀⠂⠄⠀⠄⠀⢀⠀⠀⠉⠀⠠⠤⠀⠒⡐⠀⠂\n⢀⠂⠁⠀⠐⠀⠀⠀⠄⠀⢀⡘⠁⠂⠁⠀⠂⢀⠂⠅⡀⠀⠈⠡⠈⠉⢀⠩⠉⠄⡀⠀⠀⠐⠀⡀⡄⠈⠀⢀⠀⠂⠌⠀⠀⠂⠀⠀⠁⠀⠀⠀\n⠂⠠⠀⡀⠀⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⠐⠀⠀⠂⡁⠁⠉⠈⠀⠀⠁⠀⠄⢀⠤⠀⠀⠁⡂⠠⠀⠄⠀⠀⡀⠀⢀⠥⠀⢉⠀⠀⠄⠁⠀\n⠈⠀⠀⠀⠀⠅⠀⠀⠈⠀⠄⡄⠀⠀⠀⠠⠄⠈⠠⠀⠀⠐⠂⠀⠀⠀⠀⠆⠠⠀⠀⠀⠐⠀⠐⠀⠀⠀⠀⠀⠀⡀⠌⢠⠀⠀⠂⠐⠈⠀⠀⠐\n⠀⡀⠁⠈⡀⠀⢀⠁⠈⠠⡈⠁⢄⠈⠀⠀⠀⢁⠐⣀⠂⠄⠄⢀⠠⠀⠐⠀⠡⠠⠄⠈⢄⢈⠂⠈⠆⠀⠁⠀⠀⠀⠃⠀⠀⠠⠀⠐⠀⠐⠘⡀\n⠀⠂⠁⠰⠁⠀⠀⠀⠀⠄⠀⣐⠀⡄⠤⡀⠀⠄⠀⠐⠀⠉⠁⠀⠈⢀⣐⠠⠀⠀⠂⠀⠀⠀⠠⠂⠐⠁⠀⠀⠀⠐⡈⠀⠐⡀⠠⡁⡀⠠⡀⠈\n⠈⠀⠀⠠⠀⠀⠀⠁⠠⠐⠀⠐⠄⡀⠠⠀⠀⠀⠐⡀⠀⠀⠄⠀⠀⢒⠈⠊⠀⢢⡠⠀⠀⠀⡈⠀⠀⠀⠀⠈⠉⠃⠀⡀⡉⠀⢁⠔⠀⠀⠂⠀\n⠀⠀⠀⡐⠠⢀⠀⡐⠀⠈⢀⠀⠀⠀⠐⠪⠀⠂⡄⠐⠀⢀⠀⠈⠀⠀⠰⠀⠀⠀⠈⠀⠀⠠⠀⠀⠐⠀⠀⠠⠀⠀⡀⠄⠈⢂⠂⠌⠀⠀⠐⠀\n⢀⠜⢈⠀⠤⠂⢄⠀⠘⠀⠀⠀⠈⠀⠀⢀⠄⠀⠠⠀⠠⠀⠀⠀⠁⠐⠁⠀⠀⠈⠁⠀⠀⢀⠀⢄⠀⠄⠀⠀⠀⠀⠀⡀⢄⠀⠅⠀⠀⠀⠀⠀\n⠠⠦⠀⡐⠈⠐⠀⡄⠀⠄⠀⠀⠀⠀⡐⠀⠀⠌⠀⠨⠀⠀⠩⢀⠁⠀⠈⠐⠐⠀⠀⠀⠀⡐⠈⠀⠁⠘⠀⢀⠀⠀⠈⠀⠈⠀⠀⠐⠀⠐⠀⠈\n⠀⠀⠀⢄⠤⠀⡀⠀⠀⠬⠀⠀⠂⡡⠀⠌⠠⠠⠀⠀⢀⢔⠀⠀⠀⠀⢀⠄⠀⡈⠀⠀⠈⠄⡀⠐⠀⠠⠀⠀⠠⠂⠠⠑⠀⠀⡄⢀⠁⠀⠀⢁\n⠀⡀⠀⠀⠄⠀⠀⡀⠀⠀⠀⠄⠀⠂⠀⠁⠀⠀⠁⡠⠀⠀⠡⠀⠂⠂⠄⠀⣀⠄⠊⢀⠁⠀⠄⠀⠀⢀⠀⠄⠀⠁⡀⠈⠁⠀⠀⠀⢂⠀⠈⠂\n⠀⠀⠀⢀⠀⠀⠀⠀⠀⠀⠠⡠⢐⠀⠀⠁⠀⠂⠀⠐⠀⠒⠈⡀⡂⢀⠀⠀⠀⠡⠌⠀⠀⢀⠄⠀⢐⠀⠀⢀⠠⠀⠀⠂⠀⠀⠈⠄⠠⡠⠀⡀\n⢀⠲⠀⠀⠈⠀⠀⠂⠀⠀⠀⠀⠀⣀⠨⠁⢀⠀⠀⠀⠀⠀⠰⠀⠀⢠⠀⠁⠀⢀⢀⢀⠀⡡⠀⠈⠁⠀⠁⠠⠀⡀⠀⡀⠀⠐⠀⠐⠁⡀⠂⠈\n⢀⠄⠀⠀⠀⠀⠡⠀⠀⠀⠀⠀⠀⠀⢀⠀⣂⠀⠀⠀⠂⠀⠀⠀⠀⠀⠁⠀⢀⠐⠀⠀⠐⠋⠀⠀⠀⢢⠠⠀⠂⠐⠄⢈⠠⠤⠀⡀⠀⠀⠀⠀\n⠀⠠⠀⠄⢀⠄⠀⠑⠀⠀⠀⠄⠀⡠⠁⡀⢔⠠⢐⠀⢀⠀⠢⠀⠀⠈⠐⠀⠀⠀⠄⠂⠀⠀⠀⠀⠀⠀⡄⠀⡈⠀⠀⠀⡀⠀⠊⡀⠀⢠⠀⠀\n⠀⠀⠒⠀⡀⢐⠄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠁⠄⠀⠀⠀⠀⠀⡄⢀⡀⠀⠀⠀⠀⢀⢀⢀⠁⠁⠀⠁⠔⠀⠀⠀⠂⠀⠒⠀⢀⢈⢀⠀⠀\n⠈⠀⠀⡂⠀⠁⢐⡀⠀⠀⠂⠀⠀⡂⠄⠊⠀⠀⠄⢀⠈⠈⠁⠀⠀⠈⠒⠀⠠⠑⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠄⠆⢄⠀⠀⠂⠂⠀⡀⠀⠀\n⠀⠠⠄⠀⠀⠠⡀⠠⠀⠠⠀⠐⠀⠀⡌⠨⢀⠀⠀⠁⠀⠂⠀⡀⠄⠴⠀⢠⠄⠄⠄⡀⠀⠀⠂⢠⠀⠀⠀⠜⠐⠀⠀⠁⢠⠀⠄⠐⠁⠂⠀⠁\n⠈⠀⠀⠀⠈⠐⠂⠈⠆⢈⠐⡀⠈⢀⠀⠐⠀⠰⠂⠀⠀⠀⠀⠀⠀⠠⠀⡂⠨⠀⠈⡀⠁⠀⠤⠈⠐⠂⠀⠀⡀⠀⠀⠀⠀⠢⠀⠠⠀⠀⠁⠀\n⠠⠈⠀⠈⠠⡀⠀⠠⠀⠠⠀⠀⠐⢄⠜⠀⠈⠀⠄⡁⠀⠠⠀⠀⠀⠁⠀⠡⡀⠈⠐⠀⠂⠀⠀⠀⠀⠐⠐⡈⢀⡠⡂⠀⠀⠐⠀⠄⠀⠀⠀⠁\n⢀⠁⠀⢠⠂⢁⠄⡅⠀⠠⠀⠄⠀⠠⠀⠈⡀⠈⠂⠀⠨⠈⢀⠀⢀⡈⠀⠈⡈⠂⠀⠈⠀⠀⡀⠀⠀⠀⠀⠀⠀⠊⠄⠠⠀⠀⠄⠊⠀⠈⠄⠀\n⠂⠀⠀⠀⠌⠁⢀⠀⠐⠀⠀⠈⠀⠀⠁⠀⢀⠁⠪⠠⠀⠀⢐⠀⠀⠄⠀⠂⢀⡀⢐⠁⠀⣀⠒⠀⢀⢀⠀⠠⢂⠀⠀⠠⠀⠄⠐⠄⠁⠀⠀⠀\n⠐⠀⠠⠀⠀⡀⠀⠄⠄⠐⠀⠁⠀⠀⠀⠀⠄⠄⠀⠀⢀⠂⠀⠰⠀⠀⠊⠀⢀⠀⠤⠀⠀⠀⠉⠀⠀⢀⠀⠁⠁⠀⠈⠁⠀⡠⡀⠐⠐⠀⠀⠀\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11747148/" ]
74,584,372
<p>I am new to C and I am learning how to add a line break. Although it's easy, I haven't been able to figure out how to do it after a variable, taking into account that it's at the end of the line.</p> <p>This is the code with the error, as you can see, I added '\n' after varA and varB</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { char varA = 10; int varB = 150; float varC = 1.25; printf(&quot;The value of varA is: %d&quot;, varA, '\n\'); printf(&quot;The value of varB is: %d&quot;, varB, '\n'); printf(&quot;The value of varC is: %.3f&quot;, varC); return 0; } </code></pre>
[ { "answer_id": 74584392, "author": "Gnought", "author_id": 294577, "author_profile": "https://Stackoverflow.com/users/294577", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main(void)\n{\n char varA = 10;\n int varB = 150;\n float varC = 1.25;\n\n printf(\"The value of varA is: %d\\n\", varA);\n printf(\"The value of varB is: %d\\n\", varB);\n printf(\"The value of varC is: %.3f\\n\", varC);\n return 0;\n}\n" }, { "answer_id": 74584393, "author": "Virat", "author_id": 18246254, "author_profile": "https://Stackoverflow.com/users/18246254", "pm_score": 0, "selected": false, "text": "printf(\"The value of varA is: %d\\n\", varA);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17423323/" ]
74,584,385
<p>I have just a simple message page which consists of From: Text: and a Submit button, then I have another page, which contains nothing, it's my &quot;Message Board&quot; the most recent posted message goes on top of the board, both are aspx pages with master page.</p> <p>I have a SQL DB, I'm already assuming there will be a table with From: Message:(with varchar i think), but what i don't understand how it will get inserted into the messageboard page in a most recent to oldest list fashion.</p> <p>Message.aspx - From: Text: Submit MessageBoard.aspx - just a div , messages submitted will appear here in a drop down list</p> <p>I want it to be super simple no cool features, only &quot;Submit the message&quot; -&gt; &quot;Appears on MessageBoard.aspx to everyone&quot;, and that's it</p>
[ { "answer_id": 74584392, "author": "Gnought", "author_id": 294577, "author_profile": "https://Stackoverflow.com/users/294577", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main(void)\n{\n char varA = 10;\n int varB = 150;\n float varC = 1.25;\n\n printf(\"The value of varA is: %d\\n\", varA);\n printf(\"The value of varB is: %d\\n\", varB);\n printf(\"The value of varC is: %.3f\\n\", varC);\n return 0;\n}\n" }, { "answer_id": 74584393, "author": "Virat", "author_id": 18246254, "author_profile": "https://Stackoverflow.com/users/18246254", "pm_score": 0, "selected": false, "text": "printf(\"The value of varA is: %d\\n\", varA);\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20522538/" ]
74,584,404
<p>Implement the function most_popular_character(my_string), which gets the string argument my_string and returns its most frequent letter. In case of a tie, break it by returning the letter of smaller ASCII value. Note that lowercase and uppercase letters are considered different (e.g., ‘A’ &lt; ‘a’). You may assume my_string consists of English letters only, and is not empty.</p> <p>Example 1: &gt;&gt;&gt; most_popular_character(&quot;HelloWorld&quot;) &gt;&gt;&gt; 'l'</p> <p>Example 2: &gt;&gt;&gt; most_popular_character(&quot;gggcccbb&quot;) &gt;&gt;&gt; 'c'<br /> Explanation: cee and gee appear three times each (and bee twice), but cee precedes gee lexicographically.</p> <p>Hints (you may ignore these):</p> <ul> <li>Build a dictionary mapping letters to their frequency;</li> <li>Find the largest frequency;</li> <li>Find the smallest letter having that frequency.</li> </ul> <pre><code>def most_popular_character(my_string): char_count = {} # define dictionary for c in my_string: if c in char_count: #if c is in the dictionary: char_count[c] = 1 else: # if c isn't in the dictionary - create it and put 1 char_count[c] = 1 sorted_chars = sorted(char_count) # sort the dictionary char_count = char_count.keys() # place the dictionary in a list max_per = 0 for i in range(len(sorted_chars) - 1): if sorted_chars[i] &gt;= sorted_chars[i+1]: max_per = sorted_chars[i] break return max_per </code></pre> <p>my function returns 0 right now, and I think the problem is in the last for loop and if statement - but I can't figure out what the problem is..</p> <p>If you have any suggestions on how to adjust the code it would be very appreciated!</p>
[ { "answer_id": 74584515, "author": "solac34", "author_id": 20554831, "author_profile": "https://Stackoverflow.com/users/20554831", "pm_score": 0, "selected": false, "text": "def most_popular_character(my_string):\n history_l = [l for l in my_string] #each letter in string\n char_dict = {} #creating dict\n for item in history_l: #for each letter in string\n char_dict[item] = history_l.count(item)\n\n return [max(char_dict.values()),min(char_dict.values())]\n" }, { "answer_id": 74584616, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "Counter max >>> from collections import Counter\n>>> def most_popular_character(my_string):\n... chars = Counter(my_string)\n... return max(chars, key=lambda c: (chars[c], -ord(c)))\n...\n>>> most_popular_character(\"HelloWorld\")\n'l'\n>>> most_popular_character(\"gggcccbb\")\n'c'\n max" }, { "answer_id": 74584999, "author": "Rolf of Saxony", "author_id": 4637585, "author_profile": "https://Stackoverflow.com/users/4637585", "pm_score": 2, "selected": true, "text": "add def most_popular_character(my_string):\n # NOTE: you might want to convert the entire sting to upper or lower case, first, depending on the use\n # e.g. my_string = my_string.lower()\n char_count = {} # define dictionary\n for c in my_string:\n if c in char_count: #if c is in the dictionary:\n char_count[c] += 1 # add 1 to it\n else: # if c isn't in the dictionary - create it and put 1\n char_count[c] = 1\n\n # Never under estimate the power of print in debugging\n print(char_count)\n\n # max(char_count.values()) will give the highest value\n # But there may be more than 1 item with the highest count, so get them all\n max_keys = [key for key, value in char_count.items() if value == max(char_count.values())]\n\n # Choose the lowest by sorting them and pick the first item\n low_item = sorted(max_keys)[0]\n\n return low_item, max(char_count.values())\n\nprint(most_popular_character(\"HelloWorld\"))\nprint(most_popular_character(\"gggcccbb\"))\nprint(most_popular_character(\"gggHHHAAAAaaaccccbb 12 3\"))\n {'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}\n('l', 3)\n{'g': 3, 'c': 3, 'b': 2}\n('c', 3)\n{'g': 3, 'H': 3, 'A': 4, 'a': 3, 'c': 4, 'b': 2, ' ': 2, '1': 1, '2': 1, '3': 1}\n('A', 4)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486728/" ]
74,584,415
<p>How to make sure that part of the pattern (keyword in this case) is in the pattern you're looking for, but it can appear in different places. I want to have a match only when it occurs at least once.</p> <p><strong>Regex</strong>:</p> <pre><code> \b(([0-9])(xyz)?([-]([0-9])(xyz)?)?)\b </code></pre> <p>We only want the value if there is a keyword: <code>xyz</code></p> <p><strong>Examples</strong>:</p> <pre><code>1. 1xyz-2xyz - it's OK 2. 1-2xyz - it's OK 3. 1xyz - it's OK 4. 1-2 - there should be no match, at least one xyz missing </code></pre> <p>I tried a positive lookahead and lookbehind but this is not working in this case.</p>
[ { "answer_id": 74584493, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b([0-9])(xyz)?(?:-([0-9])(xyz)?)?\\b(?(2)|(?(4)|(?!)))\n \\b ([0-9]) (xyz)? xyz (?:-([0-9])(xyz)?)? - xyz \\b (?(2)|(?(4)|(?!))) (xyz)? (xyz)? import re\ntext = \"1. 1xyz-2xyz - it's OK\\n2. 1-2xyz - it's OK\\n3. 1xyz - it's OK\\n4. 1-2 - there should be no match\"\npattern = r\"\\b([0-9])(xyz)?(?:-([0-9])(xyz)?)?\\b(?(2)|(?(4)|(?!)))\"\nprint( [x.group() for x in re.finditer(pattern, text)] )\n ['1xyz-2xyz', '1-2xyz', '1xyz']\n" }, { "answer_id": 74584546, "author": "FarrisFahad", "author_id": 1131888, "author_profile": "https://Stackoverflow.com/users/1131888", "pm_score": 1, "selected": false, "text": "\\b(([0-9])?(xyz)+([-]([0-9])+(xyz)+)?)\\b ? +" }, { "answer_id": 74584620, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "\\b\\d(?:xyz|(?=-\\dxyz))(?:-\\d(?:xyz)?)?\\b\n ^ $ xyz xyz" }, { "answer_id": 74587475, "author": "Daniel Cruz", "author_id": 17537072, "author_profile": "https://Stackoverflow.com/users/17537072", "pm_score": 0, "selected": false, "text": "^.*xyz.*$\n xyz .* ^ $ xyz ^.*(?:-?\\d+xyz)+.*$\n" }, { "answer_id": 74590320, "author": "Buttered_Toast", "author_id": 12522652, "author_profile": "https://Stackoverflow.com/users/12522652", "pm_score": 1, "selected": false, "text": "(\\dxyz-\\dxyz|\\dxyz-\\d|\\d-\\dxyz|\\dxyz)\n \\b(\\dxyz-\\dxyz|\\dxyz-\\d|\\d-\\dxyz|\\dxyz)\\b\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19601467/" ]
74,584,424
<p>I have been using typescript for a little while in node.js projects. I understand that for many npm packages there is separate @types package for typescript type definitions.</p> <p>My question is: how can I know that the @types package is up to date with the latest version of the actual package when they are maintained separately?</p> <p>For example there is npm package <a href="https://www.npmjs.com/package/better-sqlite3" rel="nofollow noreferrer">better-sqlite3</a> with no typescript definitions and then a separate type definition package <a href="https://www.npmjs.com/package/@types/better-sqlite3" rel="nofollow noreferrer">@types/better-sqlite3</a>. How user of the package can know that types match the current version of the package?</p> <p>In this answer <a href="https://stackoverflow.com/a/42771216/13277644">here</a> it is said that &quot;TypeScript types for JS packages is best effort and depends on Community interest in the package&quot;. This sounds a bit scary.</p>
[ { "answer_id": 74584493, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 1, "selected": false, "text": "\\b([0-9])(xyz)?(?:-([0-9])(xyz)?)?\\b(?(2)|(?(4)|(?!)))\n \\b ([0-9]) (xyz)? xyz (?:-([0-9])(xyz)?)? - xyz \\b (?(2)|(?(4)|(?!))) (xyz)? (xyz)? import re\ntext = \"1. 1xyz-2xyz - it's OK\\n2. 1-2xyz - it's OK\\n3. 1xyz - it's OK\\n4. 1-2 - there should be no match\"\npattern = r\"\\b([0-9])(xyz)?(?:-([0-9])(xyz)?)?\\b(?(2)|(?(4)|(?!)))\"\nprint( [x.group() for x in re.finditer(pattern, text)] )\n ['1xyz-2xyz', '1-2xyz', '1xyz']\n" }, { "answer_id": 74584546, "author": "FarrisFahad", "author_id": 1131888, "author_profile": "https://Stackoverflow.com/users/1131888", "pm_score": 1, "selected": false, "text": "\\b(([0-9])?(xyz)+([-]([0-9])+(xyz)+)?)\\b ? +" }, { "answer_id": 74584620, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "\\b\\d(?:xyz|(?=-\\dxyz))(?:-\\d(?:xyz)?)?\\b\n ^ $ xyz xyz" }, { "answer_id": 74587475, "author": "Daniel Cruz", "author_id": 17537072, "author_profile": "https://Stackoverflow.com/users/17537072", "pm_score": 0, "selected": false, "text": "^.*xyz.*$\n xyz .* ^ $ xyz ^.*(?:-?\\d+xyz)+.*$\n" }, { "answer_id": 74590320, "author": "Buttered_Toast", "author_id": 12522652, "author_profile": "https://Stackoverflow.com/users/12522652", "pm_score": 1, "selected": false, "text": "(\\dxyz-\\dxyz|\\dxyz-\\d|\\d-\\dxyz|\\dxyz)\n \\b(\\dxyz-\\dxyz|\\dxyz-\\d|\\d-\\dxyz|\\dxyz)\\b\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13277644/" ]
74,584,445
<p>I have a huge list like this. I want to remove the lines that have only numbers. How can I do that? I'm using <strong>Notepad++</strong>. So, if possible, please give me a solution that will work on <strong>Notepad++</strong></p> <p><strong>List:</strong></p> <pre><code>dog.belt.b79 dog.food 7902823429 dog.hoodie.722 1898261 dog.collar dogbelt 80862 doghoodie.89 42111556 </code></pre> <p><strong>I want:</strong></p> <pre><code>dog.belt.b79 dog.food dog.hoodie.722 dog.collar dogbelt doghoodie.89 </code></pre> <p>I tried to Google it. But nothing really helps.</p>
[ { "answer_id": 74584583, "author": "help-info.de", "author_id": 1981088, "author_profile": "https://Stackoverflow.com/users/1981088", "pm_score": 1, "selected": false, "text": "^\\d+\\R NOTHING" }, { "answer_id": 74593134, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "\\s*^\\s*\\d+\\s*$\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13776038/" ]
74,584,494
<pre><code>u = [] n = 3 for i in range(0,n): u[i] = n - i u.append(u[i]) print(u) </code></pre> <p>I am creating an array as u = [0 n-2 n-1....1]. I tried with above code and I cant find my mistake here.</p>
[ { "answer_id": 74584583, "author": "help-info.de", "author_id": 1981088, "author_profile": "https://Stackoverflow.com/users/1981088", "pm_score": 1, "selected": false, "text": "^\\d+\\R NOTHING" }, { "answer_id": 74593134, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "\\s*^\\s*\\d+\\s*$\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20608660/" ]
74,584,534
<p>I am attempting to set up the Vite project configuration shown in Thomas Findlay's book &quot;React The Road To Enterprise.&quot; I am trying to configure absolute imports (2.2.7)</p> <p>When I run <code>pnpm run dev</code> or <code>npm run dev</code> the dev server gives this error referencing <code>stylelint</code>. Does anyone know what the issue could be? All my config files are below. (<a href="https://github.com/currenthandle/react-road-to-enterprise" rel="nofollow noreferrer">https://github.com/currenthandle/react-road-to-enterprise</a>)</p> <pre><code>error when starting dev server: Error: Dynamic require of &quot;stylelint&quot; is not supported at formatError (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39975:46) at Context.error (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39971:19) at Context.buildStart (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite-plugin-stylelint@3.0.2_ob6wbqjaxhaqcketchi7ll2j5i/node_modules/vite-plugin-stylelint/dist/index.mjs:1:2251) at async Promise.all (index 4) at async hookParallel (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39862:9) at async Object.buildStart (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:40133:13) at async file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:61879:13 at async httpServer.listen (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:61894:17)  ELIFECYCLE  Command failed with exit code 1. </code></pre> <p><a href="https://github.com/currenthandle/react-road-to-enterprise" rel="nofollow noreferrer">https://github.com/currenthandle/react-road-to-enterprise</a></p> <p><code>vite.config.ts</code></p> <pre><code>/// &lt;reference types=&quot;vitest&quot; /&gt; import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { fileURLToPath, URL } from 'url'; import eslint from 'vite-plugin-eslint'; import StylelintPlugin from 'vite-plugin-stylelint'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), eslint(), StylelintPlugin({ fix: true, quiet: false, }), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), 'test-utils': fileURLToPath( new URL('./src/helpers/test-utils.tsx', import.meta.url) ), }, }, css: { preprocessorOptions: { scss: { // example : additionalData: `@import &quot;./src/styles/variables&quot;;` // There is need to include the .scss file extensions. additionalData: `@import &quot;./src/styles/variables&quot;;`, }, }, }, test: { globals: true, environment: 'jsdom', coverage: { reporter: ['text', 'json', 'html'], }, setupFiles: ['./vitest.setup.ts'], }, }); </code></pre> <p><code>tsconfig.ts</code></p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;.&quot;, &quot;target&quot;: &quot;ESNext&quot;, &quot;useDefineForClassFields&quot;: true, &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ESNext&quot;], &quot;allowJs&quot;: false, &quot;skipLibCheck&quot;: true, &quot;esModuleInterop&quot;: false, &quot;allowSyntheticDefaultImports&quot;: true, &quot;strict&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true, &quot;module&quot;: &quot;ESNext&quot;, &quot;moduleResolution&quot;: &quot;Node&quot;, &quot;resolveJsonModule&quot;: true, &quot;isolatedModules&quot;: true, &quot;noEmit&quot;: true, &quot;jsx&quot;: &quot;react-jsx&quot;, &quot;paths&quot;: { &quot;@/*&quot;: [&quot;src/*&quot;], &quot;test-utils&quot;: [&quot;src/helpers/test-utils&quot;] } }, &quot;include&quot;: [&quot;src&quot;], &quot;references&quot;: [{ &quot;path&quot;: &quot;./tsconfig.node.json&quot; }] } </code></pre> <p><code>stylelint.config.cjs</code></p> <pre><code>/* eslint-env node */ module.exports = { extends: [ 'stylelint-config-standard', 'stylelint-config-recess-order', 'stylelint-config-css-modules', 'stylelint-config-prettier', // Uncomment out the below if you want to use scss 'stylelint-config-standard-scss', 'stylelint-config-recommended-scss', ], plugins: ['stylelint-scss'], ignoreFiles: [ './node_modules/**/*.css', './dist/**/*.css', './coverage/**/*.css', ], rules: { 'at-rule-no-unknown': [ true, { ignoreAtRules: [ 'tailwind', 'apply', 'screen', 'variants', 'responsive', ], }, ], 'no-duplicate-selectors': null, 'no-empty-source': null, 'rule-empty-line-before': null, 'comment-empty-line-before': null, 'selector-pseudo-element-no-unknown': null, 'declaration-block-trailing-semicolon': null, 'no-descending-specificity': null, 'string-no-newline': null, // Limit the number of universal selectors in a selector, // to avoid very slow selectors 'selector-max-universal': 1, 'selector-class-pattern': '^[a-z][a-zA-Z0-9]+$', // -------- // SCSS rules // -------- 'scss/dollar-variable-colon-space-before': 'never', 'scss/dollar-variable-colon-space-after': 'always', 'scss/dollar-variable-no-missing-interpolation': true, 'scss/dollar-variable-pattern': /^[a-z-]+$/, 'scss/double-slash-comment-whitespace-inside': 'always', 'scss/operator-no-newline-before': true, 'scss/operator-no-unspaced': true, 'scss/selector-no-redundant-nesting-selector': true, // Allow SCSS and CSS module keywords beginning with `@` 'scss/at-rule-no-unknown': null, }, } </code></pre> <p><code>postcss.config.cjs</code></p> <pre><code>/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-env node */ module.exports = { plugins: [ require('postcss-flexbugs-fixes'), require('stylelint')({ configFile: 'stylelint.config.js', }), require('postcss-import'), require('postcss-extend'), require('postcss-mixins'), // Comment out postcss-nested if you're using tailwindcss/nesting require('postcss-nested'), require('tailwindcss/nesting'), require('tailwindcss')('tailwind.config.js'), require('postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, 'nesting-rules': false, }, }), require('autoprefixer')(), require('postcss-reporter'), ], }; </code></pre> <p><code>tailwind.config.cjs</code></p> <pre><code>const colors = require('tailwindcss/colors'); module.exports = { content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], theme: { extend: {}, }, // Add only if you want to use the @tailwindcss/forms package plugins: [require('@tailwindcss/forms')], }; </code></pre> <p><code>tsconfig.json</code></p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;.&quot;, &quot;target&quot;: &quot;ESNext&quot;, &quot;useDefineForClassFields&quot;: true, &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ESNext&quot;], &quot;allowJs&quot;: false, &quot;skipLibCheck&quot;: true, &quot;esModuleInterop&quot;: false, &quot;allowSyntheticDefaultImports&quot;: true, &quot;strict&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true, &quot;module&quot;: &quot;ESNext&quot;, &quot;moduleResolution&quot;: &quot;Node&quot;, &quot;resolveJsonModule&quot;: true, &quot;isolatedModules&quot;: true, &quot;noEmit&quot;: true, &quot;jsx&quot;: &quot;react-jsx&quot;, &quot;paths&quot;: { &quot;@/*&quot;: [&quot;src/*&quot;], &quot;test-utils&quot;: [&quot;src/helpers/test-utils&quot;] } }, &quot;include&quot;: [&quot;src&quot;], &quot;references&quot;: [{ &quot;path&quot;: &quot;./tsconfig.node.json&quot; }] } </code></pre> <p><code>postcss.config.cjs</code></p> <pre><code>/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-env node */ module.exports = { plugins: [ require('postcss-flexbugs-fixes'), require('stylelint')({ configFile: 'stylelint.config.js', }), require('postcss-import'), require('postcss-extend'), require('postcss-mixins'), // Comment out postcss-nested if you're using tailwindcss/nesting require('postcss-nested'), require('tailwindcss/nesting'), require('tailwindcss')('tailwind.config.js'), require('postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, 'nesting-rules': false, }, }), require('autoprefixer')(), require('postcss-reporter'), ], }; </code></pre> <p><code>prettier.config.cjs</code></p> <pre><code>/* eslint-env node */ module.exports = { endOfLine: 'lf', jsxSingleQuote: true, printWidth: 80, proseWrap: 'never', quoteProps: 'as-needed', semi: true, singleQuote: true, tabWidth: 2, trailingComma: 'es5', useTabs: false, }; </code></pre>
[ { "answer_id": 74584794, "author": "Jay F.", "author_id": 20504019, "author_profile": "https://Stackoverflow.com/users/20504019", "pm_score": 2, "selected": true, "text": "type: \"module\"" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5633198/" ]
74,584,553
<p>I have a large dataframe with rows that have duplicated first three columns (UnionChr, UnionStart, UnionEnd) and the remaining columns differ in values.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>UnionChr</th> <th>UnionStart</th> <th>UnionEnd</th> <th>IntersectChr</th> <th>IntersectStart</th> <th>IntersectEnd</th> <th>IntersectLength</th> <th>IntersectPileup</th> <th>IntersectName</th> <th>Overlap</th> <th>Genotype</th> <th>PeakType</th> </tr> </thead> <tbody> <tr> <td>chr1</td> <td>3667144</td> <td>3668013</td> <td>.</td> <td>-1</td> <td>-1</td> <td>.</td> <td>.</td> <td>.</td> <td>0</td> <td>WT</td> <td>DKO Specific</td> </tr> <tr> <td>chr1</td> <td>3667144</td> <td>3668013</td> <td>chr1</td> <td>3667144</td> <td>3668013</td> <td>870</td> <td>20.60</td> <td>dko_k27_peak_1</td> <td>869</td> <td>DKO</td> <td>N/A</td> </tr> <tr> <td>chr1</td> <td>4478778</td> <td>4479151</td> <td>chr1</td> <td>4478778</td> <td>4479151</td> <td>374</td> <td>22.90</td> <td>wt_k27_peak_4</td> <td>373</td> <td>WT</td> <td>N/A</td> </tr> <tr> <td>chr1</td> <td>4478778</td> <td>4479151</td> <td>.</td> <td>-1</td> <td>-1</td> <td>.</td> <td>.</td> <td>.</td> <td>0</td> <td>DKO</td> <td>WT Specific</td> </tr> <tr> <td>chr1</td> <td>4482327</td> <td>4483301</td> <td>.</td> <td>-1</td> <td>-1</td> <td>.</td> <td>.</td> <td>.</td> <td>0</td> <td>WT</td> <td>DKO Specific</td> </tr> <tr> <td>chr1</td> <td>4482327</td> <td>4483301</td> <td>chr1</td> <td>4482327</td> <td>4483301</td> <td>975</td> <td>22.77</td> <td>dko_k27_peak_4</td> <td>974</td> <td>DKO</td> <td>N/A</td> </tr> <tr> <td>chr1</td> <td>4483527</td> <td>4483784</td> <td>chr1</td> <td>4483527</td> <td>4483784</td> <td>258</td> <td>24.58</td> <td>wt_k27_peak_5</td> <td>257</td> <td>WT</td> <td>N/A</td> </tr> <tr> <td>chr1</td> <td>4483527</td> <td>4483784</td> <td>.</td> <td>-1</td> <td>-1</td> <td>.</td> <td>.</td> <td>.</td> <td>0</td> <td>DKO</td> <td>WT Specific</td> </tr> </tbody> </table> </div> <p>I ultimately want to just replace the N/A value with WT or DKO specific from the duplicated row and then remove the duplicated row, so my final data should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>UnionChr</th> <th>UnionStart</th> <th>UnionEnd</th> <th>IntersectChr</th> <th>IntersectStart</th> <th>IntersectEnd</th> <th>IntersectLength</th> <th>IntersectPileup</th> <th>IntersectName</th> <th>Overlap</th> <th>Genotype</th> <th>PeakType</th> </tr> </thead> <tbody> <tr> <td>chr1</td> <td>3667144</td> <td>3668013</td> <td>chr1</td> <td>3667144</td> <td>3668013</td> <td>870</td> <td>20.60</td> <td>dko_k27_peak_1</td> <td>869</td> <td>DKO</td> <td>DKO Specific</td> </tr> <tr> <td>chr1</td> <td>4478778</td> <td>4479151</td> <td>chr1</td> <td>4478778</td> <td>4479151</td> <td>374</td> <td>22.90</td> <td>wt_k27_peak_4</td> <td>373</td> <td>WT</td> <td>WT Specific</td> </tr> <tr> <td>chr1</td> <td>4482327</td> <td>4483301</td> <td>chr1</td> <td>4482327</td> <td>4483301</td> <td>975</td> <td>22.77</td> <td>dko_k27_peak_4</td> <td>974</td> <td>DKO</td> <td>DKO Specific</td> </tr> <tr> <td>chr1</td> <td>4483527</td> <td>4483784</td> <td>chr1</td> <td>4483527</td> <td>4483784</td> <td>258</td> <td>24.58</td> <td>wt_k27_peak_5</td> <td>257</td> <td>WT</td> <td>WT Specific</td> </tr> </tbody> </table> </div> <p>I can't do a search/replace based Genotype and PeakType column because I have other rows that don't have this duplicated problem that also have N/A. An additional problem is that the duplicated row is either leading or lagging, depending on the data set it came from.</p> <p>I know I should use dplyr, and group by the first three columns, and somehow use lead/lag.</p> <pre><code>test &lt;- df %&gt;% group_by(UnionChr, UnionStart, UnionEnd) %&gt;% mutate(??) </code></pre>
[ { "answer_id": 74584612, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\ndf %>% \n mutate(PeakType = na_if(PeakType, \"N/A\"),\n indx = is.na(PeakType)) %>%\n group_by(UnionChr, UnionStart, UnionEnd) %>% \n fill(PeakType, .direction = \"downup\") %>% \n filter(indx) %>% \n ungroup %>%\n select(-indx)\n # A tibble: 4 × 12\n UnionChr UnionStart UnionEnd IntersectChr IntersectStart IntersectEnd IntersectLe…¹ Inter…² Inter…³ Overlap Genot…⁴ PeakT…⁵\n <chr> <int> <int> <chr> <int> <int> <chr> <chr> <chr> <int> <chr> <chr> \n1 chr1 3667144 3668013 chr1 3667144 3668013 870 20.60 dko_k2… 869 DKO DKO Sp…\n2 chr1 4478778 4479151 chr1 4478778 4479151 374 22.90 wt_k27… 373 WT WT Spe…\n3 chr1 4482327 4483301 chr1 4482327 4483301 975 22.77 dko_k2… 974 DKO DKO Sp…\n4 chr1 4483527 4483784 chr1 4483527 4483784 258 24.58 wt_k27… 257 WT WT Spe…\n# … with abbreviated variable names ¹​IntersectLength, ²​IntersectPileup, ³​IntersectName, ⁴​Genotype, ⁵​PeakType\n df <- structure(list(UnionChr = c(\"chr1\", \"chr1\", \"chr1\", \"chr1\", \"chr1\", \n\"chr1\", \"chr1\", \"chr1\"), UnionStart = c(3667144L, 3667144L, 4478778L, \n4478778L, 4482327L, 4482327L, 4483527L, 4483527L), UnionEnd = c(3668013L, \n3668013L, 4479151L, 4479151L, 4483301L, 4483301L, 4483784L, 4483784L\n), IntersectChr = c(\".\", \"chr1\", \"chr1\", \".\", \".\", \"chr1\", \"chr1\", \n\".\"), IntersectStart = c(-1L, 3667144L, 4478778L, -1L, -1L, 4482327L, \n4483527L, -1L), IntersectEnd = c(-1L, 3668013L, 4479151L, -1L, \n-1L, 4483301L, 4483784L, -1L), IntersectLength = c(\".\", \"870\", \n\"374\", \".\", \".\", \"975\", \"258\", \".\"), IntersectPileup = c(\".\", \n\"20.60\", \"22.90\", \".\", \".\", \"22.77\", \"24.58\", \".\"), IntersectName = c(\".\", \n\"dko_k27_peak_1\", \"wt_k27_peak_4\", \".\", \".\", \"dko_k27_peak_4\", \n\"wt_k27_peak_5\", \".\"), Overlap = c(0L, 869L, 373L, 0L, 0L, 974L, \n257L, 0L), Genotype = c(\"WT\", \"DKO\", \"WT\", \"DKO\", \"WT\", \"DKO\", \n\"WT\", \"DKO\"), PeakType = c(\"DKO Specific\", \"N/A\", \"N/A\", \"WT Specific\", \n\"DKO Specific\", \"N/A\", \"N/A\", \"WT Specific\")), \nclass = \"data.frame\", row.names = c(NA, \n-8L))\n" }, { "answer_id": 74585278, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>%\n group_by(UnionStart) %>% \n mutate(PeakType = na_if(PeakType, \"N/A\")) %>% \n fill(PeakType, .direction = \"downup\") %>% \n filter(!if_any(.col=everything(), .fns = ~ . == \".\"))\n UnionChr UnionStart UnionEnd IntersectChr IntersectStart IntersectEnd IntersectLength IntersectPileup IntersectName Overlap Genotype PeakType \n <chr> <int> <int> <chr> <int> <int> <chr> <chr> <chr> <int> <chr> <chr> \n1 chr1 3667144 3668013 chr1 3667144 3668013 870 20.60 dko_k27_peak_1 869 DKO DKO Specific\n2 chr1 4478778 4479151 chr1 4478778 4479151 374 22.90 wt_k27_peak_4 373 WT WT Specific \n3 chr1 4482327 4483301 chr1 4482327 4483301 975 22.77 dko_k27_peak_4 974 DKO DKO Specific\n4 chr1 4483527 4483784 chr1 4483527 4483784 258 24.58 wt_k27_peak_5 257 WT WT Specific\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17053500/" ]
74,584,598
<p>I have following React component:</p> <p><code>App.tsx:</code></p> <pre><code>function App() { const [countdownTimers, setCountdownTimers] = React.useState&lt; Map&lt;number, number&gt; &gt;(new Map([[1, 60]])); useEffect(() =&gt; { const timeoutId = setInterval(() =&gt; { setCountdownTimers((prevState) =&gt; { console.log(prevState); for (const [timerKey, timer] of prevState) { prevState.set(timerKey, timer - 1); } return new Map(prevState); }); }, 1000); return () =&gt; { clearInterval(timeoutId); }; }, []); return &lt;&gt;{countdownTimers.get(1)}&lt;/&gt;; }; </code></pre> <p><code>index.tsx</code></p> <pre><code>&lt;React.StrictMode&gt; &lt;App /&gt; &lt;/React.StrictMode&gt; </code></pre> <p>Code above is expected to subtract <code>1</code> from all values in <code>Map</code> every second. But due to <code>StrictMode</code> it subtracts <code>2</code>. Removing <code>&lt;React.StrictMode&gt;</code> solves issue, but I want to understand why <code>StrictMode</code> behave this way only with <code>Map</code></p> <p>Could you please advise why it's this way?</p> <p><a href="https://i.stack.imgur.com/56D5s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/56D5s.png" alt="duplicated" /></a></p>
[ { "answer_id": 74584673, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": true, "text": "setCountdownTimers((prevState) => {\n console.log(prevState);\n for (const [timerKey, timer] of prevState) {\n prevState.set(timerKey, timer - 1);\n }\n return new Map(prevState);\n});\n prevState.set prevState function App() {\n const [countdownTimers, setCountdownTimers] = React.useState(new Map([[1, 60]]));\n\n React.useEffect(() => {\n const timeoutId = setInterval(() => {\n setCountdownTimers((prevState) => {\n const newMap = new Map(prevState);\n console.log(JSON.stringify([...newMap.entries()]));\n for (const [timerKey, timer] of prevState) {\n newMap.set(timerKey, timer - 1);\n }\n return newMap;\n });\n }, 1000);\n return () => {\n clearInterval(timeoutId);\n };\n }, []);\n\n return countdownTimers.get(1);\n};\n\nReactDOM.createRoot(document.querySelector('.react')).render(<React.StrictMode><App /></React.StrictMode>); <script crossorigin src=\"https://unpkg.com/react@18/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@18/umd/react-dom.development.js\"></script>\n<div class='react'></div>" }, { "answer_id": 74584701, "author": "Karim Elghamry", "author_id": 10853255, "author_profile": "https://Stackoverflow.com/users/10853255", "pm_score": 0, "selected": false, "text": "Map setCountdownTimers 2 1" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7374141/" ]
74,584,614
<h2>Explanation</h2> <p>I'm working with <code>react-select</code> and want to generate the <code>options</code> array which would be passed to the <code>react-select</code> component.</p> <p>The options array is of the type:</p> <pre><code>type TOptions = { value: string; label: string }[] </code></pre> <p>I get the data for the <code>options</code> array from an API. The data will have a structure like:</p> <pre><code>{ name: string; slug: string; id: number; }[] </code></pre> <p>So, I created a helper function to transform the data into the options array format.</p> <pre><code>const generateSelectOptions = ( data: Record&lt;string, string&gt;[], field: { valueKey: string; labelKey: string } ) =&gt; { const options = data.map((data) =&gt; ({ value: data[field.valueKey], label: data[field.labelKey], })); // TODO: create a better type check return options as TOptions; }; </code></pre> <p>This function will have get two params,</p> <ol> <li><code>data</code> - data received from the API</li> <li><code>field</code> - which is an object that would contain the keys, <code>valueKey</code> and <code>labelKey</code> from the <code>data</code> object that would be mapped appropriately to the <code>options</code> array.</li> </ol> <p>The function I created works fine, but I have manually asserted the return type of the function as <code>TOptions</code>.</p> <h3>Example</h3> <pre><code> const data = [ { name: &quot;Holy Holy Holy&quot;, slug: &quot;holy-holy-holy&quot;, id: 1, }, { name: &quot;Amazing Grace&quot;, slug: &quot;amazing-grace&quot;, id: 2, }, ]; const options = generateSelectOptions(data, { valueKey: &quot;slug&quot;, labelKey: &quot;name&quot;, }); // now options would be options = [ { label: &quot;Holy Holy Holy&quot;, value: &quot;holy-holy-holy&quot;, }, { label: &quot;Amazing Grace&quot;, value: &quot;amazing-grace&quot;, }, ]; </code></pre> <h2>Question</h2> <p>Now, I'm thinking of a better way to type <code>generateSelectOptions</code> function, where when calling the function, as soon as I give the first argument <code>data</code>, the <code>fieldKeys</code> object which would be the second argument should automatically get type inference, as the <code>fieldKeys</code> - <code>valueKey</code> and <code>labelKey</code> can only be of the type <code>keyof data</code></p> <p>Is there a way to achieve this? I would really appreciate some help here. Thanks</p>
[ { "answer_id": 74584673, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": true, "text": "setCountdownTimers((prevState) => {\n console.log(prevState);\n for (const [timerKey, timer] of prevState) {\n prevState.set(timerKey, timer - 1);\n }\n return new Map(prevState);\n});\n prevState.set prevState function App() {\n const [countdownTimers, setCountdownTimers] = React.useState(new Map([[1, 60]]));\n\n React.useEffect(() => {\n const timeoutId = setInterval(() => {\n setCountdownTimers((prevState) => {\n const newMap = new Map(prevState);\n console.log(JSON.stringify([...newMap.entries()]));\n for (const [timerKey, timer] of prevState) {\n newMap.set(timerKey, timer - 1);\n }\n return newMap;\n });\n }, 1000);\n return () => {\n clearInterval(timeoutId);\n };\n }, []);\n\n return countdownTimers.get(1);\n};\n\nReactDOM.createRoot(document.querySelector('.react')).render(<React.StrictMode><App /></React.StrictMode>); <script crossorigin src=\"https://unpkg.com/react@18/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@18/umd/react-dom.development.js\"></script>\n<div class='react'></div>" }, { "answer_id": 74584701, "author": "Karim Elghamry", "author_id": 10853255, "author_profile": "https://Stackoverflow.com/users/10853255", "pm_score": 0, "selected": false, "text": "Map setCountdownTimers 2 1" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9162851/" ]
74,584,642
<p>How can I write a JavaScript object inside of an array that is inside a JSON file? What I mean is: I'm making a Discord (message app) BOT, when the user uses the command &quot;/add&quot; the BOT will ask for 2 inputs, a &quot;name&quot; and an &quot;artist&quot; both this inputs make up a song so I'm creating an object called &quot;data&quot; for that song. I also have a JSON file, that my database, what I want is, everytime this command is used, my object should the pushed inside of an array in my JSON file, so later on I can retrieve a random object inside of this array. <strong>How can I do that? I hope the question is not too confusing, thanks!</strong></p> <pre><code> module.exports={ data: new SlashCommandBuilder() .setName('add') .setDescription('Add a song to the database.') .addStringOption(option =&gt; option.setName('artist') .setDescription('The artist of the song') .setRequired(true)) .addStringOption(option =&gt; option.setName('name') .setDescription('The name of the song') .setRequired(true)), async execute(interaction){ let name = interaction.options.getString('name'); let artist = interaction.options.getString('artist'); const data = { name: name, artist: artist}; await interaction.reply(`**` + artist + `**` + ` - ` + `**` + name + `**` + ` was added to the database.`)}, }; //WHAT YOU SEE FROM NOW ON IS A DIFFERENT FILE, A JSON FILE CALLED data.json with some examples of what it should look like [ { &quot;name&quot;:&quot;Die for You&quot;, &quot;artist&quot;:&quot;The Weeknd&quot; }, { &quot;name&quot;:&quot;FEAR&quot;, &quot;artist&quot;:&quot;Kendrick Lamar&quot; } ] </code></pre>
[ { "answer_id": 74584656, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": ".push var arr = [];\narr.push(123);\narr.push({a:1,b:2});\narr.push(null);\narr.push(\"string\");\nconsole.dir(arr);" }, { "answer_id": 74585114, "author": "Krelq", "author_id": 15000290, "author_profile": "https://Stackoverflow.com/users/15000290", "pm_score": 1, "selected": false, "text": "const fs = require('fs');\nconst data = { name: name, artist: artist };\n\nfs.writeFile(\"output.json\", JSON.stringify(data), 'utf8', function (err) {\n if (err) {\n console.log(\"An error occured while writing JSON Object to File.\");\n return console.log(err);\n }\n\n console.log(\"JSON file has been saved.\");\n});\n let rawdata = fs.readFileSync('data.json');\nlet data = JSON.parse(rawdata);\n\ndata.push({name: name, artist: artist}); \n// to use push() function data have to be an array, edit your .json file to \" [] \", \n// now you can add elements.\n\nfs.writeFile(\"output.json\", JSON.stringify(data), 'utf8', function (err) {\n if (err) {\n console.log(\"An error occured while writing JSON Object to File.\");\n return console.log(err);\n }\n\n console.log(\"JSON file has been saved.\");\n});\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20287603/" ]
74,584,661
<p>Is anyone else receiving a moduleNotFoundError with their requests library? Not sure why this is happening. The library is installed as well which is even more confusing.</p> <pre class="lang-py prettyprint-override"><code> import csv from datetime import datetime import requests from bs4 import BeautifulSoup </code></pre> <p>and the resulting error was this:</p> <pre class="lang-py prettyprint-override"><code> --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In [1], line 4 2 import csv 3 from datetime import datetime ----&gt; 4 import requests 5 from bs4 import BeautifulSoup ModuleNotFoundError: No module named 'requests' </code></pre> <p>when i run <code>pip freeze</code> I can confirm I have requests installed as well, see below:</p> <p><a href="https://i.stack.imgur.com/eENSn.png" rel="nofollow noreferrer">Screenshot from my terminal</a></p> <p>I have requests version <code>requests==2.28.1</code></p>
[ { "answer_id": 74584656, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": ".push var arr = [];\narr.push(123);\narr.push({a:1,b:2});\narr.push(null);\narr.push(\"string\");\nconsole.dir(arr);" }, { "answer_id": 74585114, "author": "Krelq", "author_id": 15000290, "author_profile": "https://Stackoverflow.com/users/15000290", "pm_score": 1, "selected": false, "text": "const fs = require('fs');\nconst data = { name: name, artist: artist };\n\nfs.writeFile(\"output.json\", JSON.stringify(data), 'utf8', function (err) {\n if (err) {\n console.log(\"An error occured while writing JSON Object to File.\");\n return console.log(err);\n }\n\n console.log(\"JSON file has been saved.\");\n});\n let rawdata = fs.readFileSync('data.json');\nlet data = JSON.parse(rawdata);\n\ndata.push({name: name, artist: artist}); \n// to use push() function data have to be an array, edit your .json file to \" [] \", \n// now you can add elements.\n\nfs.writeFile(\"output.json\", JSON.stringify(data), 'utf8', function (err) {\n if (err) {\n console.log(\"An error occured while writing JSON Object to File.\");\n return console.log(err);\n }\n\n console.log(\"JSON file has been saved.\");\n});\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20480131/" ]
74,584,679
<p>In Node js, trying to fetch data using Axios Get from any URL. For example: [Json Place Holder] <a href="https://jsonplaceholder.typicode.com/users" rel="nofollow noreferrer">https://jsonplaceholder.typicode.com/users</a></p> <p>.The response.data() is returning special characters. Tried to use the same request from Postman, its fetching data as expected.</p> <p>In VSCode:</p> <pre><code>const axios = require(&quot;axios&quot;); async function getData() { const resp = await axios.get( &quot;https://jsonplaceholder.typicode.com/users&quot;, {} ); console.log(resp.data); } getData(); </code></pre> <p>Output:<a href="https://i.stack.imgur.com/jUUNU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jUUNU.jpg" alt="output showing special characters" /></a> I am not sure what went wrong. Node version is v16.14.2, axios version is ^1.2.0</p> <p>The response' status is 200. the response.data() is as shown in the image. Please help</p>
[ { "answer_id": 74585119, "author": "Bench Vue", "author_id": 8054998, "author_profile": "https://Stackoverflow.com/users/8054998", "pm_score": 2, "selected": false, "text": "const axios = require(\"axios\");\nasync function getData() {\n const resp = await axios.get(\n \"https://jsonplaceholder.typicode.com/users\",\n {\n headers: {\n 'Accept-Encoding': 'application/json',\n }\n }\n );\n console.log(JSON.stringify(resp.data));\n}\ngetData()\n $ node get-data.js\n[{\"id\":1,\"name\":\"Leanne Graham\",\"username\":\"Bret\",\"email\":\"Sincere@april.biz\",\"address\":{\"street\":\"Kulas Light\",\"suite\":\"Apt. 556\",\"city\":\"Gwenborough\",\"zipcode\":\"92998-3874\",\"geo\":{\"lat\":\"-37.3159\",\"lng\":\"81.1496\"}},\"phone\":\"1-770-736-8031 x56442\",\"website\":\"hildegard.org\",\"company\":{\"name\":\n\"Romaguera-Crona\",\"catchPhrase\":\"Multi-layered client-server neural-net\",\"bs\":\"harness real-time e-markets\"}},{\"id\":2,\"name\":\"Ervin Howell\",\"username\":\"Antonette\",\"email\":\"Shanna@melissa.tv\",\"address\":{\"street\":\"Victor Plains\",\"suite\":\"Suite 879\",\"city\":\"Wisokyburgh\",\"zipcode\":\"90566-7771\",\"g\neo\":{\"lat\":\"-43.9509\",\"lng\":\"-34.4618\"}},\"phone\":\"010-692-6593 x09125\",\"website\":\"anastasia.net\",\"company\":{\"name\":\"Deckow-Crist\",\"catchPhrase\":\"Proactive didactic contingency\",\"bs\":\"synergize scalable supply-chains\"}},{\"id\":3,\"name\":\"Clementine Bauch\",\"username\":\"Samantha\",\"email\":\"Nathan@ye\nsenia.net\",\"address\":{\"street\":\"Douglas Extension\",\"suite\":\"Suite 847\",\"city\":\"McKenziehaven\",\"zipcode\":\"59590-4157\",\"geo\":{\"lat\":\"-68.6102\",\"lng\":\"-47.0653\"}},\"phone\":\"1-463-123-4447\",\"website\":\"ramiro.info\",\"company\":{\"name\":\"Romaguera-Jacobson\",\"catchPhrase\":\"Face to face bifurcated interf\nace\",\"bs\":\"e-enable strategic applications\"}},{\"id\":4,\"name\":\"Patricia Lebsack\",\"username\":\"Karianne\",\"email\":\"Julianne.OConner@kory.org\",\"address\":{\"street\":\"Hoeger Mall\",\"suite\":\"Apt. 692\",\"city\":\"South Elvis\",\"zipcode\":\"53919-4257\",\"geo\":{\"lat\":\"29.4572\",\"lng\":\"-164.2990\"}},\"phone\":\"493-17\n0-9623 x156\",\"website\":\"kale.biz\",\"company\":{\"name\":\"Robel-Corkery\",\"catchPhrase\":\"Multi-tiered zero tolerance productivity\",\"bs\":\"transition cutting-edge web services\"}},{\"id\":5,\"name\":\"Chelsey Dietrich\",\"username\":\"Kamren\",\"email\":\"Lucio_Hettinger@annie.ca\",\"address\":{\"street\":\"Skiles Walks\n\",\"suite\":\"Suite 351\",\"city\":\"Roscoeview\",\"zipcode\":\"33263\",\"geo\":{\"lat\":\"-31.8129\",\"lng\":\"62.5342\"}},\"phone\":\"(254)954-1289\",\"website\":\"demarco.info\",\"company\":{\"name\":\"Keebler LLC\",\"catchPhrase\":\"User-centric fault-tolerant solution\",\"bs\":\"revolutionize end-to-end systems\"}},{\"id\":6,\"name\":\n\"Mrs. Dennis Schulist\",\"username\":\"Leopoldo_Corkery\",\"email\":\"Karley_Dach@jasper.info\",\"address\":{\"street\":\"Norberto Crossing\",\"suite\":\"Apt. 950\",\"city\":\"South Christy\",\"zipcode\":\"23505-1337\",\"geo\":{\"lat\":\"-71.4197\",\"lng\":\"71.7478\"}},\"phone\":\"1-477-935-8478 x6430\",\"website\":\"ola.org\",\"company\n\":{\"name\":\"Considine-Lockman\",\"catchPhrase\":\"Synchronised bottom-line interface\",\"bs\":\"e-enable innovative applications\"}},{\"id\":7,\"name\":\"Kurtis Weissnat\",\"username\":\"Elwyn.Skiles\",\"email\":\"Telly.Hoeger@billy.biz\",\"address\":{\"street\":\"Rex Trail\",\"suite\":\"Suite 280\",\"city\":\"Howemouth\",\"zipcod\ne\":\"58804-1099\",\"geo\":{\"lat\":\"24.8918\",\"lng\":\"21.8984\"}},\"phone\":\"210.067.6132\",\"website\":\"elvis.io\",\"company\":{\"name\":\"Johns Group\",\"catchPhrase\":\"Configurable multimedia task-force\",\"bs\":\"generate enterprise e-tailers\"}},{\"id\":8,\"name\":\"Nicholas Runolfsdottir V\",\"username\":\"Maxime_Nienow\",\"\nemail\":\"Sherwood@rosamond.me\",\"address\":{\"street\":\"Ellsworth Summit\",\"suite\":\"Suite 729\",\"city\":\"Aliyaview\",\"zipcode\":\"45169\",\"geo\":{\"lat\":\"-14.3990\",\"lng\":\"-120.7677\"}},\"phone\":\"586.493.6943 x140\",\"website\":\"jacynthe.com\",\"company\":{\"name\":\"Abernathy Group\",\"catchPhrase\":\"Implemented seconda\nry concept\",\"bs\":\"e-enable extensible e-tailers\"}},{\"id\":9,\"name\":\"Glenna Reichert\",\"username\":\"Delphine\",\"email\":\"Chaim_McDermott@dana.io\",\"address\":{\"street\":\"Dayna Park\",\"suite\":\"Suite 449\",\"city\":\"Bartholomebury\",\"zipcode\":\"76495-3109\",\"geo\":{\"lat\":\"24.6463\",\"lng\":\"-168.8889\"}},\"phone\":\"(\n775)976-6794 x41206\",\"website\":\"conrad.com\",\"company\":{\"name\":\"Yost and Sons\",\"catchPhrase\":\"Switchable contextually-based project\",\"bs\":\"aggregate real-time technologies\"}},{\"id\":10,\"name\":\"Clementina DuBuque\",\"username\":\"Moriah.Stanton\",\"email\":\"Rey.Padberg@karina.biz\",\"address\":{\"street\":\"\nKattie Turnpike\",\"suite\":\"Suite 198\",\"city\":\"Lebsackbury\",\"zipcode\":\"31428-2261\",\"geo\":{\"lat\":\"-38.2386\",\"lng\":\"57.2232\"}},\"phone\":\"024-648-3804\",\"website\":\"ambrose.net\",\"company\":{\"name\":\"Hoeger LLC\",\"catchPhrase\":\"Centralized empowering task-force\",\"bs\":\"target end-to-end models\"}}]\n" }, { "answer_id": 74587217, "author": "josh hoffer", "author_id": 17039095, "author_profile": "https://Stackoverflow.com/users/17039095", "pm_score": 1, "selected": false, "text": "headers: { Accept: 'application/json', 'Accept-Encoding': 'identity' }\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12851971/" ]
74,584,683
<h2>Background</h2> <p>I am making a custom control that has multiple ListBox's. I want to make this control MVVM compliant, so I am keeping any XAML and the code behind agnostic with respect to any ViewModel. One ListBox is simply going to be a list of TextBox's while the other is going to have a canvas as the host to display the data graphically. Both of these ListBox's are children of this custom control. Pseudo example for the custom control template:</p> <pre class="lang-xml prettyprint-override"><code>&lt;CustomControl&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ListBox1 Grid.Column=&quot;0&quot;/&gt; &lt;ListBox2 Grid.Column=&quot;1&quot;/&gt; &lt;/CustomControl&gt; </code></pre> <p>The code behind for this custrom control would have a dependency property that will serve as the ItemsSource, fairly standard stuff:</p> <pre class="lang-cs prettyprint-override"><code>public IEnumerable ItemsSource { get { return (IEnumerable)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(&quot;ItemsSource&quot;, typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged))); private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var control = sender as UserControl1; if (control != null) control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue); } </code></pre> <h2>Where I am stuck</h2> <p>Because the two ListBox's are using the same data source but just display the data differently, I want the ItemsSource defined as one of the the parent view's dependency properties to be the ItemsSource for the two children. From the ViewModel side, this items source can be some sort of <code>ObservableCollection&lt;ChildViewModels&gt;</code>, or IEnumerable, or whatever it wants to be.</p> <p><strong>How can I point to properties from the ItemsSource's ViewModel to dependency properties of the child views?</strong></p> <p>I was hoping to get something similar to how it could be done outside of a custom view:</p> <p>Example Parent ViewModel(omitting a lot, assume all functioning):</p> <pre class="lang-cs prettyprint-override"><code>public class ParentViewModel { public ObservableCollection&lt;ChildViewModel&gt; ChildViewModels; } </code></pre> <p>Example ViewModel (omitting <code>INotifyPropertyChanged</code> and associated logic):</p> <pre class="lang-cs prettyprint-override"><code>public class ChildViewModel { public string Name {get; set;} public string ID {get; set;} public string Description {get; set;} } </code></pre> <p>Example control (ommitting setting the DataContext, assume set properly):</p> <pre class="lang-xml prettyprint-override"><code>&lt;ListBox ItemsSource=&quot;{Binding ChildViewModels}&quot;&gt; &lt;ListBox.ItemsTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock Text=&quot;{Binding Name}&quot;/&gt; &lt;TextBlock Text =&quot;{Binding Description}&quot;/&gt; &lt;/StackPanel&gt; &lt;/ListBox.ItemsTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>How can I do something similar where I can pass the properties from the ItemsSource to the child views on a custom control?</p> <p>Many thanks</p>
[ { "answer_id": 74586279, "author": "BionicCode", "author_id": 3141792, "author_profile": "https://Stackoverflow.com/users/3141792", "pm_score": 0, "selected": false, "text": "ItemsSource ListBox IList IEnumerable IList ItemTemplate DataTemplate ListBox.ItemTemplate ItemsSource DataTemplate <Window>\n <Window.DataContext>\n <ParentViewModel />\n </Window.DataCOntext>\n\n <CustomControl ItemsSource=\"{Binding ChildViewModels}\">\n <CustomControl.ItemsTemplate>\n <StackPanel>\n <TextBlock Text=\"{Binding Name}\"/>\n <TextBlock Text =\"{Binding Description}\"/>\n </StackPanel>\n </CustomControl.ItemsTemplate>\n\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition/>\n <ColumnDefinition/>\n </Grid.ColumnDefinitions>\n\n <ListBox1 Grid.Column=\"0\"\n ItemsSource=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}\"\n ItemTemplate=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}\" />\n <ListBox2 Grid.Column=\"1\"\n ItemsSource=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}\"\n ItemTemplate=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}\" />\n </CustomControl>\n</Window>\n ListBox1 ListBox2 <UserControl>\n <ListBox ItemsSource=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}\"\n ItemTemplate=\"{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}\" />\n</UserControl>\n" }, { "answer_id": 74586719, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 2, "selected": true, "text": "using System.Collections;\nusing System.Windows;\nusing System.Windows.Controls;\n\nnamespace Core2022.SO.jgrmn\n{\n public class TwoListControl : Control\n {\n static TwoListControl()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(TwoListControl), new FrameworkPropertyMetadata(typeof(TwoListControl)));\n }\n\n public IEnumerable ItemsSource\n {\n get { return (IEnumerable)GetValue(ItemsSourceProperty); }\n set { SetValue(ItemsSourceProperty, value); }\n }\n\n public static readonly DependencyProperty ItemsSourceProperty =\n DependencyProperty.Register(\n nameof(ItemsSource),\n typeof(IEnumerable),\n typeof(TwoListControl),\n new PropertyMetadata((d, e) => ((TwoListControl)d).OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue)));\n\n private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)\n {\n //throw new NotImplementedException();\n }\n\n public DataTemplate TemplateForStack\n {\n get { return (DataTemplate)GetValue(TemplateForStackProperty); }\n set { SetValue(TemplateForStackProperty, value); }\n }\n\n public static readonly DependencyProperty TemplateForStackProperty =\n DependencyProperty.Register(\n nameof(TemplateForStack),\n typeof(DataTemplate),\n typeof(TwoListControl),\n new PropertyMetadata(null));\n\n public DataTemplate TemplateForCanvas\n {\n get { return (DataTemplate)GetValue(TemplateForCanvasProperty); }\n set { SetValue(TemplateForCanvasProperty, value); }\n }\n\n public static readonly DependencyProperty TemplateForCanvasProperty =\n DependencyProperty.Register(\n nameof(TemplateForCanvas),\n typeof(DataTemplate),\n typeof(TwoListControl),\n new PropertyMetadata(null));\n\n public Style StyleForCanvas\n {\n get { return (Style)GetValue(StyleForCanvasProperty); }\n set { SetValue(StyleForCanvasProperty, value); }\n }\n\n public static readonly DependencyProperty StyleForCanvasProperty =\n DependencyProperty.Register(\n nameof(StyleForCanvas),\n typeof(Style),\n typeof(TwoListControl),\n new PropertyMetadata(null));\n }\n}\n <ResourceDictionary\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:jgrmn=\"clr-namespace:Core2022.SO.jgrmn\">\n\n <Style TargetType=\"{x:Type jgrmn:TwoListControl}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type jgrmn:TwoListControl}\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition/>\n <ColumnDefinition/>\n </Grid.ColumnDefinitions>\n <ListBox Grid.Column=\"0\"\n ItemsSource=\"{TemplateBinding ItemsSource}\"\n ItemTemplate=\"{TemplateBinding TemplateForStack}\"/>\n <ListBox Grid.Column=\"1\"\n ItemsSource=\"{TemplateBinding ItemsSource}\"\n ItemTemplate=\"{TemplateBinding TemplateForCanvas}\"\n ItemContainerStyle=\"{TemplateBinding StyleForCanvas}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <Canvas/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n </ListBox>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</ResourceDictionary>\n <Window x:Class=\"Core2022.SO.jgrmn.TwoListWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:Core2022.SO.jgrmn\"\n mc:Ignorable=\"d\"\n Title=\"TwoListWindow\" Height=\"250\" Width=\"400\">\n <FrameworkElement.DataContext>\n <CompositeCollection>\n <Point>15 50</Point>\n <Point>50 150</Point>\n <Point>150 50</Point>\n <Point>150 150</Point>\n </CompositeCollection>\n </FrameworkElement.DataContext>\n <Grid>\n <local:TwoListControl ItemsSource=\"{Binding}\">\n <local:TwoListControl.TemplateForStack>\n <DataTemplate>\n <TextBlock>\n <TextBlock.Text>\n <MultiBinding StringFormat=\"{}Point ({0} {1})\">\n <Binding Path=\"X\"/>\n <Binding Path=\"Y\"/>\n </MultiBinding>\n </TextBlock.Text>\n </TextBlock>\n </DataTemplate>\n </local:TwoListControl.TemplateForStack>\n <local:TwoListControl.TemplateForCanvas>\n <DataTemplate>\n <Ellipse Width=\"10\" Height=\"10\" Fill=\"Red\"/>\n </DataTemplate>\n </local:TwoListControl.TemplateForCanvas>\n <local:TwoListControl.StyleForCanvas>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"Canvas.Left\" Value=\"{Binding X}\"/>\n <Setter Property=\"Canvas.Top\" Value=\"{Binding Y}\"/>\n </Style>\n </local:TwoListControl.StyleForCanvas>\n </local:TwoListControl>\n </Grid>\n</Window>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5326068/" ]
74,584,690
<p>In my <code>nodeJs</code> code I make a REST call to a 3rd party api and one of the values in the response is a string value e.g:</p> <pre><code> &quot;total&quot;: &quot;-15&quot; </code></pre> <p>Note that this value can either be a negative number, zero or a positive number, but as a string.</p> <p>e.g:</p> <pre><code> &quot;total&quot;: &quot;-5&quot; &quot;total&quot;: &quot;0&quot; &quot;total&quot;: &quot;+3&quot; </code></pre> <p>How can I convert this value to be as follows? Based off the above example:</p> <pre><code> 5 under level par 3 over </code></pre> <p>I am quite new to <code>node/javascript</code> - is <code>regex</code> the best option to do this?</p>
[ { "answer_id": 74584791, "author": "Yasio", "author_id": 9488284, "author_profile": "https://Stackoverflow.com/users/9488284", "pm_score": 2, "selected": false, "text": "const toText = (value) => {\n const parsed = parseInt(value)\n return parsed > 0 ? `${parsed} over` : parsed < 0 ? `${Math.abs(parsed)} under` : 'level par';\n}\n\nconsole.log(toText(\"-5\"));\nconsole.log(toText(\"0\"));\nconsole.log(toText(\"+3\"));" }, { "answer_id": 74584846, "author": "kayahr", "author_id": 274473, "author_profile": "https://Stackoverflow.com/users/274473", "pm_score": 0, "selected": false, "text": "const toText = v => v == 0 ? \"level par\" : v < 0 ? `${-v} under` : `${+v} over`;\n\nconsole.log(toText(\"-5\"));\nconsole.log(toText(\"0\"));\nconsole.log(toText(\"+3\"));\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12268910/" ]
74,584,693
<p>I am aware that it is discouraged to plot 2 separate y-axes on a single plot, and that it can be confusing and misleading.</p> <p>Is there a way to match the values of the Y axis ? Such as finding a way to shift the right Y axis data within the graph (?) For example, I would like 40 in the left Y axis to match -1 in the right Y axis, because those two values correspond to the beginning of drought conditions categories.</p> <p><a href="https://i.stack.imgur.com/rFmft.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rFmft.png" alt="enter image description here" /></a></p> <p>Sample:</p> <pre><code>structure(list(Time = structure(c(9862, 9893, 9921, 9952, 9982, 10013, 10043, 10074, 10105, 10135, 10166, 10196, 10227, 10258, 10286, 10317, 10347, 10378, 10408, 10439), class = &quot;Date&quot;), Year = c(1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1997, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998), VCI = c(48.7488482440362, 51.8662335250972, 54.4212125411374, 61.7338808190779, 63.9870065731148, 61.3375357670741, 62.6197335631611, 63.0950799644754, 61.6276947895731, 61.1298324406371, 64.4422427513358, 60.3823204404222, 60.5883337239537, 61.8918834440238, 59.1304135098709, 62.1668350554954, 61.9352586665065, 55.75795384214, 50.3371363875305, 52.5748728440737), TCI = c(53.7071192239754, 53.6178820221828, 57.7831310561669, 57.3996088686986, 49.8613200877384, 54.9673093834738, 42.4962626269047, 33.542249807155, 36.9526033996693, 46.0464770178552, 49.5240246297537, 49.6298842520857, 47.9889200846868, 40.3862301499032, 36.8605803231892, 38.8799158911488, 39.0120455451407, 45.9071510330717, 55.8730250709158, 60.4339176493461), SPEI = c(0.385767341805337, -0.240467091114443, 0.218601001011986, 0.392296211626228, -0.0041472667529566, 0.36089672045203, -0.415596363086708, -0.694577131096395, -0.53422184521265, 0.372791671097943, 0.0714646484375678, 0.100567550879492, 0.484279813014397, -0.478876226785371, -0.591222448288627, -0.473201395390211, -0.347352514594038, -0.432571106796894, -0.259775061906046, 0.114961224539346)), row.names = c(NA, 20L), class = &quot;data.frame&quot;) </code></pre> <p>Here is the code:</p> <pre><code>## Plot first set of data and draw its axis par(mar = c(5, 5, 4, 4)) #VCI index plot(variables$Time, variables$VCI, pch=20, cex=.9, axes=FALSE, ylim=c(0,100), xlab=&quot;&quot;, ylab=&quot;&quot;, type=&quot;l&quot;,col=&quot;Aquamarine3&quot;, main=&quot;Temporal trend - drought indices, growing season&quot;) axis(2, ylim=c(0,100),col=&quot;black&quot;,las=1) ## las=1 makes horizontal labels mtext(&quot;VCI and TCI&quot;,side=2,line=2.5) box() abline(h = 40, col = &quot;black&quot;, lty = &quot;dotted&quot;, lwd= 2) ## Allow a second plot on the same graph par(new=TRUE) #TCI index plot(variables$Time, variables$TCI, pch=21, cex = 1.2, axes=FALSE, ylim=c(0,100), xlab=&quot;&quot;, ylab=&quot;&quot;, type=&quot;l&quot;,col=&quot;Chocolate2&quot;, main=&quot;Temporal trend - drought indices, growing season&quot;) axis(2, ylim=c(0,100),col=&quot;grey&quot;,las=1) ## las=1 makes horizontal labels mtext(&quot;VCI and TCI&quot;,side=2,line=2.5) box() ## Allow a second plot on the same graph par(new=TRUE) ## Plot the second plot and put axis scale on right plot(variables$Time, variables$SPEI, pch=15, cex=.4, xlab=&quot;&quot;, ylab=&quot;&quot;, ylim=c(-2.5,2.5), axes=FALSE, type=&quot;l&quot;, col=&quot;darkorchid3&quot;) abline(h = -1.5, col = &quot;black&quot;, lty = &quot;dashed&quot;, lwd= 2) ## a little farther out (line=4) to make room for labels mtext(&quot;SPEI&quot;,side=4,line=2.5) axis(4, ylim=c(-2.5, 2.5), col=&quot;black&quot;,col.axis=&quot;black&quot;,las=1) par(new=TRUE) ## Draw the time axis axis(1, spei.df$Time, format(spei.df$Time, &quot;%Y&quot;), 20) mtext(&quot;Time&quot;,side=1,col=&quot;black&quot;,line=2.5) ## Add Legend legend(&quot;topleft&quot;,legend=c(&quot;VCI&quot;,&quot;TCI&quot;, &quot;SPEI&quot;), text.col=c(&quot;black&quot;,&quot;black&quot;, &quot;black&quot;), lty=1, lwd=2, col=c(&quot;Aquamarine3&quot;,&quot;Chocolate2&quot;, &quot;darkorchid3&quot;)) </code></pre>
[ { "answer_id": 74585813, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 2, "selected": true, "text": "library(tidyverse)\n\ndat |>\n mutate(SPEI = (SPEI+(25/15))*15)|>\n pivot_longer(VCI:SPEI) |>\n mutate(name = factor(name, levels = c(\"VCI\", \"TCI\", \"SPEI\"))) |>\n ggplot(aes(Time, value, color = name))+\n geom_line()+\n geom_hline(linetype = \"dotted\", yintercept = 40)+ \n geom_hline(linetype = \"dashed\", yintercept = 2.5)+\n scale_color_manual(values = c(\"Aquamarine3\", \"Chocolate2\", \"darkorchid3\"))+\n scale_y_continuous(name = \"VCI and TCI\", \n breaks = seq(0, 100, by = 20),\n limits = c(0, 100),\n sec.axis = sec_axis(trans = ~(./15)-(25/15), name = \"SPEI\", \n breaks = seq(-2,5, by = 1)))+\n ggtitle(\"Temporal trend - drought indices, growing season\")+\n labs(color = \"\")+\n theme(panel.background = element_blank(),\n panel.border = element_rect(fill = NA, color = \"black\"),\n legend.key = element_blank(),\n legend.box.background = element_rect(fill = NA, color = \"black\"),\n legend.position = c(0.07,0.87),\n legend.title = element_blank())\n library(tidyverse)\n\ndat |>\n mutate(SPEI = ((SPEI+(55/15))*15))|>\n pivot_longer(VCI:SPEI) |>\n mutate(name = factor(name, levels = c(\"VCI\", \"TCI\", \"SPEI\"))) |>\n ggplot(aes(Time, value, color = name))+\n geom_line()+\n geom_hline(linetype = \"dotted\", yintercept = 40)+ \n geom_hline(linetype = \"dashed\", yintercept = 32.5)+\n scale_color_manual(values = c(\"Aquamarine3\", \"Chocolate2\", \"darkorchid3\"))+\n scale_y_continuous(name = \"VCI and TCI\", \n breaks = seq(0, 100, by = 20),\n limits = c(0, 100),\n sec.axis = sec_axis(trans = ~(./15)-(55/15), name = \"SPEI\", \n breaks = seq(-4,3, by = 1)))+\n ggtitle(\"Temporal trend - drought indices, growing season\")+\n labs(color = \"\")+\n theme(panel.background = element_blank(),\n panel.border = element_rect(fill = NA, color = \"black\"),\n legend.key = element_blank(),\n legend.box.background = element_rect(fill = NA, color = \"black\"),\n legend.position = c(0.07,0.87),\n legend.title = element_blank())\n" }, { "answer_id": 74592658, "author": "tpetzoldt", "author_id": 3677576, "author_profile": "https://Stackoverflow.com/users/3677576", "pm_score": 0, "selected": false, "text": "ya yb ya yb yb ## create a few random test data\nset.seed(123)\nx <- 1:10\nya <- runif(x, min = 20, max = 70)\nyb <- runif(x, min = -1.5, max= 1)\n\n## set limits for the two y axes, but omit yb_max\nya_min <- 0; ya_max <- 100; yb_min <- -3\n\n## set value, where the two axes should match\nya_match <- 40; yb_match <- -1\n\n## calculate yb_max using linear interpolation (here: extrapolation)\nyb_max <- yb_min + (ya_max - ya_min) * (yb_match - yb_min) / (ya_match - ya_min)\n\n## set graphical parameter to increase margin for right axis\npar(mar=c(5, 4, 5, 5) + .1)\n\n## plot data set \"a\" \nplot(x, ya, type = \"l\", col = \"black\", ylim = c(ya_min, ya_max))\nabline(h = ya_match, col = \"grey\", lty = \"dashed\")\n\n## add a second plot for data set \"b\", omitting axes and axis labels\npar(new = TRUE)\nplot(x, yb, type = \"l\", col = \"red\", ylim = c(yb_min, yb_max),\n axes = FALSE, xlab = \"\", ylab = \"\")\n\n## add right axis and axis label\naxis(4)\nmtext(\"yb\", side = 4, line = 3, col = \"red\")\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964076/" ]
74,584,717
<p>I need to instantiate an object using iterable with multiple objects inside. I have to create another method to do it</p> <pre><code>class MyClass: def __init__(self, *args): self.args = args def instantiate_from_iterable #some clever code </code></pre> <p>I need to have a result like this</p> <pre><code>MyClass.instantiate_from_iterable([1, 5, 3]) == MyClass(1, 5, 3) MyClass.instantiate_from_iterable((3, 1, 7)) == MyClass(3, 1, 7) </code></pre> <p>I have no idea how to do this. If someone could help, I would appreciate it very much!</p>
[ { "answer_id": 74584760, "author": "Grzegorz Skibinski", "author_id": 11610186, "author_profile": "https://Stackoverflow.com/users/11610186", "pm_score": 2, "selected": false, "text": "classmethod from collections.abc import Iterable\n\nclass MyClass:\n def __init__(self, *args):\n self.args = args\n \n @classmethod\n def instantiate_from_iterable(cls, args: Iterable):\n return cls(*args)\n\n \na = MyClass(1, 5, 7)\nb = MyClass.instantiate_from_iterable([1, 5, 7])\n \nprint(a.args) # -> (1, 5, 7)\nprint(b.args) # -> (1, 5, 7)\n" }, { "answer_id": 74584775, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "class MyClass:\n\n def __init__(self, *args):\n self.args = args\n\n \n def __eq__(self, other):\n if not isinstance(other, MyClass):\n return False\n else:\n return self.args == other.args\n\nassert MyClass(1, 5, 3) == MyClass(*[1, 5, 3]) \n * __eq__" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20608809/" ]
74,584,719
<p>I'm trying to add a variable to a className and need to append a percentage for it to work. For example the following works:</p> <pre><code>className=&quot;scale-x-[35%]&quot; </code></pre> <p>But the following doesn't:</p> <pre><code>className={`scale-x-[${variableNumber}%]`} </code></pre> <p>What would be the correct way to append the percentage string to my variable?</p> <p><strong>Edit: Full code</strong></p> <pre><code>export default function proposalDetail() { const [percentage1, setPercentage1] = useState(10); const [percentage2, setPercentage2] = useState(35); return ( &lt;div className=&quot;relative p-4 my-4 overflow-hidden border border-gray-200 rounded-lg hover:border-indigo-500&quot;&gt; &lt;div className={`scale-x-${percentage1}% absolute inset-0 w-full origin-top-left bg-indigo-500 bg-opacity-50`}&gt;&lt;/div&gt; &lt;div className=&quot;relative text-black z-100 dark:text-white&quot;&gt; &lt;div className=&quot;font-medium&quot;&gt;0% burn, 2.5% revenue&lt;/div&gt; &lt;div className=&quot;text-sm&quot;&gt;23 voters&lt;/div&gt; &lt;div className=&quot;text-sm&quot;&gt;295.7513474746361 QNTFI ({percentage1}%)&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) </code></pre>
[ { "answer_id": 74584865, "author": "Karim Elghamry", "author_id": 10853255, "author_profile": "https://Stackoverflow.com/users/10853255", "pm_score": -1, "selected": false, "text": "10 scale className={`scale-x-[${percentage1}]`}\n 0 1" }, { "answer_id": 74586856, "author": "Ed Lucas", "author_id": 287476, "author_profile": "https://Stackoverflow.com/users/287476", "pm_score": 2, "selected": true, "text": "className={`scale-x-${percentage1}% ...`} percentage1 percentage2 style <div style={{transform: `scaleX(${percentage1/100})`}} className=\"absolute inset-0 w-full origin-top-left bg-indigo-500 bg-opacity-50\"></div>\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15018688/" ]
74,584,726
<p>I want to find duplicate directories from a list of dictionaries and delete one of them but it's generating an error. name, age, group only all 3 should be same values to take it as duplicate dictionary. Without append to a new list of dictionaries</p> <pre><code>a = [ {&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 21,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:0}, {&quot;name&quot;: &quot;Mark&quot;, &quot;age&quot;: 5,&quot;group&quot;:&quot;sdo&quot;,&quot;points&quot;:0}, {&quot;name&quot;: &quot;Pam&quot;, &quot;age&quot;: 7,&quot;group&quot;:&quot;spp&quot;,&quot;points&quot;:0}, {&quot;name&quot;: &quot;Tom&quot;, &quot;age&quot;: 21,&quot;group&quot;:&quot;sdd&quot;,&quot;points&quot;:0}, {&quot;name&quot;: &quot;Buke&quot;, &quot;age&quot;: 31,&quot;group&quot;:&quot;pool&quot;,&quot;points&quot;:0} ] print(a) for i in range(len(a)): for j in range(i+1,len(a)): if a[i] == a[j]: a.pop[j] print(a) </code></pre>
[ { "answer_id": 74584766, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 2, "selected": false, "text": "dict tuple set list dict a = [\n {\"name\": \"Tom\", \"age\": 21,\"group\":\"sdd\",\"points\":0},\n {\"name\": \"Mark\", \"age\": 5,\"group\":\"sdo\",\"points\":0},\n {\"name\": \"Pam\", \"age\": 7,\"group\":\"spp\",\"points\":0},\n {\"name\": \"Tom\", \"age\": 21,\"group\":\"sdd\",\"points\":0},\n {\"name\": \"Buke\", \"age\": 31,\"group\":\"pool\",\"points\":0}\n]\n\na_new = list(map(dict, set(tuple(dct.items()) for dct in a)))\nprint(a_new)\n [{'name': 'Mark', 'age': 5, 'group': 'sdo', 'points': 0},\n {'name': 'Tom', 'age': 21, 'group': 'sdd', 'points': 0},\n {'name': 'Buke', 'age': 31, 'group': 'pool', 'points': 0},\n {'name': 'Pam', 'age': 7, 'group': 'spp', 'points': 0}]\n a = list(set(a)) a a" }, { "answer_id": 74584778, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "a = [\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Mark\", \"age\": 5, \"group\": \"sdo\", \"points\": 0},\n {\"name\": \"Pam\", \"age\": 7, \"group\": \"spp\", \"points\": 0},\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n\nout, seen = [], set()\nfor d in a:\n tpl = d[\"name\"], d[\"age\"], d[\"group\"]\n if tpl not in seen:\n seen.add(tpl)\n out.append(d)\n\nprint(out)\n [\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Mark\", \"age\": 5, \"group\": \"sdo\", \"points\": 0},\n {\"name\": \"Pam\", \"age\": 7, \"group\": \"spp\", \"points\": 0},\n {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20095556/" ]
74,584,770
<p>I'm trying to build a login form, and one of the fields accepts both email and text(username). What type should I use for my input?</p>
[ { "answer_id": 74584766, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 2, "selected": false, "text": "dict tuple set list dict a = [\n {\"name\": \"Tom\", \"age\": 21,\"group\":\"sdd\",\"points\":0},\n {\"name\": \"Mark\", \"age\": 5,\"group\":\"sdo\",\"points\":0},\n {\"name\": \"Pam\", \"age\": 7,\"group\":\"spp\",\"points\":0},\n {\"name\": \"Tom\", \"age\": 21,\"group\":\"sdd\",\"points\":0},\n {\"name\": \"Buke\", \"age\": 31,\"group\":\"pool\",\"points\":0}\n]\n\na_new = list(map(dict, set(tuple(dct.items()) for dct in a)))\nprint(a_new)\n [{'name': 'Mark', 'age': 5, 'group': 'sdo', 'points': 0},\n {'name': 'Tom', 'age': 21, 'group': 'sdd', 'points': 0},\n {'name': 'Buke', 'age': 31, 'group': 'pool', 'points': 0},\n {'name': 'Pam', 'age': 7, 'group': 'spp', 'points': 0}]\n a = list(set(a)) a a" }, { "answer_id": 74584778, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "a = [\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Mark\", \"age\": 5, \"group\": \"sdo\", \"points\": 0},\n {\"name\": \"Pam\", \"age\": 7, \"group\": \"spp\", \"points\": 0},\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n\nout, seen = [], set()\nfor d in a:\n tpl = d[\"name\"], d[\"age\"], d[\"group\"]\n if tpl not in seen:\n seen.add(tpl)\n out.append(d)\n\nprint(out)\n [\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Mark\", \"age\": 5, \"group\": \"sdo\", \"points\": 0},\n {\"name\": \"Pam\", \"age\": 7, \"group\": \"spp\", \"points\": 0},\n {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15611155/" ]
74,584,790
<p>I am quite new to R. I have few text (.txt) files in a folder that have been converted from PDF with page break character (#12). I need to produce a data frame by reading these text files in R with condition that one row in R represents one PDF page. It means that every time there is a page break (\f), it will only then create a new row.</p> <p>The problem is when the text file gets load into R, every new line became a new row and I do not want this. Please assist me on this. Thanks!</p> <p>Some methods that I have tried are read.table and readLines.</p> <p><a href="https://i.stack.imgur.com/6ZbiP.png" rel="nofollow noreferrer">As you can see in lines 273 &amp; 293, there is \f, so I need whatever that comes after \f to be in a row (which represents a page)</a></p>
[ { "answer_id": 74584845, "author": "dcsuka", "author_id": 19512611, "author_profile": "https://Stackoverflow.com/users/19512611", "pm_score": 1, "selected": true, "text": "library(tidyverse)\nread_file(\"mytxt.txt\") %>%\n str_split(\"␌\") %>%\n unlist() %>%\n as_tibble_col(\"data\")\n" }, { "answer_id": 74584882, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": false, "text": "vec <- c(\"a\",\"b\",\"\\fd\",\"e\",\"\\ff\",\"g\")\n# vec <- readLines(\"file.txt\")\nout <- data.frame(page = sapply(split(vec, cumsum(grepl(\"^\\f\", vec))), paste, collapse = \"\\n\"))\nout\n# page\n# 0 a\\nb\n# 1 \\fd\\ne\n# 2 \\ff\\ng\n \\f out$page <- sub(\"^\\f\", \"\", out$page)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12190512/" ]
74,584,803
<p>I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error:</p> <p>(The view post.views.view didn't return an HttpResponse object. It returned None instead.)</p> <p>views</p> <pre><code>class PostDetailView(View): &quot;&quot;&quot;see detail post&quot;&quot;&quot; def get(self, request, post_id, post_slug): post = Post.objects.get(pk=post_id, slug=post_slug) return render(request, &quot;post/detail.html&quot;, {&quot;post&quot;: post}) class PostCreateView(LoginRequiredMixin, View): form_class = PostCreateUpdateForm def get(self, request, *args, **kwargs): form = self.form_class return render(request, &quot;post/create.html&quot;, {&quot;form&quot;: form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.slug = slugify(form.cleaned_data[&quot;body&quot;][:20]) new_post.user = request.user new_post.save() messages.success(request, &quot;you created a new post&quot;, &quot;success&quot;) return redirect(&quot;post:post-detail&quot;, new_post.id, new_post.slug) </code></pre> <p>models</p> <pre><code>class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() slug = models.SlugField() img = models.ImageField(upload_to=&quot;%Y/%m/%d/&quot;) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) </code></pre> <p>urls</p> <pre><code>app_name = 'post' urlpatterns = [ path('', views.BlogView.as_view(), name=&quot;home&quot;), path('detail/&lt;int:post_id&gt;/&lt;slug:post_slug&gt;/', views.PostDetailView.as_view(), name=&quot;post-detail&quot;), path('delete/&lt;int:post_id&gt;/', views.PostDeleteView.as_view(), name=&quot;post-delete&quot;), path('update/&lt;int:post_id&gt;/', views.PostUpdateView.as_view(), name=&quot;post-update&quot;), path('create/', views.PostCreateView.as_view(), name=&quot;post-create&quot;), ] </code></pre>
[ { "answer_id": 74584845, "author": "dcsuka", "author_id": 19512611, "author_profile": "https://Stackoverflow.com/users/19512611", "pm_score": 1, "selected": true, "text": "library(tidyverse)\nread_file(\"mytxt.txt\") %>%\n str_split(\"␌\") %>%\n unlist() %>%\n as_tibble_col(\"data\")\n" }, { "answer_id": 74584882, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": false, "text": "vec <- c(\"a\",\"b\",\"\\fd\",\"e\",\"\\ff\",\"g\")\n# vec <- readLines(\"file.txt\")\nout <- data.frame(page = sapply(split(vec, cumsum(grepl(\"^\\f\", vec))), paste, collapse = \"\\n\"))\nout\n# page\n# 0 a\\nb\n# 1 \\fd\\ne\n# 2 \\ff\\ng\n \\f out$page <- sub(\"^\\f\", \"\", out$page)\n" } ]
2022/11/26
[ "https://Stackoverflow.com/questions/74584803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17601745/" ]