qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,367,322
<ul> <li><p><em>Task:</em> count the number of operations required to make an array's values alternate between even and odd.</p> </li> <li><p><em>Given:</em> items = [6, 5, 9, 7, 3] (Example test case)</p> </li> <li><p><em>Operations we can do:</em> make n number of operations: floor(item/2)</p> </li> </ul> <p>My code</p> <pre><code>def change(expected): return 1 if (expected == 0) else 0 def getMinimumOperations(items, expected): countOp = 0 for i in items: if (int(i % 2 == 0) != expected): countOp += 1 expected = change(expected) return countOp def minChangeToGetMinOp(items): minStack = [getMinimumOperations(items, 1), getMinimumOperations(items, 0)] return min(minStack) if __name__ == &quot;__main__&quot;: items = [6, 5, 9, 7, 3] print(minChangeToGetMinOp(items)) </code></pre> <p>ANS: 3</p> <p>What I'm asking: A good approach to solve this</p>
[ { "answer_id": 74367243, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 1, "selected": false, "text": "std::move_backwards" }, { "answer_id": 74368006, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 3, "selected": true, "text": "std::deque" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6640284/" ]
74,367,330
<p>I have this draggable div which automatically positions correctly when window is being re-sized from left or top. I want it to do the same thing from right and bottom as well so it is still visible.</p> <p>Can this be done with just css? or do I need to use javascript? can someone please show me how.</p> <p><a href="https://i.stack.imgur.com/RJbGY.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJbGY.gif" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt; &lt;style&gt; #box { position: fixed; background: red; width: 10%; height: 10%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="box"&gt; &lt;/div&gt; &lt;script&gt; //Make the DIV element draggagle: dragElement(document.getElementById("box")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { /* if present, the header is where you move the DIV from:*/ document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } else { /* otherwise, move the DIV from anywhere inside the DIV:*/ elmnt.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); // calculate the new cursor position: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } } &lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74367712, "author": "Jack Brown", "author_id": 20415519, "author_profile": "https://Stackoverflow.com/users/20415519", "pm_score": -1, "selected": false, "text": "<head>\n <style>\n #box {\n position: sticky;\n background: red;\n width: 10vw;\n height: 10vh;\n }\n </style>\n \n</head>\n\n<body>\n\n <div id=\"box\"> </div>\n\n <script>\n //Make the DIV element draggagle:\n dragElement(document.getElementById(\"box\"));\n\n function dragElement(elmnt) {\n var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;\n if (document.getElementById(elmnt.id + \"header\")) {\n /* if present, the header is where you move the DIV from:*/\n document.getElementById(elmnt.id + \"header\").onmousedown = dragMouseDown;\n } else {\n /* otherwise, move the DIV from anywhere inside the DIV:*/\n elmnt.onmousedown = dragMouseDown;\n }\n\n function dragMouseDown(e) {\n e = e || window.event;\n e.preventDefault();\n // get the mouse cursor position at startup:\n pos3 = e.clientX;\n pos4 = e.clientY;\n document.onmouseup = closeDragElement;\n // call a function whenever the cursor moves:\n document.onmousemove = elementDrag;\n }\n\n function elementDrag(e) {\n e = e || window.event;\n e.preventDefault();\n // calculate the new cursor position:\n pos1 = pos3 - e.clientX;\n pos2 = pos4 - e.clientY;\n pos3 = e.clientX;\n pos4 = e.clientY;\n // set the element's new position:\n elmnt.style.top = (elmnt.offsetTop - pos2) + \"px\";\n elmnt.style.left = (elmnt.offsetLeft - pos1) + \"px\";\n }\n\n function closeDragElement() {\n /* stop moving when mouse button is released:*/\n document.onmouseup = null;\n document.onmousemove = null;\n }\n }\n </script>\n</body>" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14560631/" ]
74,367,390
<p>I'm currently sitting in Jupyter Notebook on a dataset that has a duration column that looks like this;</p> <p><a href="https://i.stack.imgur.com/7wuBe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7wuBe.jpg" alt="enter image description here" /></a></p> <p>I still feel like a newbie at programming at programming, so i'm not sure to convert this data so it can be visualized in graphs in jupyter. Right now its just all strings in the column. Does anyone knows how i do this right?</p> <p>Thank you!</p>
[ { "answer_id": 74367837, "author": "Jimpsoni", "author_id": 18195201, "author_profile": "https://Stackoverflow.com/users/18195201", "pm_score": 0, "selected": false, "text": "from datetime import timedelta\nimport re\n\nstring = \"1 hour 35 mins\" # Example from dataset\n\n# Extract numbers with regex\nnumbers = list(map(int, re.findall(r'\\d+', string))) \n\n# Create timedelta object from those numbers\nif len(numbers) < 2:\n time = timedelta(minutes=numbers[0])\nelse:\n time = timedelta(hours=numbers[0], minutes=numbers[1])\n\nprint(time) # -> prints 1:35:00\n" }, { "answer_id": 74368260, "author": "user19077881", "author_id": 19077881, "author_profile": "https://Stackoverflow.com/users/19077881", "pm_score": 1, "selected": false, "text": "from dateutil import parser\n\ns = \"1 hour 35 mins\"\nprint(s)\n\ns = s.replace('min', 'minute')\ntime = parser.parse(s).time()\nprint(time)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367961/" ]
74,367,418
<p>In SQL Server, I am trying to obtain the values between the second and third forward slash (<code>/</code>) character. The length of the numbers can vary so <code>substring(column, 8, 10)</code> wouldn't work.</p> <pre><code>123/123/123456789/12 </code></pre> <p>What I am trying to get in the current example is: 123456789</p>
[ { "answer_id": 74367524, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 2, "selected": false, "text": "Declare @YourTable table (ID int,SomeCol varchar(50))\nInsert Into @YourTable values \n (1,'123/123/123456789/12')\n\nSelect A.ID\n ,Pos3 = JSON_VALUE(JS,'$[2]')\n From @YourTable A\n Cross Apply (values ('[\"'+replace(SomeCol,'/','\",\"')+'\"]') ) B(JS)\n" }, { "answer_id": 74367527, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 2, "selected": false, "text": "-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(100));\nINSERT @tbl (tokens) VALUES\n('123/123/123456789/12'),\n('123/123/9876543210/12');\n-- DDL and sample data population, end\n\nDECLARE @separator CHAR(1) = '/';\n\nSELECT t.* \n , ThirdToken = c.value('(/root/r[position() eq 3]/text())[1]', 'VARCHAR(100)')\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(tokens, @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c);\n" }, { "answer_id": 74367567, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 3, "selected": true, "text": "declare @string varchar(50) = '123/123/123456789/12';\n\nselect ParseName(Replace(@string,'/','.'),2);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18942652/" ]
74,367,422
<p>I have a large table that I'm wanting to select 8 columns out of. I would be comparing it to another table with 2 columns making sure they (said columns) match exactly.</p> <p>Pseudo Code:</p> <pre><code>SELECT a, b, c, d, e, f, g, h, i FROM table1 t1 WHERE a AND b are matching the same rows in table 2 </code></pre> <p>I've done this with a similar example, but only had 1 column in table 2 instead of 2 like so:</p> <pre><code>SELECT a, b, c, d, e, f, g, h, i FROM table t1 WHERE a IN (SELECT * FROM table2 t2) </code></pre> <p>which gives me the results. But again, I now need to make sure that a AND b match the corresponding rows from table2. I've been searching but cannot find a solution. I've tried INNER JOINS, but I'm getting more results than there should be. Any help would be greatly appreciated as SQL is definitely not my wheelhouse. Also if there are any other clarifications, please let me know.</p> <p>I think this is simple enough of a question, I hope. Thanks in advance!</p> <p>In response to the comment:</p> <p>Table 1 (has 20 million rows)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Address</th> <th>Zip</th> <th>Year</th> <th>Area</th> <th>Name1</th> <th>Name2</th> <th>example</th> <th>example</th> </tr> </thead> <tbody> <tr> <td>123 Main St</td> <td>77777</td> <td>1999</td> <td>2000</td> <td>John Doe</td> <td>John Smith</td> <td>data</td> <td>data</td> </tr> <tr> <td>456 Main St</td> <td>88888</td> <td>2012</td> <td>2500</td> <td>James Doe</td> <td>John Smith</td> <td>data</td> <td>data</td> </tr> <tr> <td>789 Main St</td> <td>99999</td> <td>2018</td> <td>2800</td> <td>Michael Doe</td> <td>Michelle Doe</td> <td>data</td> <td>data</td> </tr> </tbody> </table> </div> <p>Table 2 (has 7500 rows):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Address</th> <th>Zip</th> </tr> </thead> <tbody> <tr> <td>123 Main St</td> <td>77777</td> </tr> <tr> <td>321 Smith St</td> <td>66666</td> </tr> <tr> <td>789 Main St</td> <td>99999</td> </tr> <tr> <td>455 Highway 1</td> <td>44444</td> </tr> </tbody> </table> </div> <p>Results would be expected (7500 rows)</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Address</th> <th>Zip</th> <th>Year</th> <th>Area</th> <th>Name1</th> <th>Name2</th> <th>example</th> <th>example</th> </tr> </thead> <tbody> <tr> <td>123 Main St</td> <td>77777</td> <td>1999</td> <td>2000</td> <td>John Doe</td> <td>John Smith</td> <td>data</td> <td>data</td> </tr> <tr> <td>789 Main St</td> <td>99999</td> <td>2018</td> <td>2800</td> <td>Michael Doe</td> <td>Michelle Doe</td> <td>data</td> <td>data</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74367664, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": false, "text": "table1" }, { "answer_id": 74367692, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "SELECT t1.*\nFROM Table1 t1\nINNER JOIN Table2 t2 on t1.a = t2.a and t1.b = t2.b\n" }, { "answer_id": 74379856, "author": "Jerome Dela Cruz", "author_id": 19831561, "author_profile": "https://Stackoverflow.com/users/19831561", "pm_score": 0, "selected": false, "text": " SELECT PropertyAddressFull, PropertyAddressZIP, c, d, e, f FROM table1 t1\n INNER JOIN table2 t2 ON (t1.PropertyAddressFull=t2.address AND t1.PropertyAddressZIP=t2.propertyzip) \n WHERE PropertyAddressFull != '' AND PropertyAddressFull IS NOT NULL AND PropertyAddressZIP != '' AND PropertyAddressZIP IS NOT NULL\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19831561/" ]
74,367,450
<p>We have an Azure Data Factory dataflow, it will sink into Delta. We have Owerwrite, Allow Insert options set and Vacuum = 1. When we run the pipeline over and over with no change in the table structure pipeline is successfull. But when the table structure being sinked changed, ex data types changed and such the pipeline fails with below error.</p> <p>Error code: DFExecutorUserError Failure type: User configuration issue</p> <p>Details: Job failed due to reason: at Sink 'ConvertToDelta': Job aborted.</p> <p><a href="https://i.stack.imgur.com/NW0WV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NW0WV.png" alt="enter image description here" /></a></p> <p>We tried setting Vacuum to 0 and back, Merge Schema set and now, instead of Overwrite Truncate and back and forth, pipeline still failed.</p>
[ { "answer_id": 74367664, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 1, "selected": false, "text": "table1" }, { "answer_id": 74367692, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "SELECT t1.*\nFROM Table1 t1\nINNER JOIN Table2 t2 on t1.a = t2.a and t1.b = t2.b\n" }, { "answer_id": 74379856, "author": "Jerome Dela Cruz", "author_id": 19831561, "author_profile": "https://Stackoverflow.com/users/19831561", "pm_score": 0, "selected": false, "text": " SELECT PropertyAddressFull, PropertyAddressZIP, c, d, e, f FROM table1 t1\n INNER JOIN table2 t2 ON (t1.PropertyAddressFull=t2.address AND t1.PropertyAddressZIP=t2.propertyzip) \n WHERE PropertyAddressFull != '' AND PropertyAddressFull IS NOT NULL AND PropertyAddressZIP != '' AND PropertyAddressZIP IS NOT NULL\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19846846/" ]
74,367,468
<p>I wish to print this data in a table with the columns aligned. I tried with <code>Format</code> but the columns were not aligned. Does anyone know how to do it ? Thank you.</p> <pre><code>((&quot;tiscali&quot; 10000 2.31 0.84 -14700.0 &quot;none&quot;) (&quot;atlantia&quot; 50 22.65 22.68 1.5 &quot;none&quot;) (&quot;bper-banca&quot; 1000 1.59 2.01 423.0 &quot;none&quot;) (&quot;alerion-cleanpower&quot; 30 44.14 36.45 -230.7 &quot;none&quot;) (&quot;tesmec&quot; 10000 0.12 0.14 150.0 &quot;none&quot;) (&quot;cover-50&quot; 120 8.95 9.6 78.0 &quot;none&quot;) (&quot;ovs&quot; 1000 1.71 1.93 217.0 &quot;none&quot;) (&quot;credito-emiliano&quot; 200 5.7 6.26 112.0 &quot;none&quot;)) </code></pre> <p>I tried to align the columns wit the ~T directive, no way. Is there a piece of code that prints nicely table data?</p>
[ { "answer_id": 74371020, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 3, "selected": true, "text": "(defparameter *data* \n '((\"tiscali\" 10000 2.31 0.84 -14700.0 \"none\")\n (\"atlantia\" 50 22.65 22.68 1.5 \"none\")\n (\"bper-banca\" 1000 1.59 2.01 423.0 \"none\")\n (\"alerion-cleanpower\" 30 44.14 36.45 -230.7 \"none\")\n (\"tesmec\" 10000 0.12 0.14 150.0 \"none\")\n (\"cover-50\" 120 8.95 9.6 78.0 \"none\")\n (\"ovs\" 1000 1.71 1.93 217.0 \"none\")\n (\"credito-emiliano\" 200 5.7 6.26 112.0 \"none\")))\n" }, { "answer_id": 74387893, "author": "coredump", "author_id": 124319, "author_profile": "https://Stackoverflow.com/users/124319", "pm_score": 0, "selected": false, "text": "(defpackage :tabular (:use :cl)) \n(in-package :tabular) \n \n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440185/" ]
74,367,471
<p>I have a map view, and in another componenet, I would like to be able to have a function that animates that mapview. That function would need a reference to my map view. How can I access my maps reference inside another component?</p> <p>I have a <a href="https://snack.expo.dev/@priedejm/pass-reference-to-component" rel="nofollow noreferrer">snack expo that reproduces my problem exactly here</a> as well as some code below. <strong>Please note which files are classes and which are functions.</strong> The files are too big in my projects, I do not want to change them</p> <p>EDIT: Could I use some sort of state library such as Context to store the ref?</p> <pre><code>export default function App() { return ( &lt;View style={styles.container}&gt; &lt;Map/&gt; &lt;AnimateMapButton/&gt; &lt;/View&gt; ); } </code></pre> <p>I cant access this._map for obvious reasons. How can I access this?</p> <pre><code>export default class AnimateMapButton extends React.Component { goToLocation = () =&gt; { this._map.animateToRegion({ latitude: 103.1561, longitude: -47.1651, latitudeDelta: 0.0025, longitudeDelta: 0.0025, }) } render() { return ( &lt;View style={{height: 75, width: 200, backgroundColor: 'red', position: 'absolute', top: 100}}&gt; &lt;TouchableOpacity onPress={() =&gt; this.goToLocation()}&gt; &lt;Text style={{fontSize: 20, }}&gt;Click to animate the map&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; ); } } </code></pre> <pre><code>export default class Map extends React.Component { render(){ return ( &lt;View style={styles.container}&gt; &lt;MapView style={styles.map} ref={map =&gt; this._map = map} /&gt; &lt;/View&gt; ); } } </code></pre>
[ { "answer_id": 74370867, "author": "vinayr", "author_id": 1427309, "author_profile": "https://Stackoverflow.com/users/1427309", "pm_score": 0, "selected": false, "text": "export default function App() {\n const mapRef = React.useRef();\n\n const goToLocation = () => {\n mapRef.current.animateToRegion({\n latitude: 37.78825,\n longitude: -122.4324,\n latitudeDelta: 0.0922,\n longitudeDelta: 0.0421,\n })\n }\n\n return (\n <View style={styles.container}>\n <Map mapRef={mapRef} />\n <AnimateMapButton goToLocation={goToLocation} />\n </View>\n );\n}\n" }, { "answer_id": 74427627, "author": "Gavara.Suneel", "author_id": 8988448, "author_profile": "https://Stackoverflow.com/users/8988448", "pm_score": 2, "selected": true, "text": "React.forwardRef" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12915212/" ]
74,367,499
<p>I would like to remove the third and fourth last character from as string.</p> <p>Here is some sample data:</p> <pre><code>HS0202 HS0902 MV0100 SUE0300 </code></pre> <p>I would need return something like this</p> <pre><code>HS02 HS02 MV00 SUE00 </code></pre>
[ { "answer_id": 74367575, "author": "shaun_m", "author_id": 18289387, "author_profile": "https://Stackoverflow.com/users/18289387", "pm_score": 3, "selected": true, "text": "have <- c('HS0202', 'HS0902', 'MV0100', 'SUE0300')\n\nwant <- paste0(substring(have,1,nchar(have)-3),substring(have,nchar(have)))\n" }, { "answer_id": 74367582, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 3, "selected": false, "text": "gsub()" }, { "answer_id": 74367830, "author": "AndrewGB", "author_id": 15293191, "author_profile": "https://Stackoverflow.com/users/15293191", "pm_score": 2, "selected": false, "text": "stringi" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19783394/" ]
74,367,513
<p>I want to take streamed IEnumerable values such as: (Tuples shown for illustration purposes. The actual application will be streaming DataRecords from a DataReader)</p> <pre><code>var tuples = new(int, int)[] { (0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), }; </code></pre> <p>I want to maintain state and watch for each change in the left field. Each group of items with the left field in common should be returned as a series of IEnumerables (the data will be pre-sorted so I don't have to worry about collating on the local end).</p> <pre><code>(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (2,0) (2,1) (2,2) </code></pre> <p>It may not be possible, but the hope is to do this without creating any per-group interim Lists that would bank records in RAM because each group will be fairly large. In other words, somehow <strong>get each group to somehow magically siphon from the original IEnumerable</strong> such that it is completely forward-only, one-pass.</p> <p>An inner-TakeWhile <em>seemed</em> like it might be the way to go, but it always restarts the iteration on <code>tg</code> from ground zero.</p> <pre class="lang-c# prettyprint-override"><code> private int currentGroup; public IEnumerator&lt;IEnumerable&lt;Tuple&lt;int, int&gt;&gt;&gt; GetEnumerator() { var tg = TupleGenerator(); foreach (Tuple&lt;int, int&gt; item in tg) { currentGroup = item.Item1; yield return tg.TakeWhile((x) =&gt; x.Item1 == currentGroup); } } static IEnumerable&lt;Tuple&lt;int, int&gt;&gt; TupleGenerator() { for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 10; j++) { yield return new Tuple&lt;int, int&gt;(i,j); } } } </code></pre>
[ { "answer_id": 74367696, "author": "julealgon", "author_id": 1946412, "author_profile": "https://Stackoverflow.com/users/1946412", "pm_score": -1, "selected": false, "text": "GroupAdjacent" }, { "answer_id": 74367952, "author": "Servy", "author_id": 1159478, "author_profile": "https://Stackoverflow.com/users/1159478", "pm_score": 3, "selected": true, "text": "IEnumerable" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112855/" ]
74,367,521
<h2>Background:</h2> <ul> <li>I'm trying to deploy a Django app to the Google App Engine (GAE) standard environment in the python39 runtime</li> <li>The database configuration is stored in a Secret Manager secret version, similar to Google's GAE Django tutorial (<a href="https://cloud.google.com/python/django/appengine" rel="nofollow noreferrer">link</a>)</li> <li>The app is run as a user-managed service account <code>server@myproject.iam.gserviceaccount.com</code>, which has the appropriate permissions to access the secret, as can be confirmed using <code>gcloud secret versions access</code></li> </ul> <h2>Problem:</h2> <ul> <li>In the Django <code>settings.py</code> module, when I try to access the secret using <code>google.cloud.secretmanager.SecretManagerServiceClient.access_secret_version(...)</code>, I get the following <code>CONSUMER_INVALID</code> error:</li> </ul> <pre><code>google.api_core.exceptions.PermissionDenied: 403 Permission denied on resource project myproject. [links { description: &quot;Google developer console API key&quot; url: &quot;https://console.developers.google.com/project/myproject/apiui/credential&quot; } , reason: &quot;CONSUMER_INVALID&quot; domain: &quot;googleapis.com&quot; metadata { key: &quot;service&quot; value: &quot;secretmanager.googleapis.com&quot; } metadata { key: &quot;consumer&quot; value: &quot;projects/myproject&quot; } </code></pre> <h2>My Debugging</h2> <ul> <li>I <em>cannot</em> reproduce the error above <em>outside</em> of GAE; <ul> <li>I can confirm that the SA can access the secret:</li> </ul> </li> </ul> <pre><code>gcloud secrets versions access latest --secret=server_env --project myproject \ --impersonate-service-account=server@myproject.iam.gserviceaccount.com </code></pre> <pre><code>WARNING: This command is using service account impersonation. All API calls will be executed as [server@myproject.iam.gserviceaccount.com]. DATABASE_URL='postgres://django:...' SECRET_KEY='...' </code></pre> <ul> <li><p>I've also confirmed I run the django app locally with service account impersonation and make the above <code>access_secret_version(...)</code> calls</p> </li> <li><p>In desperation I even created an API key for the project and hardcoded it into my <code>settings.py</code> file, and this <em>also</em> raises the same error</p> </li> <li><p>I've confirmed the following settings in the project:</p> <ul> <li>the app is running with using the correct user-managed SA</li> <li>the call to <code>access_secret_version</code> is being made with the correct SA (ie that the credentials are being pulled from the GAE environment correctly)</li> <li>the project has the <code>secretmanager.googleapis.com</code> service enabled, and has billing enabled and the billing account is active</li> </ul> </li> </ul> <p><strong>If you have any suggestions for a configuration or method to help debug this, I'd much appreciate it!</strong></p> <h2>Relevant Code Snippets</h2> <h3><code>app.yaml</code></h3> <pre><code>service_account: server@myproject.iam.gserviceaccount.com runtime: python39 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /_static static_dir: _static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto env_variables: ... inbound_services: - mail - mail_bounce app_engine_apis: true </code></pre> <h3>Service Account Creation &amp; Permissions</h3> <ul> <li>The SA is created with Terraform as below</li> <li>(The SA doesn't have the role <code>roles/secretmanager.secretAccessor</code>, but has an IAM binding directly on the secret itself)</li> </ul> <pre><code>resource &quot;google_service_account&quot; &quot;frontend_server&quot; { project = google_project.project.project_id account_id = &quot;server&quot; display_name = &quot;Frontend Server Service Account&quot; } resource &quot;google_project_iam_member&quot; &quot;frontend_server&quot; { depends_on = [ google_service_account.frontend_server, ] for_each = toset([ &quot;roles/appengine.serviceAgent&quot;, &quot;roles/cloudsql.client&quot;, &quot;roles/cloudsql.instanceUser&quot;, &quot;roles/secretmanager.viewer&quot;, &quot;roles/storage.objectViewer&quot;, ]) project = google_project.project.project_id role = each.key member = &quot;serviceAccount:${google_service_account.frontend_server.email}&quot; } </code></pre> <h3>Django <code>settings.py</code></h3> <p>The relevant sections of the app <code>settings.py</code> are shown below; the <code>access_secret_version</code> raises the</p> <pre><code>import logging import environ from google.cloud import secretmanager import google.auth # Load secrets from secret manager; the client is auth'd by SA IAM policies credentials, project = google.auth.default( scopes=['https://www.googleapis.com/auth/cloud-platform'] ) secretmanager_client = secretmanager.SecretManagerServiceClient(credentials=credentials) # Load the database connection string into the environment secrets = [ f&quot;projects/{GOOGLE_CLOUD_PROJECT}/secrets/server_env/versions/latest&quot;, ] for name in secrets: try: logging.info(f&quot;Reading secret {name} into django settings module...&quot;) payload = secretmanager_client.access_secret_version(name=name).payload.data.decode(&quot;UTF-8&quot;) env.read_env(io.StringIO(payload)) except Exception as e: logging.error(f&quot;Encountered error when accessing secret {name}: {e}&quot;) logging.error(f&quot;Client credentials during error: {secretmanager_client._transport._credentials.__dict__}&quot;) raise e from None </code></pre>
[ { "answer_id": 74367696, "author": "julealgon", "author_id": 1946412, "author_profile": "https://Stackoverflow.com/users/1946412", "pm_score": -1, "selected": false, "text": "GroupAdjacent" }, { "answer_id": 74367952, "author": "Servy", "author_id": 1159478, "author_profile": "https://Stackoverflow.com/users/1159478", "pm_score": 3, "selected": true, "text": "IEnumerable" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2967377/" ]
74,367,526
<p>The relevant data in my dataframe looks as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Datapoint</th> <th>Values</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0.2</td> </tr> <tr> <td>2</td> <td>0.8</td> </tr> <tr> <td>3</td> <td>0.4</td> </tr> <tr> <td>4</td> <td>0.1</td> </tr> <tr> <td>5</td> <td>1.0</td> </tr> <tr> <td>6</td> <td>0.6</td> </tr> <tr> <td>7</td> <td>0.7</td> </tr> <tr> <td>8</td> <td>0.2</td> </tr> <tr> <td>9</td> <td>0.5</td> </tr> <tr> <td>10</td> <td>0.1</td> </tr> </tbody> </table> </div> <p>I am hoping to group the numbers in the Values column into three categories: less than 0.25 as 'low', between 0.25 and 0.75 as middle and greater than 0.75 as high. I want to create a new column which returns 'low', 'middle' or 'high' for each row based off the data in the value column.</p> <p>What I have tried:</p> <pre><code>def categorize_values(&quot;Values&quot;): if &quot;Values&quot; &gt; 0.75: return 'high' elif 'Values' &lt; 0.25: return 'low' else: return 'middle' </code></pre> <p>However this is returning an error for me.</p>
[ { "answer_id": 74367584, "author": "w kooij", "author_id": 19551554, "author_profile": "https://Stackoverflow.com/users/19551554", "pm_score": 0, "selected": false, "text": "def categorize_values(Values):\n if Values > 0.75:\n return 'high'\n elif Values < 0.25:\n return 'low'\n else:\n return 'middle'\n" }, { "answer_id": 74367603, "author": "amance", "author_id": 17142551, "author_profile": "https://Stackoverflow.com/users/17142551", "pm_score": 1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nfrom io import StringIO\n\ndf = pd.read_csv(StringIO('''Datapoint Values\n1 0.2\n2 0.8\n3 0.4\n4 0.1\n5 1.0\n6 0.6\n7 0.7\n8 0.2\n9 0.5\n10 0.1'''), sep='\\t')\n\ndf['category'] = pd.cut(df['Values'], [0, 0.25, 0.75, df['Values'].max()], labels=['low', 'middle', 'high'])\n\n#output\n>>> df\n Datapoint Values category\n0 1 0.2 low\n1 2 0.8 high\n2 3 0.4 middle\n3 4 0.1 low\n4 5 1.0 high\n5 6 0.6 middle\n6 7 0.7 middle\n7 8 0.2 low\n8 9 0.5 middle\n9 10 0.1 low\n" }, { "answer_id": 74367608, "author": "Mehmet Kaan ERKOÇ", "author_id": 15601037, "author_profile": "https://Stackoverflow.com/users/15601037", "pm_score": 1, "selected": true, "text": "def categorize_values(Values):\n if Values > 0.75:\n return 'high'\n elif Values < 0.25:\n return 'low'\n else:\n return 'middle'\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20187301/" ]
74,367,541
<p>I was coding a discord bot and realized I had difficulty parsing messages. I ended up using a double for loop (yuck). What can I do to optimize this code? (this is a far more straightforward version of the code)</p> <pre><code>string = &quot;His name is food&quot; list = [&quot;food&quot;, &quot;numbers&quot;] parsed_string = string.split(&quot; &quot;) print(parced_string) for i in parsed_string: for x in list: if i == x: print(&quot;stop&quot;) </code></pre> <p>How do I optimize this bit of code?</p>
[ { "answer_id": 74367571, "author": "ddastrodd", "author_id": 5656617, "author_profile": "https://Stackoverflow.com/users/5656617", "pm_score": 0, "selected": false, "text": "string = \"His name is food\"\nlist = [\"food\", \"numbers\"]\nparsed_string = string.split(\" \")\nprint(parsed_string)\n\nfor i in parsed_string:\n if i in list:\n print(\"stop\")\n" }, { "answer_id": 74367591, "author": "9769953", "author_id": 9769953, "author_profile": "https://Stackoverflow.com/users/9769953", "pm_score": 1, "selected": false, "text": "string = \"His name is food\"\nmylist = [\"food\", \"numbers\"]\n\nif set(string.split()).intersection(mylist):\n print(\"stop\")\n" }, { "answer_id": 74367632, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 1, "selected": false, "text": "text = \"His name is food\"\nwords = {\"food\", \"numbers\"}\n\nfor word in text.split(' '):\n if word in words:\n print(\"stop\")\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18039764/" ]
74,367,547
<p>Hello I am working on implementing various technical indicators to better understand the algorithms and their implementations; I do not want to use <code>zoo</code> or other pre-packaged algorithms.</p> <p>I want to use <code>data.table</code>.</p> <h1>sample data</h1> <p>Here is the data we are working with:</p> <pre class="lang-r prettyprint-override"><code>set.seed(123) nrows &lt;- 10000 dt &lt;- data.table::data.table( symbol = sample(LETTERS[1:2], 100, replace = TRUE), close = runif(nrows, 0, 100), open = runif(nrows, 0, 100), high = runif(nrows, 0, 100), low = runif(nrows, 0, 100), volume = runif(nrows, 0, 100) ) </code></pre> <h1>sma (simple moving average)</h1> <p>I can calculate the simple moving average (sma) very easily using <code>data.table::frollmean</code>; this is simply the mean of the window:</p> <pre class="lang-r prettyprint-override"><code># calculate simple moving average sma dt[, sma_short := data.table::frollmean(close, n = 30L, algo = &quot;exact&quot;), by = symbol] # another way to do the same thing: dt[, sma_manual_calculation := data.table::frollapply(close, n = 30L, \(x) { return(mean(x)) }), by = symbol] identical(dt$sma_short, dt$sma_manual_calculation) # TRUE </code></pre> <h1>ema (exponential moving average)</h1> <p>The formula I have found for calculating the ema is as shown here: <a href="https://bookdown.org/kochiuyu/technical-analysis-with-r-second-edition2/exponential-moving-average-ema.html" rel="nofollow noreferrer">https://bookdown.org/kochiuyu/technical-analysis-with-r-second-edition2/exponential-moving-average-ema.html</a></p> <p>If anyone has a different formula or this one shown is wrong please let me know and I would love an explanation - I seek to understand the algorithm and the maths behind</p> <p>From what I've understood an exponential moving average is a type of moving average that gives more weight to recent observations.</p> <blockquote> <p>beta = 2 / (n + 1) # the smoothing factor</p> </blockquote> <blockquote> <p>ema_t(P, n) = beta * P_t + beta (1 - beta) * P_(t-1) + beta (1 - beta)^2 * P_(t-2) + ...</p> </blockquote> <blockquote> <p>ema_t(P, n) = beta * P_t + (1 - beta) * ema_(t-1)(P, n)</p> </blockquote> <p>This the formula I've found in a function from the previous link I mentioned above; I made some small modifications for efficiency:</p> <pre class="lang-r prettyprint-override"><code>myEMA &lt;- function (price, n) { # calculate the smoothing coefficient beta beta &lt;- 2 / (n + 1) # pre-allocate the vector with NA values ema &lt;- rep(NA_real_, n - 1) # calculate first value as the average of the sliding window ema[n] &lt;- mean(price[1:n]) for (i in (n + 1):length(price)){ ema[i] &lt;- beta * price[i] + (1 - beta) * ema[i - 1] } return(as.list(ema)) } </code></pre> <h1>question</h1> <p>My question is how would I accomplish this same thing with <code>data.table</code>. I am certain this must be possible with <code>data.table::frollapply</code>.</p> <p>As always with <code>R</code> I would like to stick first to using vectorised operations, avoid for loops (prefer <code>apply</code> family of functions if necessary) and first I want to use <code>data.table</code>.</p> <p>What I seek is to implement the algorithm myself in the most computationally efficient way possible.</p>
[ { "answer_id": 74370167, "author": "dereckdemezquita", "author_id": 14410815, "author_profile": "https://Stackoverflow.com/users/14410815", "pm_score": 0, "selected": false, "text": "data.table::frollapply" }, { "answer_id": 74376350, "author": "Waldi", "author_id": 13513328, "author_profile": "https://Stackoverflow.com/users/13513328", "pm_score": 1, "selected": false, "text": "signal" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14410815/" ]
74,367,620
<p>currently trying to figure this out with code like this..but not quite yet able to get it:</p> <pre><code>df[(df.index.day_of_week==0) &amp; (df.index.day&lt;15) &amp; (df.shift(-4).index.day_of_week==4)] </code></pre> <p>this is what the data looks like. (i've added the day_of_week column for convenience). basically, i am trying to find the first day_of_week=0 (monday) in the month, then filter for the first day_of_week=4 after that (friday)</p> <pre><code> close day_of_week date 2022-07-01 3825.330078 4 2022-07-05 3831.389893 1 2022-07-06 3845.080078 2 2022-07-07 3902.620117 3 2022-07-08 3899.379883 4 2022-07-11 3854.429932 0 2022-07-12 3818.800049 1 2022-07-13 3801.780029 2 2022-07-14 3790.379883 3 2022-07-15 3863.159912 4 ... 2022-08-01 4118.629883 0 2022-08-02 4091.189941 1 2022-08-03 4155.169922 2 2022-08-04 4151.939941 3 2022-08-05 4145.189941 4 2022-08-08 4140.060059 0 2022-08-09 4122.470215 1 2022-08-10 4210.240234 2 2022-08-11 4207.270020 3 2022-08-12 4280.149902 4 ... 2022-09-01 3966.850098 3 2022-09-02 3924.260010 4 2022-09-06 3908.189941 1 2022-09-07 3979.870117 2 2022-09-08 4006.179932 3 2022-09-09 4067.360107 4 2022-09-12 4110.410156 0 2022-09-13 3932.689941 1 2022-09-14 3946.010010 2 2022-09-15 3901.350098 3 2022-09-16 3873.330078 4 ... 2022-10-03 3678.429932 0 2022-10-04 3790.929932 1 2022-10-05 3783.280029 2 2022-10-06 3744.520020 3 2022-10-07 3639.659912 4 2022-10-10 3612.389893 0 2022-10-11 3588.840088 1 2022-10-12 3577.030029 2 ... 2022-11-01 3856.100098 1 2022-11-02 3759.689941 2 2022-11-03 3719.889893 3 2022-11-04 3770.550049 4 2022-11-07 3806.800049 0 2022-11-08 3828.110107 1 </code></pre> <p>This should return:</p> <pre><code>2022-07-15 3863.159912 4 2022-08-05 4145.189941 4 2022-09-16 3873.330078 4 2022-10-07 3639.659912 4 </code></pre> <p>EDIT: while i dont expect this to work, curious as to why this returns no results? is shifting not supported when filtering in this manner</p> <pre><code>df[(df.index.day_of_week==0) &amp; (df.index.day&lt;15) &amp; (df.shift(-4).index.day_of_week==4)] </code></pre>
[ { "answer_id": 74367754, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "day_of_week" }, { "answer_id": 74369161, "author": "bui", "author_id": 8990644, "author_profile": "https://Stackoverflow.com/users/8990644", "pm_score": 1, "selected": false, "text": "[year, month, day_of_week]" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480118/" ]
74,367,634
<p>I have a dataframe with information, where the rows are not related to eachother:</p> <pre><code> Fruits Vegetables Protein 1 Apple Spinach Beef 2 Banana Cucumber Chicken 3 Pear Carrot Pork </code></pre> <p>I essentially just want to create a pandas series with all of that information, I want it to look like this:</p> <pre><code> All Foods 1 Apple 2 Banana 3 Pear 4 Spinach 5 Cucumber 6 Carrot 7 Beef 8 Chicken 9 Pork </code></pre> <p>How can I do this in pandas?</p>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18020970/" ]
74,367,641
<p>We are currently using spring boot 2.7.4 and we want to use a built in dependency of 2.7.5. I added it to the properties in the pom, but its being ignored. I have done this successfully with other dependencies. jackson-databind 2.13.4 is a builtin dependency of spring boot 2.7.4 jackson-databind 2.13.4.2 is a dependency of spring boot 2.7.5</p> <pre><code>&lt;jackson-databind.version&gt;2.13.4.2&lt;/jackson-databind.version&gt; </code></pre> <p>That does not seem to work. Will spring just ignore an incompatible version automatically ?</p>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654460/" ]
74,367,648
<p>When creating a database table in jupyter, we specify restrictions on data types in the columns of the table, but for some reason we can still add other data types. For example, the st_gr column should contain only numbers, but nothing will stop us from adding a line (code below) Why? How to fix?</p> <pre><code>%%sql sqlite:// CREATE TABLE students( st_id INTEGER PRIMARY KEY AUTOINCREMENT, fname VARCHAR(15) NOT NULL, lname VARCHAR(15) NOT NULL, st_gr NUMERIC ) %%sql sqlite:// INSERT INTO students (fname, lname, st_gr) VALUES('Barack', 'Obama', 'text not num') </code></pre>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453934/" ]
74,367,666
<p>I was developing a plugin, using Eclipse IDE for java developers (Version: 2021-09 (4.21.0) Build id: 20210910-1417)</p> <p>During development, when I run it as an eclipse application, it opens a runtime-Eclipse application where the plug-in is present. In my setup this new runtime-eclips app opened from a folder next to the workspace, where C codes were present. (and my progrem would get the tests run in C , and get the results from it's exe)</p> <p>Then I downloaded the Eclipse IDE for committers, which is a newer version. I downloaded it as a zip and after unpacking I run the eclipse.exe. My program had problems opening the runtime-Eclipse application in C there, so i went back to the older one which is installed on my computer.</p> <p>After opening the original eclipse, on which I was working and had no problems, I was hoping everything will be fine. It opens the IDE for java developers (same version, same build) but I have the same problems with the runtime-eclipse application as the one I run as an eclipse.exe , (not recognising the C code?? I don't understand).</p> <p>When i try to run the plug-in I get this error.<a href="https://i.stack.imgur.com/XvCBU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XvCBU.png" alt="error during eclipse plugin run" /></a></p> <p>And when the runtime-app opens i get this error. <a href="https://i.stack.imgur.com/CVrss.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CVrss.png" alt="enter when runtimeapp opens" /></a></p> <p>I cannot create C projects anymore on the runtime-app. I don't know the reason behind this. <a href="https://i.stack.imgur.com/DOtAs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DOtAs.png" alt="C/C++ projects option not present" /></a></p> <p>Also I have billion of these [&quot;java.net.UnknownHostException: downdload.eclipse.ort&quot;] [&quot; org.eclipse.equinox.p2.core.ProvisionException: Unknown Host: http://downdload.eclipse.ort/eclipse/updates/4.2/content.xml &quot;]</p> <p>Thank you in advance!</p> <p>I don't know if it is possible or not, since seemingly it did not update the older eclipse IDE. If it can be restored the way it was before i run the eclipse.exe, I would be happy.</p>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17059494/" ]
74,367,718
<pre><code>let friends = [&quot;Ahmed&quot;, &quot;Sayed&quot;, &quot;Ali&quot;, 1, 2, &quot;Mahmoud&quot;, &quot;Amany&quot;]; let index = 0; let counter = 0; while (index &lt; friends.length) { index++; if ( typeof friends[index] === &quot;number&quot; &amp;&amp; friends[index] == friends[index].startsWith(&quot;a&quot;.toUpperCase()) ) { continue; } console.log(friends[index]); } </code></pre> <p>what's wrong with my code i get a syntax error this is the output i want i want to remove the numbers and the names thats starts with letter a</p> <p>Output &quot;1 =&gt; Sayed &quot;2 =&gt; Mahmoud</p>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17352460/" ]
74,367,725
<p>I am working with an Azure shared image gallery and trying to write a bash <code>if</code> statement to iterate through the list of image definition names and <code>if</code> that image definition name is not there, create it <code>elif</code>, etc...</p> <p>I have a variable set as:</p> <pre><code>defs=$(az sig image-definition list --resource-group $MyRG --gallery-name $mySIG --query [*].name) \ echo &quot;$defs&quot; </code></pre> <p>What I'm attempting to do is create an if statement that will iterate through this list of image definition names in my Azure compute gallery, and create a specified name if it does not exist. My original assumption was something like <code>if [$defs != x</code> but not sure how to go about setting x, as it would be a user input for someone wanting to create a new definition.</p> <p>Sorry if my question is unclear. If there's more info I can provide please let me know.</p> <p>The problem I'm facing is that I understand bash somewhat but not in conjunction with how exactly I am attempting to apply it to my Azure image definitions issue.</p>
[ { "answer_id": 74367701, "author": "supersquires", "author_id": 18182675, "author_profile": "https://Stackoverflow.com/users/18182675", "pm_score": 0, "selected": false, "text": "pd.concat" }, { "answer_id": 74367723, "author": "My Work", "author_id": 12281892, "author_profile": "https://Stackoverflow.com/users/12281892", "pm_score": 0, "selected": false, "text": "unstack" }, { "answer_id": 74367733, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "out = df.to_numpy().ravel(order='F')\npd.DataFrame({'All Foods' : out})\n All Foods\n0 Apple\n1 Banana\n2 Pear\n3 Spinach\n4 Cucumber\n5 Carrot\n6 Beef\n7 Chicken\n8 Pork\n" }, { "answer_id": 74367746, "author": "Matěj Novák", "author_id": 16584666, "author_profile": "https://Stackoverflow.com/users/16584666", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\n# Loading file with fruits, vegetables and protein\ndataset = pd.read_csv('/fruit.csv')\n\n# This is where you should apply your code\n# Unpivoting (creating one column out of 3 columns)\ndf_unpivot = pd.melt(dataset, value_vars=['Fruits', 'Vegetables', 'Protein'])\n# Renaming column from value to All Foods\ndf_finalized = df_unpivot.rename(columns={'value': 'All Foods'})\n# Printing out \"All Foods\" column\nprint(df_finalized[\"All Foods\"])\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18344412/" ]
74,367,732
<p>Say I want to retrieve with graddle the dependancy tree of this artifact : <code>com.google.firebase:firebase-firestore:24.4.0</code></p> <p>How can I do ?</p>
[ { "answer_id": 74367766, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 0, "selected": false, "text": "gradle dependencies\n" }, { "answer_id": 74373137, "author": "George", "author_id": 11301941, "author_profile": "https://Stackoverflow.com/users/11301941", "pm_score": 3, "selected": true, "text": "Gradle dependencies" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114043/" ]
74,367,751
<p>Using Azure B2C Active Directory. Enforcing authentication. I'm able to get the user and email address. However I do I get a custom attribute with c#?</p> <pre><code> [Authorize] [HttpGet(&quot;authenticated/profile&quot;)] public string GetCustomAttribute() { var user = User.FindFirst(ClaimTypes.NameIdentifier); var customAttribute = ? } </code></pre> <p>Sifted through documentation and reviewed similar posts on stackoverflow.</p>
[ { "answer_id": 74367766, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 0, "selected": false, "text": "gradle dependencies\n" }, { "answer_id": 74373137, "author": "George", "author_id": 11301941, "author_profile": "https://Stackoverflow.com/users/11301941", "pm_score": 3, "selected": true, "text": "Gradle dependencies" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19416844/" ]
74,367,760
<p>After the .Net 7.0 update, when I use <code>dotnet watch run</code> I get this error:</p> <blockquote> <p>Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. File name: 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' at System.Reflection.RuntimeAssembly.GetType(QCallAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext) at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) at System.Reflection.Assembly.GetType(String name, Boolean throwOnError) at System.StartupHookProvider.CallStartupHook(StartupHookNameOrPath startupHook) at System.StartupHookProvider.ProcessStartupHooks()</p> </blockquote> <p>I can successfully build and run the project using Visual Studio, but can't use <strong>dotnet cli</strong>. How can this error be fixed?</p>
[ { "answer_id": 74367847, "author": "Omer", "author_id": 1996435, "author_profile": "https://Stackoverflow.com/users/1996435", "pm_score": 6, "selected": true, "text": "dotnet watch run xyz\n" }, { "answer_id": 74396378, "author": "Alex W. Andreza", "author_id": 5504551, "author_profile": "https://Stackoverflow.com/users/5504551", "pm_score": 3, "selected": false, "text": "dotnet" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1996435/" ]
74,367,775
<p>The ViewModel below is used on multiple forms.</p> <p>My goal is to update values received from those forms using the DateRangeViewModel itself. Is it possible?</p> <p>Example: User submits <em>&quot;2022-01-01 12:00:00 AM&quot;</em> and I update it to <em>&quot;2022-01-02 12:00:00 AM&quot;</em> before passing it to the controller.</p> <p>What I have tried:</p> <pre><code>public class DateRangeViewModel { public DateTime? From { get; set; } public DateTime? To { get { if (!To.HasValue) { return null; } return To.Value.AddDays(1); } set {} } } </code></pre> <p>And it throws an Exception of type 'System.StackOverflowException'.</p> <p>I know I can update these values through the controller. However, it is not my intent.</p>
[ { "answer_id": 74367924, "author": "Christian Gollhardt", "author_id": 2441442, "author_profile": "https://Stackoverflow.com/users/2441442", "pm_score": 2, "selected": true, "text": "public class DateRangeViewModel\n{ \n public DateTime? From { get; set; }\n public DateTime? To { \n get \n {\n return _to;\n }\n set\n {\n if (value == null)\n {\n _to = null;\n }\n else\n {\n _to = value.Value.AddDays(1);\n }\n }\n }\n\n private DateTime? _to;\n}\n" }, { "answer_id": 74367926, "author": "riffnl", "author_id": 313663, "author_profile": "https://Stackoverflow.com/users/313663", "pm_score": 2, "selected": false, "text": "private DateTime? ToValue { get; set; }\npublic DateTime? To \n{\n get { return ToValue.HasValue ? ToValue.AddDays(1) : null; }\n set { ToValue = value; }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8221046/" ]
74,367,798
<p>I'm trying to get the last non null value on a table visualization and last non null value offset from a set of data that consists of a worker ID, dates and their shifts. (First image is how the table is loaded)</p> <p><a href="https://i.stack.imgur.com/GQ3N7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GQ3N7.png" alt="data table" /></a></p> <p>On the table visualization on my report, i need to show the last non-null shift for those workers by last date, and the same with offset for the previous date that exists. (The output that i need)</p> <p><a href="https://i.stack.imgur.com/Q0go7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q0go7.png" alt="output" /></a></p> <p>I'm having trouble getting the correct DAX for filtering by worker ID and then by date to get the columns i need for output (tried both calculated column and measure with no success).</p> <p>I would appreciate some help.</p>
[ { "answer_id": 74367924, "author": "Christian Gollhardt", "author_id": 2441442, "author_profile": "https://Stackoverflow.com/users/2441442", "pm_score": 2, "selected": true, "text": "public class DateRangeViewModel\n{ \n public DateTime? From { get; set; }\n public DateTime? To { \n get \n {\n return _to;\n }\n set\n {\n if (value == null)\n {\n _to = null;\n }\n else\n {\n _to = value.Value.AddDays(1);\n }\n }\n }\n\n private DateTime? _to;\n}\n" }, { "answer_id": 74367926, "author": "riffnl", "author_id": 313663, "author_profile": "https://Stackoverflow.com/users/313663", "pm_score": 2, "selected": false, "text": "private DateTime? ToValue { get; set; }\npublic DateTime? To \n{\n get { return ToValue.HasValue ? ToValue.AddDays(1) : null; }\n set { ToValue = value; }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453952/" ]
74,367,801
<p>I have an array in Postgres that contains timestamps. I'd like to count the number of entries in the array newer than a timestamp specified in a query. As a bonus, I'd like to delete entries in the array older than another specified timestamp. Can this be done just using SQL in PostgreSQL?</p>
[ { "answer_id": 74367924, "author": "Christian Gollhardt", "author_id": 2441442, "author_profile": "https://Stackoverflow.com/users/2441442", "pm_score": 2, "selected": true, "text": "public class DateRangeViewModel\n{ \n public DateTime? From { get; set; }\n public DateTime? To { \n get \n {\n return _to;\n }\n set\n {\n if (value == null)\n {\n _to = null;\n }\n else\n {\n _to = value.Value.AddDays(1);\n }\n }\n }\n\n private DateTime? _to;\n}\n" }, { "answer_id": 74367926, "author": "riffnl", "author_id": 313663, "author_profile": "https://Stackoverflow.com/users/313663", "pm_score": 2, "selected": false, "text": "private DateTime? ToValue { get; set; }\npublic DateTime? To \n{\n get { return ToValue.HasValue ? ToValue.AddDays(1) : null; }\n set { ToValue = value; }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3246078/" ]
74,367,804
<p>I have this unordered list which can be arranged by the user:</p> <pre><code> &lt;ul id=&quot;sortable1&quot; class=&quot;connectedSortable&quot;&gt; &lt;li id=&quot;1&quot; class=&quot;ui-state-default&quot;&gt;A&lt;/li&gt; &lt;li id=&quot;2&quot; class=&quot;ui-state-default&quot;&gt;B&lt;/li&gt; &lt;li id=&quot;3&quot; class=&quot;ui-state-default&quot;&gt;C&lt;/li&gt; &lt;li id=&quot;4&quot; class=&quot;ui-state-default&quot;&gt;D&lt;/li&gt; &lt;li id=&quot;5&quot; class=&quot;ui-state-default&quot;&gt;E&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I wanted to make a Javascript array based on the arrangement for example if the order is ADBEC then the array should be [1, 4, 2, 5, 3]</p> <p>An ID has been set for each &lt;li&gt; as an individual identifier.</p> <p>Please note this refers to the orders of list items not the contents. All help appreciated thanks!</p>
[ { "answer_id": 74367842, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 3, "selected": true, "text": "document.querySelectorAll(\"#sortable1 li\").forEach(function(li) {\n console.log(li.id)\n})" }, { "answer_id": 74367843, "author": "imvain2", "author_id": 3684265, "author_profile": "https://Stackoverflow.com/users/3684265", "pm_score": 2, "selected": false, "text": "let sortable1 = document.querySelectorAll(\"#sortable1 li\"),arry = [];\n\nsortable1.forEach((e)=> arry.push(e.id))\n\nconsole.log(arry)" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535901/" ]
74,367,858
<p>I have created a custom post type for events (performaces of theater plays). Event categories denote plays and the events are performances of the plays. I would like user comments on individual performances (i.e. posts of the event custom-post-type) to apply to the category and appear on all other events of the same category. The question is how to best achieve this.</p> <p>One (quite bad) idea would be to use the comment_post hook and attach a copy of the comment to all posts of the same category. But first this would not apply to new posts of the category (unless comments are copied when a new post is first saved), change of category would need to be taken care of, ... and it does not seem very elegant to duplicate comments this way.</p> <p>Another idea would be to use the comment_post hook and attach the comment_id as a termmeta to the category and develop a different comments.php to pick up the comments from the category. Seems a bit complicated but not undoable.</p> <p>Any ideas?</p>
[ { "answer_id": 74368628, "author": "Shoelaced", "author_id": 1512787, "author_profile": "https://Stackoverflow.com/users/1512787", "pm_score": 1, "selected": false, "text": "function get_show_comments() {\n\n // Get the current post's categories.\n $categories = get_the_category( get_the_id() );\n\n // Get the category IDs.\n foreach ( $categories as $category ) {\n $category_ids[] = $category->cat_ID;\n }\n\n // Format for query.\n $category_ids = implode(',', $category_ids);\n\n // Get all posts with those categories.\n $events = get_posts( 'cat=' . $category_ids );\n\n // Put all their comments into an array.\n foreach ( $events as $event ) {\n $comments[] = get_comments( $event );\n }\n\n // Somewhere in here you'd presumably want to sort the comments by date, but I have to get to bed, lol.\n\n return $comments;\n\n}\n" }, { "answer_id": 74377344, "author": "Christer Fernstrom", "author_id": 441639, "author_profile": "https://Stackoverflow.com/users/441639", "pm_score": 0, "selected": false, "text": "function get_show_hello_comments() {\n\n global $post_id;\n // Get the current post's categories.\n // Need to use get_the_terms since we use a custom taxonomy\n $categories = get_the_terms($post_id, 'hello_event-category');\n\n // Get the category IDs.\n foreach ( $categories as $category ) {\n $term_ids[] = $category->term_id;\n }\n\n // Get all posts with those categories.\n $events = get_posts(\n array(\n 'posts_per_page' => -1,\n 'post_type' => 'hello_event',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'hello_event-category',\n 'field' => 'term_id',\n 'terms' => $term_ids,\n )\n )\n )\n );\n\n // Put all their comments into an array.\n $comments = [];\n foreach ( $events as $event ) {\n $comments = array_merge($comments, get_comments( $event ));\n }\n // Sort ascending on dates\n usort($comments, function($a, $b) {return strcmp($a->comment_date, $b->comment_date);});\n\n return $comments;\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441639/" ]
74,367,904
<p>How do you run an &quot;order by&quot; and then &quot;replace&quot; string, but keep the order? Context - I need the string &quot;column_name&quot; to be in the first line, hence using &quot;zzz_column_name&quot; to force it in the order by. And then I need to use <code>replace</code> to change it from &quot;zzz_column_naem&quot; to &quot;column_name&quot;.</p> <pre><code>SELECT replace(column_name, 'zzz_', '') FROM ( SELECT * FROM ( SELECT 'zzz_column_name' AS column_name UNION SELECT column_name FROM table ) s ORDER BY column_name DESC ) a </code></pre> <p>After the <code>replace</code> in the first line, I'd lose the order achieved by <code>order by</code>.</p>
[ { "answer_id": 74367914, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "order by" }, { "answer_id": 74367943, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT replace(column_name, 'string', '')\nFROM (\n SELECT 'zzz_column_name' AS column_name\n UNION\n SELECT column_name\n FROM table\n) s\nORDER BY column_name DESC\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7275214/" ]
74,367,941
<p>everytime the closeEmail is triggered or called I wanted to assign the email.emailAddress as the value of the textfield.</p> <p>just really new to react , what is the syntax or way to do this ?</p> <p>Any idea guys ?</p> <p>#code snippet</p> <pre><code>&lt;div style={{ display: &quot;block&quot; }}&gt; &lt;FormControl sx={{ mt: 2, minWidth: 720 }}&gt; &lt;div style={{ display: &quot;flex&quot;, justifyContent: &quot;space-between&quot;, alignItems: &quot;center&quot;, }} &gt; &lt;TextField style={{ width: &quot;95%&quot; }} onChange={emailOnChange} label=&quot;Email Address&quot; variant=&quot;filled&quot; name={email.emailAddress} defaultValue={email.emailAddress} /&gt; &lt;DeleteIcon style={{ color: &quot;red&quot; }} onClick={() =&gt; deleteEmail(email, prop.id)} /&gt; &lt;/div&gt; </code></pre> <p>#ts</p> <pre><code> const closeEmail = (email: IEmail) =&gt; { const test = email.emailAddress; setOpenEmail(false); return email.emailAddress; } </code></pre>
[ { "answer_id": 74368101, "author": "Beatriz Infante", "author_id": 7773975, "author_profile": "https://Stackoverflow.com/users/7773975", "pm_score": 0, "selected": false, "text": "<TextField\n style={{ width: \"95%\" }}\n value={email.emailAddress}\n label=\"Email Address\"\n variant=\"filled\"\n name={email.emailAddress}\n defaultValue={email.emailAddress}\n onChange={emailOnChange}\n/>\n" }, { "answer_id": 74374706, "author": "MrPatel2021", "author_id": 19671394, "author_profile": "https://Stackoverflow.com/users/19671394", "pm_score": 0, "selected": false, "text": "textField" }, { "answer_id": 74375631, "author": "Nitin Kudesia", "author_id": 20459187, "author_profile": "https://Stackoverflow.com/users/20459187", "pm_score": 3, "selected": true, "text": "import React,{useState} from 'react';\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19053255/" ]
74,368,004
<p><strong>Write a function to divide the input list into three sublists. The first sub-list is to include all the elements whose indexes satisfy the equation i mod 3 = 1. The second sub-list is to include all the elements whose indexes satisfy the equation and mod 3 = 2. The third sub-list is to contain the remaining elements. The order of the elements must be maintained. Return the result as three lists. Write a function using tail and non-tail recursion.</strong></p> <p>My attempt: I’m very confused in how to increase index so it can go through the list, any recommendation about how to make it recursive with increasing index each time?</p> <pre><code> def divide(list: List[Int]): (List[Int], List[Int], List[Int]) = { var index:Int =0 def splitList(remaining: List[Int], firstSubList: List[Int], secondSubList: List[Int], thirdSubList: List[Int], index:Int): (List[Int], List[Int], List[Int]) = { if(remaining.isEmpty) { return (List[Int](), List[Int](), List[Int]()) } val splitted = splitList(remaining.tail, firstSubList, secondSubList, thirdSubList, index) val firstList = if (index % 3 == 1) List() ::: splitted._1 else splitted._1 val secondList = if (index % 3 == 2) List() ::: splitted._2 else splitted._2 val thirdList = if((index% 3 != 1) &amp;&amp; (index % 3 != 2)) List() ::: splitted._3 else splitted._3 index +1 (firstSubList ::: firstList, secondSubList ::: secondList, thirdSubList ::: thirdList) } splitList(list, List(), List(), List(), index+1) } println(divide(List(0,11,22,33))) </code></pre>
[ { "answer_id": 74369402, "author": "Leo C", "author_id": 6316508, "author_profile": "https://Stackoverflow.com/users/6316508", "pm_score": 2, "selected": false, "text": "Map" }, { "answer_id": 74371150, "author": "Tim", "author_id": 7662670, "author_profile": "https://Stackoverflow.com/users/7662670", "pm_score": 1, "selected": false, "text": "def divide[T](list: List[T]) = {\n val g = list.zipWithIndex.groupMap(_._2 % 3)(_._1)\n\n (g.getOrElse(1, Nil), g.getOrElse(2, Nil), g.getOrElse(0, Nil)) \n}\n" }, { "answer_id": 74374510, "author": "Dima", "author_id": 4254517, "author_profile": "https://Stackoverflow.com/users/4254517", "pm_score": 1, "selected": false, "text": "index+1" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18025822/" ]
74,368,007
<p>I have the the sum from (i = 1) to N is 1 + 2 + 3 + 4 ... + N</p> <p>I found this program to calculate the sum <code>for i in range(1,100)</code></p> <pre><code>num1, num2 = 1, 100 sum = int((num2*(num2+1)/2) - (num1*(num1+1)/2) + num1) print(sum) </code></pre> <p>This works, but what if I want to know N = 10, or N = 100?</p>
[ { "answer_id": 74368047, "author": "Jiho Kim", "author_id": 16562494, "author_profile": "https://Stackoverflow.com/users/16562494", "pm_score": 1, "selected": false, "text": "def sum(n):\n return int(n * (n + 1) // 2)\n\nprint(sum(10))\nprint(sum(100))\n" }, { "answer_id": 74368063, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "1, 2, 3, 4, 5, 6" }, { "answer_id": 74368105, "author": "Pentragon", "author_id": 19010882, "author_profile": "https://Stackoverflow.com/users/19010882", "pm_score": 0, "selected": false, "text": "N * (N + 1) / 2" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20200075/" ]
74,368,030
<p>I have a huge problem with my CSS not working with my Angular project.</p> <p>When I log in on the login page</p> <pre><code>username = toto password = 123 </code></pre> <p>I created a demo <a href="https://stackblitz.com/github/kora1348/salma?file=src/styles.css" rel="nofollow noreferrer">here</a>.</p> <p><a href="https://i.stack.imgur.com/NBeWA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NBeWA.png" alt="enter image description here" /></a></p> <p>I gotta get that view</p> <p><a href="https://i.stack.imgur.com/uU3dG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uU3dG.png" alt="enter image description here" /></a></p> <p>Unfortunately I get this view, I don't understand what is wrong? The CSS code is perfect, it's just Angular that blocks, but I don't understand. :-(</p> <p>Do you have an idea please. I've been stuck since yesterday.</p> <p><a href="https://i.stack.imgur.com/WpFCU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WpFCU.png" alt="enter image description here" /></a></p> <p><em><strong>styles.css</strong></em></p> <p>This is the login</p> <pre><code>* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #444; } .container { position: relative; width: 70vw; height: 80vh; background: #fff; border-radius: 15px; box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.3), 0 6px 20px 0 rgba(0, 0, 0, 0.3); overflow: hidden; } .container::before { content: &quot;&quot;; position: absolute; top: 0; left: -50%; width: 100%; height: 100%; background: linear-gradient(-45deg, #4a60df, #085224); z-index: 6; transform: translateX(100%); transition: 1s ease-in-out; } .signin { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: space-around; z-index: 5; } form { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 40%; min-width: 238px; padding: 0 10px; } form.sign-in-form { opacity: 1; transition: 0.5s ease-in-out; transition-delay: 1s; } .title { font-size: 35px; color: #4a4ddf; margin-bottom: 10px; } .input-field { width: 100%; height: 50px; background: #f0f0f0; margin: 10px 0; border: 2px solid #4a6ddf; border-radius: 50px; display: flex; align-items: center; } .input-field i { flex: 1; text-align: center; color: #666; font-size: 18px; } .input-field input { flex: 5; background: none; border: none; outline: none; width: 100%; font-size: 18px; font-weight: 600; color: #444; } .btn { width: 150px; height: 50px; border: none; border-radius: 50px; background: #4a8bdf; color: #fff; font-weight: 600; margin: 10px 5px 10px 0; text-transform: uppercase; cursor: pointer; } .btn:hover { background: #3c3ec0; } .icon-text { margin: 10px 0; font-size: 16px; } .icon-block { display: flex; justify-content: center; } .item-icon { height: 45px; width: 45px; display: flex; align-items: center; justify-content: center; color: #444; border: 1px solid #444; border-radius: 50px; margin: 0 5px; } a { text-decoration: none; } .item-icon:hover { color: #4a59df; border-color: #724adf; } .panels-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: space-around; } .panel { display: flex; flex-direction: column; align-items: center; justify-content: space-around; width: 35%; min-width: 238px; padding: 0 10px; text-align: center; z-index: 6; } .left-panel { pointer-events: none; } .content { color: #fff; transition: 1.1s ease-in-out; transition-delay: 0.5s; } .panel h3 { font-size: 24px; font-weight: 600; } .panel p { font-size: 15px; padding: 10px 0; } .image { position: absolute; top: 50px; width: 150px; height: 80px } .left-panel .image, .left-panel .content { transform: translateX(-200%); } .right-panel .image, .right-panel .content { transform: translateX(0); } .signin_item_block { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 40%; min-width: 238px; padding: 0 10px; } .signin_item_block.sign-in-block-form { opacity: 0; transition: 0.5s ease-in-out; transition-delay: 1s; } /*Responsive*/ @media (max-width:779px) { .container { width: 100vw; height: 100vh; } } @media (max-width:635px) { .container::before { display: none; } form { width: 80%; } .signin_item_block.sign-in-block-form { display: none; } .container.sign-up-mode2 form.sign-in-block-form { display: flex; opacity: 1; } .container.sign-up-mode2 form.sign-in-form { display: none; } .panels-container { display: none; } } @media (max-width:320px) { form { width: 90%; } } </code></pre> <p><em><strong>online.component.css</strong></em></p> <p>This is the dashboard.</p> <pre><code>@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&amp;display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } ul { padding: 0; } /* Hamburger Menu */ .hamburger-menu { position: relative; width: 40px; height: 40px; margin: 0 15px; } .label-hamburger-menu { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); cursor: pointer; transition: 0.5s ease; } .label-hamburger-menu .bar { width: 40px; height: 4px; background: #fff; border-radius: 1px; transition: 0.4s ease; } .label-hamburger-menu .bar:not(:first-child) { margin-top: 5px; } #checkbox-hamburger-menu { display: none; } #checkbox-hamburger-menu:checked+.label-hamburger-menu { transform: translate(-50%, -50%) rotateY(180deg); } #checkbox-hamburger-menu:checked+.label-hamburger-menu .bar { width: 30px; transform: rotateY(180deg) rotateX(360deg); } #checkbox-hamburger-menu:checked+.label-hamburger-menu .bar:first-child { transform: translateY(9px) rotate(-45deg); } #checkbox-hamburger-menu:checked+.label-hamburger-menu .bar:nth-child(2) { opacity: 0; } #checkbox-hamburger-menu:checked+.label-hamburger-menu .bar:nth-child(3) { transform: translateY(-10px) rotate(45deg); } /* Home Section */ .home-section { position: relative; background: #f3f6f2; height: 100vh; left: 260px; width: calc(100% - 260px); transition: all 0.5s ease; display: flex; flex-direction: column; } .home-section .home-header { height: 122px; display: flex; align-items: center; background-color: #1bb16c; /* #bbe7aa */ } .home-section .home-header .title { color: #fff; font-size: 22px; font-weight: 600; } /* .home-section .home-view { flex-grow: 1; display: flex; align-items: center; justify-content: center; flex-direction: column; color: #fff; } */ /* Sidebar */ .sidebar { position: fixed; top: 0; left: 0; height: 100%; width: 260px; background: #fff; z-index: 100; transition: all 0.5s ease; } .sidebar.sidebar-close { width: 60px; } .sidebar .logo-details { width: 100%; padding: 10px 10px 10px 10px; border-bottom: 1px solid #e0e0e0; } .sidebar .logo-details img { height: 50px; width: 80%; display: block; margin: 0 auto; } .sidebar .nav-links { height: 100%; width: 260px; padding-bottom: 150px; overflow: auto; } .sidebar .nav-links::-webkit-scrollbar { display: none; } .sidebar .nav-links li { list-style: none; } .sidebar .nav-links&gt;li { position: relative; width: fit-content; border-bottom: 1px solid #ccc; } .sidebar .nav-links li:hover { background: #eaeaea; } /* Dropdown Title */ .sidebar .nav-links .dropdown-title { width: 260px; overflow: hidden; transition: all 0.52s ease; display: flex; align-items: center; justify-content: space-between; position: relative; } .sidebar.sidebar-close .nav-links .dropdown-title { width: 60px; } .sidebar .nav-links li i { height: 50px; min-width: 60px; text-align: center; line-height: 50px; color: #004a65; font-size: 20px; cursor: pointer; transition: all 0.3s ease; } .sidebar .nav-links li:hover i, .sidebar .nav-links li.active i { color: #004a65; } .sidebar .nav-links li.showMenu i.arrow { transform: rotate(-180deg); } /* a Tag */ .sidebar .nav-links li a { display: flex; align-items: center; text-decoration: none; width: 100%; } /* Link Name */ .sidebar .nav-links li a .link_name { font-size: 16px; font-weight: 600; color: #004a65; transition: all 0.4s ease; } .sidebar .nav-links li:hover a .link_name, .sidebar .nav-links li.active a .link_name { color: #004a65; } .sidebar.sidebar-close .nav-links li a .link_name { pointer-events: none; } /* Sub Menu */ .sidebar .nav-links li .sub-menu { background: #fff; display: none; transition: all 0.4s ease; } .sidebar .nav-links li.showMenu .sub-menu { display: block; } .sidebar .nav-links li .sub-menu a { color: #004a65; font-size: 15px; white-space: nowrap; transition: all 0.3s ease; padding: 7px 0px; } .sidebar .nav-links li .sub-menu li { padding-left: 10px; } .sidebar .nav-links li .sub-menu li:hover a, .sidebar .nav-links li .sub-menu li.active a { color: green; font-size: 15px; font-weight: 600; } .sidebar .nav-links li .sub-menu li:hover { background: #e8f5f9; } .sidebar .nav-links li .sub-menu li:not(:first-child) { padding: 5px 60px; border-top: 1px solid #e0e0e0; } .sidebar .nav-links li .sub-menu li:last-child { padding: 5px 60px; border-top: 1px solid #e0e0e0; } .sidebar.sidebar-close .nav-links li .sub-menu { position: absolute; left: 100%; top: -10px; margin-top: 0; padding: 0; border-radius: 0 6px 6px 0; opacity: 0; display: block; pointer-events: none; transition: 0s; overflow: hidden; } .sidebar.sidebar-close .nav-links li .sub-menu li { padding: 6px 15px; width: 200px; } .sidebar.sidebar-close .nav-links li:hover .sub-menu { top: 0; opacity: 1; pointer-events: auto; transition: all 0.4s ease; } .sidebar .nav-links li .sub-menu .link_name { display: none; } .sidebar.sidebar-close .nav-links li .sub-menu .link_name { font-size: 16px; font-weight: 600; display: block; } .sidebar.sidebar-close .nav-links li .sub-menu li:first-child { background: #fff; pointer-events: none; } .sidebar .nav-links li .sub-menu.blank { pointer-events: auto; opacity: 0; pointer-events: none; } .sidebar .nav-links li:hover .sub-menu.blank, .sidebar .nav-links li.active .sub-menu.blank { top: 50%; transform: translateY(-50%); } .sidebar.sidebar-close~.home-section { left: 60px; width: calc(100% - 60px); } .sidebar.sidebar-close .logo-details img { width: 37px; height: 50px; transform: scale(1.2) translateX(-3px); } @media (max-width: 420px) { .sidebar.sidebar-close .nav-links li .sub-menu { display: none; } } </code></pre> <p>Thank you a lot for your help.</p>
[ { "answer_id": 74368047, "author": "Jiho Kim", "author_id": 16562494, "author_profile": "https://Stackoverflow.com/users/16562494", "pm_score": 1, "selected": false, "text": "def sum(n):\n return int(n * (n + 1) // 2)\n\nprint(sum(10))\nprint(sum(100))\n" }, { "answer_id": 74368063, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "1, 2, 3, 4, 5, 6" }, { "answer_id": 74368105, "author": "Pentragon", "author_id": 19010882, "author_profile": "https://Stackoverflow.com/users/19010882", "pm_score": 0, "selected": false, "text": "N * (N + 1) / 2" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18216840/" ]
74,368,056
<p>A requester is sending messages over a normal queue to a responder, indicating a dynamic queue it created as a reply queue. The responder puts these same messages on the reply queue. The responder retrieves all messages correctly.</p> <p>For each message sent the requester obtains a message from the reply queue, but its body is filled with zeroes. Both programs are written in Java, using com.ibm.mq.allclient-9.2.2.0.jar. When I wrote the same in JavaScript with Node.js and ibmmq for node, everything worked fine.</p> <p>Requester.java:</p> <pre><code>package com.hellerim.imq.comm.requester; import static com.ibm.mq.constants.CMQC.MQENC_INTEGER_NORMAL; import static com.ibm.mq.constants.CMQC.MQFMT_STRING; import static com.ibm.mq.constants.CMQC.MQGMO_FAIL_IF_QUIESCING; import static com.ibm.mq.constants.CMQC.MQGMO_NO_SYNCPOINT; import static com.ibm.mq.constants.CMQC.MQGMO_NO_WAIT; import static com.ibm.mq.constants.CMQC.MQGMO_WAIT; import static com.ibm.mq.constants.CMQC.MQMT_REQUEST; import static com.ibm.mq.constants.CMQC.MQOO_FAIL_IF_QUIESCING; import static com.ibm.mq.constants.CMQC.MQOO_INPUT_EXCLUSIVE; import static com.ibm.mq.constants.CMQC.MQOO_OUTPUT; import static com.ibm.mq.constants.CMQC.MQPMO_NO_SYNCPOINT; import static com.ibm.mq.constants.CMQC.MQRC_NO_MSG_AVAILABLE; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.stream.Collectors; import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager; import io.netty.util.CharsetUtil; import net.jcip.annotations.GuardedBy; public class Requester { private static final int WAIT_WHILE_EMPTY = 100; // ms private static int MAX_MILLIS_BETWEEN_REQUESTS = 100; private static int LONG_WIDTH_IN_HEX_CHARS = 16; private static final Charset charset = CharsetUtil.ISO_8859_1; private MQQueueManager qMgr; private final MQQueue requestQueue; private final String queueNamePattern = &quot;TEST.SESSION.*&quot;; private String replyQueueName; private final MQQueue replyQueue; private final MQGetMessageOptions getOptions = new MQGetMessageOptions(); private static final String MQ_MANAGER = &quot;MY_QM&quot;; private static final String REQUEST_QUEUE = &quot;TEST.REQUESTS&quot;; private static final String MODEL_QUEUE = &quot;TEST.SESSION.MODEL&quot;; final private Object locker = new Object(); @GuardedBy(&quot;this&quot;) boolean stopped = false; int rcvd = 0; public static void main(String[] args) { try { Requester rq = new Requester(MQ_MANAGER, REQUEST_QUEUE, MODEL_QUEUE); List&lt;String&gt; poem = writePoem(); Random requestIds = new Random(); Random delays = new Random(1000); int cnt = 0; int position = 0; for (int i = 0; i &lt; 50; ++i) { if (i == poem.size()) { int requestId = requestIds.nextInt(99999) + 1; String text = poem.stream().collect(Collectors.joining(&quot;\n&quot;)); String request = appRequestFrom(text, requestId); rq.write(request); System.out.println(&quot;Requester: sent request no &quot; + (++cnt) + &quot; - &quot; + requestId); } position %= poem.size(); String line = poem.get(position); int requestId = requestIds.nextInt(99999) + 1; String request = appRequestFrom(line, requestId); rq.write(request); System.out.println(&quot;Requester: sent request no &quot; + (++cnt) + &quot; - &quot; + requestId); position++; try { Thread.sleep((long) Math.ceil((Math.pow( delays.nextDouble(), 4) * MAX_MILLIS_BETWEEN_REQUESTS) + 1)); } catch (InterruptedException e) { // ignore } } try { Thread.sleep(2000); } catch (InterruptedException e) { // ignore } rq.close(); } catch (MQException e) { e.printStackTrace(); } } public Requester(String mqManagerName, String requestQueueName, String modelQueueName) throws MQException { super(); System.out.println(&quot;Requester: establishing mq session (mq manager: &quot; + mqManagerName + &quot;/ request queue: &quot; + requestQueueName + &quot; / model queue: &quot; + modelQueueName +&quot;)&quot;); qMgr = new MQQueueManager(mqManagerName); // get request queue int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING; requestQueue = qMgr.accessQueue(requestQueueName, openOptions); // get dynamic reply queue int inputOptions = MQOO_INPUT_EXCLUSIVE + MQOO_FAIL_IF_QUIESCING; replyQueue = new MQQueue(qMgr, modelQueueName, inputOptions, &quot;&quot;, queueNamePattern, &quot;&quot;); replyQueueName = replyQueue.getName(); System.out.println(&quot;Requester: created temporary reply queue &quot; + replyQueueName); getOptions.options = MQGMO_NO_SYNCPOINT + MQGMO_NO_WAIT + MQGMO_FAIL_IF_QUIESCING; // catch-up (for those replies not retrieved after a request was put) Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { // read options MQGetMessageOptions getOptions = new MQGetMessageOptions(); getOptions.options = MQGMO_NO_SYNCPOINT + MQGMO_WAIT + MQGMO_FAIL_IF_QUIESCING; getOptions.waitInterval = WAIT_WHILE_EMPTY; while(proceed()) { try { if (!retrieveMessage(getOptions)) { try { Thread.sleep(getOptions.waitInterval); } catch (InterruptedException e1) {} } } catch (IOException e) { e.printStackTrace(); } } } }); } private boolean retrieveMessage(MQGetMessageOptions getOptions) throws IOException { MQMessage msg = new MQMessage(); try { msg.clearMessage(); msg.seek(0); replyQueue.get(msg, getOptions); System.out.println(&quot;Requester: reply no &quot; + ++rcvd + &quot; received - id: &quot; + Long.parseLong(new String(msg.messageId, Charset.forName(&quot;ISO_8859_1&quot;)), 16)); byte[] buf = new byte[msg.getDataLength()]; String message = new String(buf, charset); System.out.println(&quot;Requester: message received:\n&quot; + message); } catch (MQException e) { if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) { return false; } } return true; } public byte[] write(String message) { int positionRequestId = 24; int endIndex = positionRequestId + 16; CharSequence requestId = message.substring(positionRequestId, endIndex); StringBuffer sb = new StringBuffer(&quot;00000000&quot;); sb.append(requestId); byte[] id = sb.toString().getBytes(charset); MQMessage mqMsg = new MQMessage(); mqMsg.characterSet = 819; mqMsg.encoding = MQENC_INTEGER_NORMAL; mqMsg.format = MQFMT_STRING; mqMsg.messageType = MQMT_REQUEST; mqMsg.messageId = id; mqMsg.correlationId = id; mqMsg.replyToQueueName = replyQueueName; try { mqMsg.writeString(message); mqMsg.seek(0); MQPutMessageOptions pmo = new MQPutMessageOptions(); pmo.options = MQPMO_NO_SYNCPOINT; requestQueue.put(mqMsg, pmo); } catch (IOException e) { e.printStackTrace(); } catch (MQException e) { e.printStackTrace(); } // try to read from reply queue fail immediately try { retrieveMessage(getOptions); } catch (IOException e) { e.printStackTrace(); } return id; } public void close() { stop(); try { Thread.sleep(2 * WAIT_WHILE_EMPTY); } catch (InterruptedException e1) { // ignore } try { if (requestQueue != null) { requestQueue.close(); } if (qMgr != null) { qMgr.disconnect(); } } catch (MQException e) { // ignore } } public boolean proceed() { synchronized(locker) { return !stopped; } } public void stop() { synchronized(locker) { stopped = true; } } private static List&lt;String&gt; writePoem() { List&lt;String&gt; poem = new ArrayList&lt;&gt;(); poem.add(&quot;Das Nasobem&quot;); poem.add(&quot;von Joachim Ringelnatz&quot;); poem.add(&quot;&quot;); poem.add(&quot;Auf seiner Nase schreitet&quot;); poem.add(&quot;einher das Nasobem,&quot;); poem.add(&quot;von seineme Kind begleitet -&quot;); poem.add(&quot;es steht noch nicht im Brehm.&quot;); poem.add(&quot;&quot;); poem.add(&quot;Es steht noch nicht im Meyer&quot;); poem.add(&quot;und auch im Brockhaus nicht -&quot;); poem.add(&quot;es tritt aus meiner Leier&quot;); poem.add(&quot;zum ersten Mal ans Licht.&quot;); poem.add(&quot;&quot;); poem.add(&quot;Auf seiner Nase schreitet&quot;); poem.add(&quot;- wie schon gesagt - seitdem&quot;); poem.add(&quot;von seinem Kind begleitet&quot;); poem.add(&quot;einher das Nasobem.&quot;); poem.add(&quot;&quot;); poem.add(&quot;&quot;); return poem; } private static String iToHex(int num, int places) { StringBuilder sb = new StringBuilder(); char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; for (int i = 0; i &lt; places; ++i) { sb.append(digits[num % places]); num /= places; } return sb.reverse().toString(); } private static String iToHex(int num) { return iToHex(num, LONG_WIDTH_IN_HEX_CHARS); } private static String appRequestFrom(String msgBody, int requestId) { int headerLength = 72; // includes message body length field here! int bodyLength = msgBody.length(); StringBuilder sb = new StringBuilder(); sb.append(&quot;GHI &quot;); // magic sb.append(&quot;1&quot;); // version major sb.append(&quot;0&quot;); // version minor sb.append(&quot;0&quot;); // flags sb.append(&quot;1&quot;); // app message type SYNCHRONOUS REQUEST sb.append(iToHex(headerLength + bodyLength)); // message length sb.append(iToHex(requestId)); // request id sb.append(iToHex(0)); // timeout sb.append(iToHex(bodyLength)); // message body length sb.append(msgBody); // message body return sb.toString(); } } </code></pre> <p>Responder.java:</p> <pre><code>package com.hellerim.imq.comm.responder; import static com.ibm.mq.constants.CMQC.*; import java.io.EOFException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager; import io.netty.util.CharsetUtil; import net.jcip.annotations.GuardedBy; public class Responder { private MQQueueManager qMgr; private MQQueue requestQueue; private Map&lt;String, MQQueue&gt; replyQueues = new HashMap&lt;&gt;(); private final Object locker = new Object(); static final private int WAIT_WHILE_EMPTY = 100; // ms @GuardedBy(&quot;locker&quot;) private boolean stopped = false; Thread fetcherThread = null; private final static byte MESSAGE_TYPE_REPLY = 52; // '4' public final static String MQ_MANAGER = &quot;MY_QM&quot;; public final static String REQUEST_QUEUE = &quot;TEST.REQUESTS&quot;; public static void main( String[] args ) throws MQException, IOException { System.out.println( &quot;running reponder application&quot; ); try { new Responder(MQ_MANAGER, REQUEST_QUEUE).start(); } catch(Exception e) { e.printStackTrace(); } } public Responder(String mqManagerName, String requestQueueName) throws MQException { System.out.println(&quot;establishing mq session (mq manager: &quot; + mqManagerName + &quot; / request queue: &quot; + requestQueueName + &quot;)&quot;); qMgr = new MQQueueManager(mqManagerName); int openOptions = MQOO_INPUT_SHARED + MQOO_FAIL_IF_QUIESCING; requestQueue = qMgr.accessQueue(requestQueueName, openOptions); } public MQQueue getReplyQueue(String replyQueueName) throws MQException { if (replyQueues.containsKey(replyQueueName)) { return replyQueues.get(replyQueueName); } int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING; MQQueue replyQueue = qMgr.accessQueue(replyQueueName, openOptions); replyQueues.put(replyQueueName, replyQueue); System.out.println(&quot;Responder: opened dynamic reply queue&quot;); return replyQueue; } private void start() throws IOException { Runnable fetcher = new Runnable() { @Override public void run() { int cnt = 0; while(proceed()) { MQMessage msg = new MQMessage(); try { //msg.clearMessage(); MQGetMessageOptions getOptions = new MQGetMessageOptions(); getOptions.options = MQGMO_NO_SYNCPOINT + MQGMO_WAIT + MQGMO_FAIL_IF_QUIESCING; getOptions.waitInterval = WAIT_WHILE_EMPTY; requestQueue.get(msg, getOptions); System.out.println(&quot;Responder: message no &quot; + ++cnt + &quot; received&quot;); MQQueue replyQueue = null; try { replyQueue = getReplyQueue(msg.replyToQueueName); } catch(MQException e) { if (e.completionCode == MQCC_FAILED &amp;&amp; e.reasonCode == MQRC_UNKNOWN_OBJECT_NAME) { // dynamic reply queue does not exist any more =&gt; message out of date continue; } throw e; } // set message type for reply if (msg.getDataLength() &lt; 56) { System.out.println(&quot;invalid message:&quot;); System.out.println(Msg2Text(msg)); continue; } System.out.println(Msg2Text(msg)); int typePosition = 7; msg.seek(typePosition); msg.writeByte(MESSAGE_TYPE_REPLY); msg.seek(0); String text = Msg2Text(msg); MQMessage msgOut = new MQMessage(); msgOut.characterSet = 819; msgOut.encoding = MQENC_INTEGER_NORMAL; msgOut.format = MQFMT_STRING; msgOut.messageType = MQMT_REPLY; msgOut.messageId = msg.messageId; msgOut.correlationId = msg.correlationId; msgOut.seek(0); msgOut.writeString(text); msgOut.seek(0); System.out.println(text); // System.out.println(&quot;Responder: message received&quot;); MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same pmo.options = MQPMO_NO_SYNCPOINT; replyQueue.put(msgOut, pmo); System.out.println(&quot;Responder: message no &quot; + cnt + &quot; returned&quot;); } catch (MQException e) { if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) { ; // NOOP } else { try { msg.seek(0); System.out.println(msg); } catch (EOFException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } e.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e1) {} } } catch (IOException e) { e.printStackTrace(); } } shutdown(); } }; Thread task = new Thread(fetcher); task.run(); System.out.print(&quot;press &lt;ENTER&gt; to terminate &quot;); System.in.read(); System.out.println(); synchronized(locker) { stopped = true; } try { task.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String Msg2Text(MQMessage msg) { int length; String text = &quot;&quot;; try { length = msg.getDataLength(); byte[] buf = new byte[length]; msg.seek(0); msg.readFully(buf); text = new String(buf, CharsetUtil.ISO_8859_1); msg.seek(0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return text; } private boolean proceed() { synchronized(locker) { return !stopped; } } private void shutdown() { System.out.print(&quot;\nshutting down responder... &quot;); for (MQQueue queue : replyQueues.values()) { try { queue.close(); } catch (MQException e) { } } replyQueues.clear(); try { qMgr.close(); } catch (MQException e) { } System.out.println(&quot;done.&quot;); } } </code></pre> <p>Is there any idea what might be wrong?</p>
[ { "answer_id": 74372649, "author": "Rich", "author_id": 19632961, "author_profile": "https://Stackoverflow.com/users/19632961", "pm_score": 3, "selected": true, "text": "byte[] buf = new byte[msg.getDataLength()];\nString message = new String(buf, charset);\nSystem.out.println(\"Requester: message received:\\n\" + message);\n" }, { "answer_id": 74383039, "author": "Roger", "author_id": 1431734, "author_profile": "https://Stackoverflow.com/users/1431734", "pm_score": 0, "selected": false, "text": "String msgStr = msg.readStringOfByteLength(msg.getMessageLength());\nSystem.out.println(\"Requester: message received:\\n\" + msgStr);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1558628/" ]
74,368,059
<p>We want to complete a DT1 table, by retrieving the sum of scores contained in another DT2 table. By adding to DT1 counters A and B from DT2, making sure that date of DT1 is between the start and end date of DT2. How is this achievable with data table?</p> <h1>Initial data</h1> <pre><code>Table DT1 Date City Squad 2022/1/5 NY a 2022/1/6 NY b 2022/1/9 LA b 2022/1/7 NY a 2022/1/5 NY a Table DT2 Date_start Date_end City Squad Counter_A Counter_B 2022/1/1 2022/1/11 NY a 1 1 2022/1/2 2022/1/5 NY a 2 3 2022/1/1 2022/1/8 LA b 2 1 2022/1/1 2022/1/8 NY b 1 3 </code></pre> <h1>Expected result</h1> <pre><code>Date City Squad Counter_A Counter_B 2022/1/5 NY a 3 4 2022/1/6 NY b 1 3 2022/1/9 LA b 0 0 2022/1/7 NY a 1 1 </code></pre> <h1>Init data code</h1> <pre><code>require(data.table) DT1 &lt;- data.table( work_day = c(&quot;2022/1/5&quot;,&quot;2022/1/6&quot;,&quot;2022/1/9&quot;,&quot;2022/1/7&quot;,&quot;2022/1/7&quot;,&quot;2022/1/3&quot;), city= c(&quot;NY&quot;, &quot;NY&quot;,&quot;LA&quot;, &quot;NY&quot;, &quot;NY&quot;, &quot;NY&quot;), squad=c(&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;) ) DT2 &lt;- data.table( date_start = c(&quot;2022/1/1&quot;,&quot;2022/1/2&quot;,&quot;2022/1/1&quot;,&quot;2022/1/1&quot;), date_end = c(&quot;2022/1/11&quot;,&quot;2022/1/5&quot;,&quot;2022/1/8&quot;,&quot;2022/1/8&quot;), city= c(&quot;NY&quot;,&quot;NY&quot;, &quot;LA&quot;, &quot;NY&quot;), squad=c(&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;), count_A=c(1,2,2,1), count_B=c(1,3,1,3) ) </code></pre> <h1>Code attempt</h1> <p>I want to do in data table something like the following code in dplyr:</p> <pre><code>if(DT1$city == DT2$city &amp; DT1$squad == DT2$squad &amp; DT1$date %in% seq(DT2$date_start,DT2$date_end)) { DT1$counter_A=DT2$counter_A DT1$counter_B=DT2$counter_B } else { &quot;Nothing&quot; } </code></pre>
[ { "answer_id": 74368268, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 1, "selected": false, "text": "# you'll want to fix these regardless, since you can't calculate on text dates\nDT1$work_day = as.Date(DT1$work_day)\nDT2$date_start = as.Date(DT2$date_start)\nDT2$date_end = as.Date(DT2$date_end)\n\n\nDT1 %>%\n left_join(DT1 %>% # only necessary to show result 3\n left_join(DT2, by = c(\"city\", \"squad\")) %>%\n filter(work_day >= date_start, work_day <= date_end) %>%\n group_by(work_day, squad) %>%\n summarize(across(count_A:count_B, sum))) %>%\n mutate(across(count_A:count_B, ~coalesce(.x, 0)))\n" }, { "answer_id": 74368531, "author": "Dr_Be", "author_id": 4923367, "author_profile": "https://Stackoverflow.com/users/4923367", "pm_score": 3, "selected": true, "text": "data.table" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19123441/" ]
74,368,078
<p>I'm getting <code>MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017</code> when trying to start mongo locally with <code>$ mongosh</code>.</p> <pre><code>$ mongosh Current Mongosh Log ID: 636addb4**************** Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&amp;serverSelectionTimeoutMS=2000&amp;appName=mongosh+1.5.4 MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017 </code></pre> <p>Some details: I killed some process at some point to try to stop mongo so I could run <code>run-rs -v 4.0.0 --shell</code>.</p>
[ { "answer_id": 74368268, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 1, "selected": false, "text": "# you'll want to fix these regardless, since you can't calculate on text dates\nDT1$work_day = as.Date(DT1$work_day)\nDT2$date_start = as.Date(DT2$date_start)\nDT2$date_end = as.Date(DT2$date_end)\n\n\nDT1 %>%\n left_join(DT1 %>% # only necessary to show result 3\n left_join(DT2, by = c(\"city\", \"squad\")) %>%\n filter(work_day >= date_start, work_day <= date_end) %>%\n group_by(work_day, squad) %>%\n summarize(across(count_A:count_B, sum))) %>%\n mutate(across(count_A:count_B, ~coalesce(.x, 0)))\n" }, { "answer_id": 74368531, "author": "Dr_Be", "author_id": 4923367, "author_profile": "https://Stackoverflow.com/users/4923367", "pm_score": 3, "selected": true, "text": "data.table" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004011/" ]
74,368,083
<p>I have a dataframe, <code>df_res</code> with volumetric and mean and standard deviation jacobian values against ID strings (<code>subjid</code>), software type ran (<code>pipeline</code>), and anatomical region labels (<code>label_id</code>):</p> <pre><code>df_res = subjid pipeline label_id volume_(mm^3) mean_jacobian stdev_jacobian 0 100007_t0 Rigid 0 10100000.0 1.11 0.078 1 100007_t0 Rigid 1 315439.0 1.04635 0.283 2 100007_t0 Rigid 2 624165.0 0.968231 0.192 3 100007_t0 Rigid 3 515589.0 1.1273 0.229 4 100007_t1 Rigid 0 10084600.0 1.0935 0.033 5 100007_t1 Rigid 1 320533.0 1.0457 0.277 6 100007_t1 Rigid 2 621393.0 0.957 0.193 7 100007_t1 Rigid 3 507840.0 1.00573 0.232 </code></pre> <p>My goal dataframe is something where I would want to have one row per <code>subjid</code>-<code>pipeline</code> pair, and the <code>label_id</code> is almost transposed as column per quantity.</p> <p><strong>The preview below is a &quot;condensed version&quot; for formatting's sake</strong>.</p> <p>Assume that each <code>label_id</code> from <code>df_res</code> has its own <code>{label_id}_volume_(mm^3)</code>, <code>{label_id}_mean_jacobian</code>, and <code>{label_id}_stdev_jacobian</code> columns (total of 9 for each <code>label_id</code>+ <code>pipeline</code> + <code>subjid</code> = 11 total columns):</p> <pre><code>df_goal = subjid pipeline label0_volume_(mm^3) +...+ label3_volume_(mm^3) +...+ label3_mean_jacobian 100007_t0 Rigid 10100000.0 515589.0 1.1273 100007_t1 Rigid 10084600.0 507840.0 1.00573 </code></pre> <p>I managed to get something close, with <code>df_res_test</code>. I did a <code>df.pivot()</code> function:</p> <pre><code>&gt;&gt;&gt; df_res_pivot = df_res.pivot(index=&quot;subjid&quot;, columns=&quot;label_id&quot;, values=[&quot;volume_(mm^3)&quot;, &quot;mean_jacobian&quot;, &quot;stdev_jacobian&quot;]) df_res_pivot = volume_(mm^3) ... stdev_jacobian label_id 0 1 2 ... 1 2 3 subjid ... 100007_t0 10100000.0 315439.0 624165.0 ... 0.289318 0.192214 0.229341 100007_t1 10084600.0 320533.0 621393.0 ... 0.277735 0.193940 0.232486 [2 rows x 12 columns] </code></pre> <p>Is there a way I can rename / combine the <code>values</code> and <code>columns</code> argument to make my data more sensible and look like <code>df_goal</code>?</p>
[ { "answer_id": 74368268, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 1, "selected": false, "text": "# you'll want to fix these regardless, since you can't calculate on text dates\nDT1$work_day = as.Date(DT1$work_day)\nDT2$date_start = as.Date(DT2$date_start)\nDT2$date_end = as.Date(DT2$date_end)\n\n\nDT1 %>%\n left_join(DT1 %>% # only necessary to show result 3\n left_join(DT2, by = c(\"city\", \"squad\")) %>%\n filter(work_day >= date_start, work_day <= date_end) %>%\n group_by(work_day, squad) %>%\n summarize(across(count_A:count_B, sum))) %>%\n mutate(across(count_A:count_B, ~coalesce(.x, 0)))\n" }, { "answer_id": 74368531, "author": "Dr_Be", "author_id": 4923367, "author_profile": "https://Stackoverflow.com/users/4923367", "pm_score": 3, "selected": true, "text": "data.table" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9343043/" ]
74,368,089
<p>I'm a new pyhton programmer, I'm writing a simple program that calculate what I have in my storage and what is remaining so let's assume that x = 1000 I want to deduct 200 items now and after a day I'll deduct 300 more the problem here that programme will deduct 200 out of the 1000 and deduct 300 out of the same 1000 not from remaining x how can I solve this problem?</p> <pre><code>x = 1000 While x !=0:`your text` b = int(input(&quot;how many (x) you need:) remaining = x - b Print(remaining) else: pass </code></pre>
[ { "answer_id": 74368268, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 1, "selected": false, "text": "# you'll want to fix these regardless, since you can't calculate on text dates\nDT1$work_day = as.Date(DT1$work_day)\nDT2$date_start = as.Date(DT2$date_start)\nDT2$date_end = as.Date(DT2$date_end)\n\n\nDT1 %>%\n left_join(DT1 %>% # only necessary to show result 3\n left_join(DT2, by = c(\"city\", \"squad\")) %>%\n filter(work_day >= date_start, work_day <= date_end) %>%\n group_by(work_day, squad) %>%\n summarize(across(count_A:count_B, sum))) %>%\n mutate(across(count_A:count_B, ~coalesce(.x, 0)))\n" }, { "answer_id": 74368531, "author": "Dr_Be", "author_id": 4923367, "author_profile": "https://Stackoverflow.com/users/4923367", "pm_score": 3, "selected": true, "text": "data.table" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19820594/" ]
74,368,104
<p>Is there a way to remove all CSS styles from a specific selector using Javascript, without removing the selector itself from the element?</p> <p>The issue is that I'd like to add my own class to an element to handle the styling, but the element is created by a WordPress plugin and there are already classes on the element that overwrite mine. I cannot remove the original classes because they're also being used for Javascript.</p> <p>Normally I'd give up and just stick <code>!important</code> on everything in my class, which I can still do if there's no other way, but the original classes have practically EVERYTHING defined, in multiple pseudo states, so I'd have to list out everything from <code>color:</code> to <code>border-bottom-right-radius:</code> with <code>!important</code> after it (including on <code>:focus</code> and <code>:hover</code> and everything) in order to overwrite all the original styles.</p> <p>Basically I have this:</p> <pre><code>&lt;button class=&quot;original-class-1 original-class-2&quot;&gt;Button&lt;/button&gt; &lt;style&gt; .my-styles { color: #fafafa; background-color: #090909; border: 1px solid; } .original-class-1 { color: #000000; background-color: #ffffff; border-width: 1px; border-style: solid; ... ... etc-with-everything-but-the-kitchen-sink: killme; } .original-class-2 { padding-top: 5px; padding-right: 5px; padding-bottom: 5px; padding-left: 5px; ... ... etc-with-even-more-stuff: why; } &lt;/style&gt; </code></pre> <p>and I want</p> <pre><code>&lt;button class=&quot;original-class-1 original-class-2 my-styles&quot;&gt;Button&lt;/button&gt; &lt;style&gt; .my-styles { color: #fafafa; background-color: #090909; border: 1px solid; } .original-class-1 { } .original-class-2 { } &lt;/style&gt; </code></pre> <p>At the moment I have something like this started:</p> <pre><code>const buttons = document.querySelectorAll('.original-class-1'); for (const button of buttons ) { button.style.removeAllProperties(); // Does something like this exist? button.classList.add('my-styles'); } </code></pre> <p>To be clear, the original classes are adding styles from an <strong>external</strong> stylesheet, I've only put them in <code>&lt;style&gt;</code> tags above for illustration purposes.</p>
[ { "answer_id": 74368668, "author": "glennpai", "author_id": 20454514, "author_profile": "https://Stackoverflow.com/users/20454514", "pm_score": 0, "selected": false, "text": "window.onload = () => {\n const buttons = document.querySelectorAll('.original-class-1');\n buttons.forEach(button => button.setAttribute('class', 'my-styles'));\n}" }, { "answer_id": 74368714, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": ".my-" }, { "answer_id": 74368826, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": "const button = document.querySelector(\"button\");\n\n\nconst element = document.getElementsByClassName(\"myclass\")[0];\nconst cssObj = window.getComputedStyle(element);\n\n\n\n\nbutton.addEventListener('click', function(e) {\n for (x in cssObj) {\n cssObjProp = cssObj.item(x)\n let val = cssObj.getPropertyValue(cssObjProp);\n element.style.setProperty(val, \"initial\");\n }\n});" }, { "answer_id": 74368865, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 1, "selected": false, "text": "all: revert" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512787/" ]
74,368,133
<p>I want to delete all lines that start with comments and print statements from my file.</p> <p>This code works on lines that don't start with indents:</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;in.py&quot;, &quot;r&quot;) as file_input: with open(&quot;out.py&quot;, &quot;w&quot;) as file_output: for line in file_input: if line.startswith('#'): continue if line.startswith('print'): continue file_output.write(line) </code></pre> <p>But on lines that start with indents this does not work.</p> <p>So this file_input:</p> <pre class="lang-py prettyprint-override"><code># comment 1 def foo(): # comment 2 x = 1 print(x) print(x) </code></pre> <p>returns this file_output:</p> <pre class="lang-py prettyprint-override"><code>def foo(): # comment 2 x = 1 print(x) </code></pre> <p>But I want it to return this:</p> <pre class="lang-py prettyprint-override"><code>def foo(): x = 1 </code></pre> <p>How do you write this?</p>
[ { "answer_id": 74368668, "author": "glennpai", "author_id": 20454514, "author_profile": "https://Stackoverflow.com/users/20454514", "pm_score": 0, "selected": false, "text": "window.onload = () => {\n const buttons = document.querySelectorAll('.original-class-1');\n buttons.forEach(button => button.setAttribute('class', 'my-styles'));\n}" }, { "answer_id": 74368714, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": ".my-" }, { "answer_id": 74368826, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": "const button = document.querySelector(\"button\");\n\n\nconst element = document.getElementsByClassName(\"myclass\")[0];\nconst cssObj = window.getComputedStyle(element);\n\n\n\n\nbutton.addEventListener('click', function(e) {\n for (x in cssObj) {\n cssObjProp = cssObj.item(x)\n let val = cssObj.getPropertyValue(cssObjProp);\n element.style.setProperty(val, \"initial\");\n }\n});" }, { "answer_id": 74368865, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 1, "selected": false, "text": "all: revert" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19912573/" ]
74,368,164
<p>i have a homework but i cant get the answer I need to write a program in C... Here is what is needed: You need to enter &quot;n&quot; natural number as input , and from all the natural numbers smaller than &quot;n&quot; , its needed to print the number which has the highest sum of devisors. For exp: INPUT 10 , OUTPUT 8 Can anyone help me somehow? I would really appreciate it !</p> <p>i tried writing a program for finding the devisor of a number but i cant get far from here</p> <pre><code>#include &lt;stdio.h&gt; int main() { int x, i; printf(&quot;\nInput an integer: &quot;); scanf(&quot;%d&quot;, &amp;x); printf(&quot;All the divisor of %d are: &quot;, x); for(i = 1; i &lt; x; i++) { if((x%i) == 0){ printf(&quot;\n%d&quot;, i); } } } </code></pre>
[ { "answer_id": 74368668, "author": "glennpai", "author_id": 20454514, "author_profile": "https://Stackoverflow.com/users/20454514", "pm_score": 0, "selected": false, "text": "window.onload = () => {\n const buttons = document.querySelectorAll('.original-class-1');\n buttons.forEach(button => button.setAttribute('class', 'my-styles'));\n}" }, { "answer_id": 74368714, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": ".my-" }, { "answer_id": 74368826, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": "const button = document.querySelector(\"button\");\n\n\nconst element = document.getElementsByClassName(\"myclass\")[0];\nconst cssObj = window.getComputedStyle(element);\n\n\n\n\nbutton.addEventListener('click', function(e) {\n for (x in cssObj) {\n cssObjProp = cssObj.item(x)\n let val = cssObj.getPropertyValue(cssObjProp);\n element.style.setProperty(val, \"initial\");\n }\n});" }, { "answer_id": 74368865, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 1, "selected": false, "text": "all: revert" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10736084/" ]
74,368,169
<p>Example: {10,4,6,-1,23,11,5}</p> <p>Output: (4,6),(-1,5),(6,5)</p> <p>The reasoning behind this is the fact that 4+6=10, -1+5=4, and 6+5=11</p> <p>The mentioned pairs add up to another existent value in the same array, and it doesn't matter which order they are displayed in</p> <p>I did the classic brute-force, with 3 nested for-loops, on paper using a pen (this is the test that I had for a paid academy..)</p> <p>And of course it is not ok - and thus I require your help, thank you!</p>
[ { "answer_id": 74368668, "author": "glennpai", "author_id": 20454514, "author_profile": "https://Stackoverflow.com/users/20454514", "pm_score": 0, "selected": false, "text": "window.onload = () => {\n const buttons = document.querySelectorAll('.original-class-1');\n buttons.forEach(button => button.setAttribute('class', 'my-styles'));\n}" }, { "answer_id": 74368714, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": ".my-" }, { "answer_id": 74368826, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": "const button = document.querySelector(\"button\");\n\n\nconst element = document.getElementsByClassName(\"myclass\")[0];\nconst cssObj = window.getComputedStyle(element);\n\n\n\n\nbutton.addEventListener('click', function(e) {\n for (x in cssObj) {\n cssObjProp = cssObj.item(x)\n let val = cssObj.getPropertyValue(cssObjProp);\n element.style.setProperty(val, \"initial\");\n }\n});" }, { "answer_id": 74368865, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 1, "selected": false, "text": "all: revert" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17002711/" ]
74,368,181
<p>I'm trying to create a JWT with joken</p> <pre><code>privKey = &quot;&quot;&quot; -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- &quot;&quot;&quot; signer = Joken.Signer.create(&quot;Ed25519&quot;, %{&quot;pem&quot; =&gt; privKey}) Joken.generate_and_sign!(%{}, %{&quot;name&quot; =&gt; &quot;John Doe&quot;}, signer) </code></pre> <p>I receive the error</p> <pre><code>** (FunctionClauseError) no function clause matching in :jose_jwk_kty_ec.parameters_to_crv/1 The following arguments were given to :jose_jwk_kty_ec.parameters_to_crv/1: # 1 :ed25519 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:410: :jose_jwk_kty_ec.parameters_to_crv/1 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:389: :jose_jwk_kty_ec.jws_alg_to_digest_type/2 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:199: :jose_jwk_kty_ec.sign/3 (jose 1.11.2) src/jws/jose_jws.erl:311: :jose_jws.sign/4 (jose 1.11.2) src/jwt/jose_jwt.erl:173: :jose_jwt.sign/3 (joken 2.5.0) lib/joken/signer.ex:128: Joken.Signer.sign/2 (joken 2.5.0) lib/joken.ex:361: Joken.encode_and_sign/3 iex:6: (file) </code></pre> <p>What is causing the error, I had a look at the code on <a href="https://github.com/joken-elixir/joken/issues/214" rel="nofollow noreferrer">https://github.com/joken-elixir/joken/issues/214</a> to try and fix it but couldn't.</p>
[ { "answer_id": 74368668, "author": "glennpai", "author_id": 20454514, "author_profile": "https://Stackoverflow.com/users/20454514", "pm_score": 0, "selected": false, "text": "window.onload = () => {\n const buttons = document.querySelectorAll('.original-class-1');\n buttons.forEach(button => button.setAttribute('class', 'my-styles'));\n}" }, { "answer_id": 74368714, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": ".my-" }, { "answer_id": 74368826, "author": "Ronnie Royston", "author_id": 4797603, "author_profile": "https://Stackoverflow.com/users/4797603", "pm_score": 0, "selected": false, "text": "const button = document.querySelector(\"button\");\n\n\nconst element = document.getElementsByClassName(\"myclass\")[0];\nconst cssObj = window.getComputedStyle(element);\n\n\n\n\nbutton.addEventListener('click', function(e) {\n for (x in cssObj) {\n cssObjProp = cssObj.item(x)\n let val = cssObj.getPropertyValue(cssObjProp);\n element.style.setProperty(val, \"initial\");\n }\n});" }, { "answer_id": 74368865, "author": "traktor", "author_id": 5217142, "author_profile": "https://Stackoverflow.com/users/5217142", "pm_score": 1, "selected": false, "text": "all: revert" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950147/" ]
74,368,253
<p>Having a table such as follows:</p> <pre><code>CREATE TABLE Associations ( obj_id int unsigned NOT NULL, attr_id int unsigned NOT NULL, assignment Double NOT NULL PRIMARY KEY (`obj_id`, `attr_id`), ); </code></pre> <p>this should occupy 16 bytes per row. So the overhead per row is small.<br /> I need to use this as a look up table where the main query would be:</p> <pre><code>SELECT WHERE obj_id IN (... thousands and thousands of ids....). </code></pre> <p>Taking these into account along with the fact that the table will be ~500 million rows, is there anything more to consider for good performance? The table with this number of rows would occupy ~8GB which seems reasonable size in general.<br /> Is there any further improvements to do here?</p>
[ { "answer_id": 74368313, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "IN()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9055634/" ]
74,368,267
<p>How do I query join two tables and sum distinct values in a column?</p> <p>Given Parent:</p> <p><a href="https://i.stack.imgur.com/wtaAl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wtaAl.png" alt="[![enter image description here](https://i.stack.imgur.com/iYLj1.png)](https://i.stack.imgur.com/iYLj1.png)" /></a></p> <p>Given Child:</p> <p><a href="https://i.stack.imgur.com/5eh3A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5eh3A.png" alt="enter image description here" /></a></p> <p>Expected Result:</p> <p><a href="https://i.stack.imgur.com/CUBnA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CUBnA.png" alt="enter image description here" /></a></p> <pre><code>from app import db_con from sqlalchemy import ForeignKey from sqlalchemy.dialects import mssql class Parent(db_con.Model): __tablename__ = &quot;parent&quot; ID = db_con.Column( &quot;id&quot;, mssql.INTEGER, nullable=False, primary_key=True ) COST = db_con.Column(&quot;cost&quot;, mssql.DECIMAL) CATEGORY_ID = db_con.Column(&quot;category_id&quot;, mssql.INTEGER, ForeignKey(&quot;child.category_id&quot;)) CATEGORY = db_con.relationship(&quot;Child&quot;, foreign_keys=[ID], uselist=False) class Child(db_con.Model): __tablename__ = &quot;child&quot; CATEGORY_ID = db_con.Column(&quot;category_id&quot;, mssql.INTEGER, nullable=False, primary_key=True) NAME = db_con.Column(&quot;name&quot;, mssql.NVARCHAR(None)) </code></pre>
[ { "answer_id": 74368313, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "IN()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19639266/" ]
74,368,288
<p>i have a dataset with three columns, small example:</p> <pre><code> A B 1 sety NA 2 NA bety 3 NA bety 4 sety bety 5 sety NA </code></pre> <p>how can i plot a pieplot where i have percentage of people having sety, percentage of people having bety, and percentage of people having both sety and bety, in the example above , the percents are respectively 60%?, 60%, 20%, The third percent must show as overlap between the first two.</p> <p>may be something like this :</p> <p><a href="https://i.stack.imgur.com/Je6KR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Je6KR.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74369107, "author": "stomper", "author_id": 9227264, "author_profile": "https://Stackoverflow.com/users/9227264", "pm_score": 0, "selected": false, "text": "\nlibrary(ggplot2)\nlibrary(stringr)\nlibrary(dplyr)\n\n#initial dataset\ndata <- data.frame(A = c(\"sety\", NA, NA, \"sety\", \"sety\"), B = c(NA, \"bety\", \"bety\", \"bety\", NA))\n\n#combine values and remove the NA\ndata$C <- str_remove_all(paste0(data$A, data$B), \"NA\")\n\n#get frequency of each value\nfreq <- data %>%\n group_by(C) %>%\n select(C) %>%\n summarize(count = n())\n\n#plot\nggplot(freq, aes(x=\"\", y=count, fill = C))+\n geom_bar(stat=\"identity\", width = 1) +\n coord_polar(\"y\", start = 0)\n" }, { "answer_id": 74382418, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "ymin" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14030805/" ]
74,368,289
<p>I have a dataset that looks something like this in R:</p> <pre><code>address = c(&quot;882 4N Road River NY, NY 12345&quot;, &quot;882 - River Road NY, ZIP 12345&quot;, &quot;123 Fake Road Boston Drive Boston&quot;, &quot;123 Fake - Rd Boston 56789&quot;) name = c(&quot;ABC Center Building&quot;, &quot;Cent. Bldg ABC&quot;, &quot;BD Home 25 New&quot;, &quot;Boarding Direct 25&quot;) my_data = data.frame(address, name) address name 1 882 4N Road River NY, NY 12345 ABC Center Building 2 882 - River Road NY, ZIP 12345 Cent. Bldg ABC 3 123 Fake Road Boston Drive Boston BD Home 25 New 4 123 Fake - Rd Boston 56789 Boarding Direct 25 </code></pre> <p>Looking at this data, it is clear that the first two rows are the same and the second two rows are the same. However, if you tried to remove duplicates directly, standard functions (e.g. &quot;<code>distinct()</code>&quot;) would state that there are no duplicates in this dataset, seeing as all rows have some unique element.</p> <p>I have been trying to research different methods in R that are able to de-duplicate rows based on &quot;fuzzy conditions&quot;.</p> <p>Based on the answers provided here (<a href="https://stackoverflow.com/questions/6683380/techniques-for-finding-near-duplicate-records">Techniques for finding near duplicate records</a>), I came across this method called &quot;Record Linkage&quot;. I came across this specific tutorial over here (<a href="https://cran.r-project.org/web/packages/RecordLinkage/vignettes/WeightBased.pdf" rel="nofollow noreferrer">https://cran.r-project.org/web/packages/RecordLinkage/vignettes/WeightBased.pdf</a>) that might be able to perform a similar task, but I am not sure if this is intended for the problem I am working on.</p> <ul> <li><p>Can someone please help me confirm if this Record Linkage tutorial is in fact relevant to the problem I am working on - and if so, could someone please show me how to use it?</p> </li> <li><p>For example, I would like to remove duplicates based on the name and address - and only have two rows remaining (i.e. one row from row1/row2 and one row from row3/row4 - which ever one is chosen doesn't really matter).</p> </li> <li><p>As another example - suppose I wanted to try this and only de-duplicate based on the &quot;address&quot; column: is this also possible?</p> </li> </ul> <p>Can someone please show me how this could work?</p> <p>Thank you!</p> <p>Note: I have heard some options about using SQL JOINS along with FUZZY JOINS (e.g. <a href="https://cran.r-project.org/web/packages/fuzzyjoin/readme/README.html" rel="nofollow noreferrer">https://cran.r-project.org/web/packages/fuzzyjoin/readme/README.html</a>) - but I am not sure if this option is also suitable.</p>
[ { "answer_id": 74408721, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": false, "text": "stringdist::stringdist()" }, { "answer_id": 74458813, "author": "JBGruber", "author_id": 5028841, "author_profile": "https://Stackoverflow.com/users/5028841", "pm_score": 2, "selected": false, "text": "library(tidyverse)\nlibrary(quanteda)\nlibrary(quanteda.textstats)\nlibrary(stringdist)\n" }, { "answer_id": 74468705, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "agrep" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,368,348
<p>With the new NextJS 13 introducing the <code>app</code> directory, would redux still make sense?</p> <p>It's already possible to wrap redux providers around a <strong>Client Component</strong> as per next docs. But how would sharing states with redux impact Next performance and optmization?</p> <p>Next docs ask to fetch data where the data is needed instead of passing down the component tree. Request will be <a href="https://beta.nextjs.org/docs/data-fetching/fundamentals#automatic-fetch-request-deduping" rel="noreferrer">automatically deduped</a>.</p> <p>My usage for Redux would be to control certain pieces of the application that I want to be consistent.</p> <p><em>E.g: If I change an user name I want that reflected in the whole application where that data is needed.</em></p>
[ { "answer_id": 74499505, "author": "Konrad", "author_id": 20547013, "author_profile": "https://Stackoverflow.com/users/20547013", "pm_score": 2, "selected": false, "text": " \"use client\";\n\nimport { useServerInsertedHTML } from \"next/navigation\";\nimport { CssBaseline, NextUIProvider } from \"@nextui-org/react\";\nimport { PropsWithChildren } from \"react\";\nimport ReduxProvider from \"./redux-provider\";\n\ntype P = PropsWithChildren;\n\nexport default function Providers({ children }: P) {\n useServerInsertedHTML(() => {\n return <>{CssBaseline.flush()}</>;\n });\n\n return ( // you can have multiple client side providers wrapped, in this case I am also using NextUIProvider\n <>\n <ReduxProvider>\n <NextUIProvider>{children}</NextUIProvider>\n </ReduxProvider>\n </>\n );\n}\n" }, { "answer_id": 74598602, "author": "friartuck", "author_id": 7424878, "author_profile": "https://Stackoverflow.com/users/7424878", "pm_score": 0, "selected": false, "text": "utils/database.js\n\nexport const db = new DatabaseConnection(...);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11252466/" ]
74,368,366
<p>I've used terraform to setup infra for an s3 bucket and my containerised lambda. I want to trigger the lambda to list the items in my s3 bucket. When I run the aws cli it's fine:</p> <pre><code>aws s3 ls </code></pre> <p>returns</p> <pre><code>2022-11-08 23:04:19 bucket-name </code></pre> <p>This is my lambda:</p> <pre><code>import logging import boto3 LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.DEBUG) s3 = boto3.resource('s3') def lambda_handler(event, context): LOGGER.info('Executing function...') bucket = s3.Bucket('bucket-name') total_objects = 0 for i in bucket.objects.all(): total_objects = total_objects + 1 return {'total_objects': total_objects} </code></pre> <p>When I run the test in the AWS console, I'm getting this:</p> <pre><code>[ERROR] ClientError: An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied </code></pre> <p>No idea why this is happening. These are my terraform lambda policies, roles and the s3 setup:</p> <pre><code>resource &quot;aws_s3_bucket&quot; &quot;statements_bucket&quot; { bucket = &quot;bucket-name&quot; acl = &quot;private&quot; } resource &quot;aws_s3_object&quot; &quot;object&quot; { bucket = aws_s3_bucket.statements_bucket.id key = &quot;excel/&quot; } resource &quot;aws_iam_role&quot; &quot;lambda&quot; { name = &quot;${local.prefix}-lambda-role&quot; path = &quot;/&quot; assume_role_policy = &lt;&lt;EOF { &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Action&quot;: &quot;sts:AssumeRole&quot;, &quot;Principal&quot;: { &quot;Service&quot;: &quot;lambda.amazonaws.com&quot; }, &quot;Effect&quot;: &quot;Allow&quot; } ] } EOF } resource &quot;aws_iam_policy&quot; &quot;lambda&quot; { name = &quot;${local.prefix}-lambda-policy&quot; description = &quot;S3 specified access&quot; policy = &lt;&lt;EOF { &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: [ &quot;s3:ListBucket&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::bucket-name&quot; ] }, { &quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: [ &quot;s3:PutObject&quot;, &quot;s3:GetObject&quot;, &quot;s3:DeleteObject&quot; ], &quot;Resource&quot;: [ &quot;arn:aws:s3:::bucket-name/*&quot; ] } ] } EOF } </code></pre>
[ { "answer_id": 74368438, "author": "dawaltco", "author_id": 8051300, "author_profile": "https://Stackoverflow.com/users/8051300", "pm_score": 2, "selected": false, "text": "aws s3 ls" }, { "answer_id": 74368659, "author": "jarmod", "author_id": 271415, "author_profile": "https://Stackoverflow.com/users/271415", "pm_score": 3, "selected": true, "text": "resource \"aws_iam_role_policy_attachment\" \"lambda-attach\" {\n role = aws_iam_role.role.name\n policy_arn = aws_iam_policy.policy.arn\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2482149/" ]
74,368,373
<p>I have a map that contains Keys and Values. i want to transfer it to a List and sort it by value first (integer) and then by Key (String) . This is , it sorts by value but if theres a tie in the value, i want to &quot;untie&quot; it by sorting it in Alphabetical order. Is there any kotlin , java function that does this? Thanks in advance</p>
[ { "answer_id": 74368439, "author": "radof", "author_id": 20349343, "author_profile": "https://Stackoverflow.com/users/20349343", "pm_score": 2, "selected": true, "text": "yourMap.toList()" }, { "answer_id": 74368530, "author": "Stefan Haustein", "author_id": 1401879, "author_profile": "https://Stackoverflow.com/users/1401879", "pm_score": 2, "selected": false, "text": "compareBy" }, { "answer_id": 74368580, "author": "Kripthonite", "author_id": 8934039, "author_profile": "https://Stackoverflow.com/users/8934039", "pm_score": 0, "selected": false, "text": "fun <T, U> pairComparator(\n firstComparator: Comparator<T>,\n secondComparator: Comparator<U>\n): Comparator<Pair<T, U>> =\n compareBy(secondComparator) { p: Pair<T, U> -> p.second }\n .thenBy(firstComparator) { p: Pair<T, U> -> p.first }\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8934039/" ]
74,368,380
<p>I am trying to combine flexible modelling functions (using tidyeval) and then mapping over data in a nested dataframe (and attempting to learn tidy evaluation along the way). I am running into the problems of inlining expressions with the captured call (I think). Any suggestion, examples, tips, or best practices for writing wrappers to simplify repetitive modelling tasks and then using them with purrr::map etc?</p> <p>The example below is based on the section wrapping modelling functions from <a href="https://adv-r.hadley.nz/evaluation.html#wrapping-modelling-functions" rel="nofollow noreferrer">20 Evaluation | Advanced R</a> using the mtcars data.</p> <pre><code>library(rlang) library(tidyverse) lm_wrap &lt;- function(data, traits, resp, env = caller_env(), ...) { traits &lt;- enexpr(traits) resp &lt;- enexpr(resp) data &lt;- enexpr(data) dots &lt;- enexprs(...) lm_call &lt;- inject(lm(!!resp ~ !!traits, data = !!data, !!!dots), env) return(lm_call) } </code></pre> <p>The wrapper function works for single cases</p> <pre><code>lm_wrap(traits = hp, data = mtcars, resp = mpg) #Call: #lm(formula = mpg ~ hp, data = mtcars) #Coefficients: #(Intercept) hp # 30.09886 -0.06823 </code></pre> <p>But looks like it runs into the problems of inlining expressions, at least as per this somewhat related example <a href="https://adv-r.hadley.nz/evaluation.html#evaluation-environment" rel="nofollow noreferrer">20 Evaluation | Advanced R</a></p> <pre><code>mt_nested &lt;- mtcars %&gt;% group_by(cyl) %&gt;% nest() %&gt;% mutate(model = map(data, lm_wrap, resp = mpg, traits = hp)) mt_nested$model[[1]]$call #lm(formula = mpg ~ hp, data = list(mpg = c(21, 21, 21.4, 18.1, #19.2, 17.8, 19.7), disp = c(160, 160, 258, 225, 167.6, 167.6, #145), hp = c(110, 110, 110, 105, 123, 123, 175), drat = c(3.9, #3.9, 3.08, 2.76, 3.92, 3.92, 3.62), wt = c(2.62, 2.875, 3.215, #3.46, 3.44, 3.44, 2.77), qsec = c(16.46, 17.02, 19.44, 20.22, #18.3, 18.9, 15.5), vs = c(0, 0, 1, 1, 1, 1, 0), am = c(1, 1, #0, 0, 0, 0, 1), gear = c(4, 4, 3, 3, 4, 4, 5), carb = c(4, 4, #1, 1, 4, 4, 6))) </code></pre> <p>Thanks in advance,</p> <p>M.</p>
[ { "answer_id": 74368689, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 0, "selected": false, "text": "data" }, { "answer_id": 74371125, "author": "Lionel Henry", "author_id": 1725177, "author_profile": "https://Stackoverflow.com/users/1725177", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74375540, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 0, "selected": false, "text": "library(rlang)\nlibrary(tidyverse)\n\n\nlm_wrap <- function(data, traits, resp, env = caller_env(), ...) {\n traits <- enexpr(traits)\n resp <- enexpr(resp)\n data <- enexpr(data)\n dots <- enexprs(...)\n lm_call <- inject(lm(!!resp ~ !!traits, data = !!data, !!!dots), env)\n return(lm_call)\n}\n\nmt_nested <- mtcars %>% group_by(cyl) %>% \n group_modify( ~ tibble(\n data = list(.x), \n model = list(lm_wrap(mtcars %>% filter(cyl==!!.y$cyl), resp = mpg, traits = hp))))\n\nmt_nested$model[[1]]$call\n\n#> lm(formula = mpg ~ hp, data = mtcars %>% filter(cyl == 4))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454416/" ]
74,368,393
<p>I'm trying to follow <a href="https://blog.syncfusion.com/blogs/post/learn-how-to-use-dependency-injection-in-net-maui.aspx#:%7E:text=Let%E2%80%99s%20bind%20the%20LabelText%20property%20to%20the%20Label,in%20your%20desired%20class%20constructors.%20...%20More%20items" rel="nofollow noreferrer">this article</a> on .NET MAUI dependency injection.</p> <p>My MauiProgram.cs</p> <pre><code>public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp&lt;App&gt;() .UseMauiCommunityToolkit() .ConfigureFonts(fonts =&gt; { fonts.AddFont(&quot;OpenSans-Regular.ttf&quot;, &quot;OpenSansRegular&quot;); fonts.AddFont(&quot;OpenSans-Semibold.ttf&quot;, &quot;OpenSansSemibold&quot;); }); builder.Services.AddSingleton&lt;IDataService, DataService&gt;(); builder.Services.AddTransient&lt;NavigationService&gt;(); builder.Services.AddTransient&lt;ValidationService&gt;(); builder.Services.AddSingleton&lt;BudgetViewPage&gt;(); builder.Services.AddSingleton&lt;BudgetViewModel&gt;(); builder.Services.AddSingleton&lt;AccountsViewModel&gt;(); builder.Services.AddSingleton&lt;FlyoutMenuRoot&gt;(); return builder.Build(); } } </code></pre> <p>My App.xaml.cs</p> <pre><code>public partial class App : Application { public App(FlyoutMenuRoot flyoutMenuRoot) { InitializeComponent(); MainPage = flyoutMenuRoot; } } </code></pre> <p>My FlyoutMenuRoot.xaml.cs</p> <pre><code>public partial class FlyoutMenuRoot : FlyoutPage { IDataService dataService; BudgetViewModel budgetViewModel; private NavigationService NavigationService = new(); public FlyoutMenuRoot(IDataService dataService, BudgetViewModel budgetViewModel) { InitializeComponent(); this.dataService = dataService; this.budgetViewModel = budgetViewModel; Detail = new NavigationPage(new BudgetViewPage(budgetViewModel)); flyoutMenuRoot.flyoutCollectionView.SelectionChanged += OnSelectionChanged; } void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var item = e.CurrentSelection.FirstOrDefault() as FlyoutPageItem; if(item != null) { if(item.TargetType == typeof(SelectAccountPage)) { NavigationService.PushToStack((Page)Activator.CreateInstance(item.TargetType, new AccountsViewModel(dataService, budgetViewModel))); } else { NavigationService.PushToStack((Page)Activator.CreateInstance(item.TargetType)); } this.IsPresented = false; flyoutMenuRoot.flyoutCollectionView.SelectedItem = null; } } } </code></pre> <p>Based on the linked article, this should work, but my app crashes on the splash screen.</p> <p>If my App.xaml.cs is this:</p> <pre><code>public partial class App : Application { public App() { InitializeComponent(); DataService dataService = new(); BudgetViewModel budgetViewModel = new(dataService); MainPage = new FlyoutMenuRoot(dataService, budgetViewModel); } } </code></pre> <p>Then it works with no problem.</p> <p>My understanding is that you shouldn't have to new() up an instance of your classes with Dependency Injection, that the container will do it automatically for you based on what's listed in the constructor. I'm following the article, so why is it crashing?</p> <p>Edit:</p> <p>I stepped through the code and narrowed the crash down to the InitializeComponent() call under FlyoutMenuPage()</p> <pre><code>public partial class FlyoutMenuPage : ContentPage { public FlyoutMenuPage() { try { InitializeComponent(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } </code></pre> <p>The message written to the output window is: <code>[DOTNET] Position 11:5. StaticResource not found for key Primary</code></p> <p>That's referencing this line in the FlyoutMenuPage.xaml <code>BackgroundColor=&quot;{StaticResource Primary}&quot;</code> This is confounding because that line never threw an exception until I tried following the method for DI from the article. If I go back to constructor injection, it doesn't crash.</p>
[ { "answer_id": 74368689, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 0, "selected": false, "text": "data" }, { "answer_id": 74371125, "author": "Lionel Henry", "author_id": 1725177, "author_profile": "https://Stackoverflow.com/users/1725177", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74375540, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 0, "selected": false, "text": "library(rlang)\nlibrary(tidyverse)\n\n\nlm_wrap <- function(data, traits, resp, env = caller_env(), ...) {\n traits <- enexpr(traits)\n resp <- enexpr(resp)\n data <- enexpr(data)\n dots <- enexprs(...)\n lm_call <- inject(lm(!!resp ~ !!traits, data = !!data, !!!dots), env)\n return(lm_call)\n}\n\nmt_nested <- mtcars %>% group_by(cyl) %>% \n group_modify( ~ tibble(\n data = list(.x), \n model = list(lm_wrap(mtcars %>% filter(cyl==!!.y$cyl), resp = mpg, traits = hp))))\n\nmt_nested$model[[1]]$call\n\n#> lm(formula = mpg ~ hp, data = mtcars %>% filter(cyl == 4))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277304/" ]
74,368,395
<p>I am trying to generate 1000 random samples and need to put if the p-value of the test for each sample is larger than alpha in reject_collect object and if the true mean of 10 is in the CI of each sample generated. My objects currently only have 1 value. Not sure how to fix it.</p> <pre><code>reject_collect &lt;- NULL CI_include_collect &lt;- NULL for ( i in c(1:1000)) { random_vector_index &lt;- rnorm( 50, mean = 10, sd = 2) alpha &lt;- 0.05 mean(random_vector_index) test_results_index &lt;- t.test(random_vector_index, mu=10, alternative = &quot;two.sided&quot;, conf.level = 0.95) test_results_index$p.value reject_collect &lt;- test_results_index$p.value &lt; alpha CI_include_collect &lt;- between(10, test_results_index$conf.int[1], test_results_index$conf.int[2]) } </code></pre>
[ { "answer_id": 74368701, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 1, "selected": true, "text": "reject_collect" }, { "answer_id": 74368712, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n \n tibble(replicate = 1:1000) |>\n mutate(random_vector_index = map(replicate, \\(x) {\n set.seed(x)\n rnorm( 50, mean = 10, sd = 2)\n }),\n test_results_index = map(random_vector_index, \n \\(x) t.test(x,\n mu=10,\n alternative = \"two.sided\",\n conf.level = 0.95)),\n p.value = map_dbl(test_results_index, \\(x) x$p.value),\n reject_collect = map_lgl(p.value, \\(x) x < 0.05),\n CI_include_collect = map_lgl(test_results_index, \n \\(x) between(10,\n x$conf.int[1],\n x$conf.int[2]))) |>\n select(replicate, p.value, reject_collect, reject_collect, CI_include_collect)\n#> # A tibble: 1,000 x 4\n#> replicate p.value reject_collect CI_include_collect\n#> <int> <dbl> <lgl> <lgl> \n#> 1 1 0.397 FALSE TRUE \n#> 2 2 0.667 FALSE TRUE \n#> 3 3 0.614 FALSE TRUE \n#> 4 4 0.0767 FALSE TRUE \n#> 5 5 0.669 FALSE TRUE \n#> 6 6 0.562 FALSE TRUE \n#> 7 7 0.101 FALSE TRUE \n#> 8 8 0.678 FALSE TRUE \n#> 9 9 0.503 FALSE TRUE \n#> 10 10 0.00758 TRUE FALSE \n#> # ... with 990 more rows\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454445/" ]
74,368,411
<p>In my attempt to start using TensorFlow on my mac [Monterey 12.6.1] [chip Apple M1 MAX] I start to get errors that I did not observe on my mac mini [Monterey 12.6 - Chip M1 2020]</p> <p>It is either an environment issue or a chipset issue. [Works on my windows machine Win-11 and Mac-Mini]</p> <p>Code:</p> <pre><code>from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras import layers model = Sequential([layers.Input((3, 1)), layers.LSTM(64), layers.Dense(32, activation='relu'), layers.Dense(32, activation='relu'), layers.Dense(1)]) model.compile(loss='mse', optimizer=Adam(learning_rate=0.001), metrics=['mean_absolute_error']) model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=100) </code></pre> <p>Error observed in DataSpell:</p> <pre><code>-------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xe </code></pre> <p>Traceback</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [14], in &lt;cell line: 1&gt;() ----&gt; 1 from tensorflow.keras.models import Sequential 2 from tensorflow.keras.optimizers import Adam 3 from tensorflow.keras import layers </code></pre> <p>Following Greg Hogg tutorial: <a href="https://www.youtube.com/watch?v=CbTU92pbDKw" rel="nofollow noreferrer">https://www.youtube.com/watch?v=CbTU92pbDKw</a></p> <p>Note this code work on my mac mini machine but not on the MacBook Pro. Anaconda env -&gt; Python 3.9</p> <hr /> <pre><code>python --version Python 3.9.12 conda list | grep tensorflow tensorflow-deps 2.8.0 0 apple tensorflow-estimator 2.10.0 pypi_0 pypi tensorflow-macos 2.10.0 pypi_0 pypi tensorflow-metal 0.6.0 pypi_0 pypi </code></pre> <p>What I am expecting is similar outcome like the windows environment and the Mac-mini where the model is constructed and fitted with the training data. (model object creation without an exception)</p> <p>Example:</p> <pre><code>Epoch 99/100 7/7 [==============================] - 0s 5ms/step - loss: 6.1541 - mean_absolute_error: 1.8648 - val_loss: 9.5456 - val_mean_absolute_error: 2.6235 Epoch 100/100 7/7 [==============================] - 0s 5ms/step - loss: 6.7555 - mean_absolute_error: 2.0134 - val_loss: 9.4403 - val_mean_absolute_error: 2.6016 &lt;keras.callbacks.History at 0x27a6590c6a0&gt; </code></pre> <p>Attempting the numpy upgrade posted answer, I did the &quot;numpy upgrade&quot; yet had the output below on the terminal and the same exception still observed.</p> <pre><code>pip install numpy --upgrade Requirement already satisfied: numpy in ./opt/anaconda3/lib/python3.9/site-packages (1.21.5) Collecting numpy Using cached numpy-1.23.4-cp39-cp39-macosx_11_0_arm64.whl (13.4 MB) Installing collected packages: numpy Attempting uninstall: numpy Found existing installation: numpy 1.21.5 Uninstalling numpy-1.21.5: Successfully uninstalled numpy-1.21.5 ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. scipy 1.7.3 requires numpy&lt;1.23.0,&gt;=1.16.5, but you have numpy 1.23.4 which is incompatible. numba 0.55.1 requires numpy&lt;1.22,&gt;=1.18, but you have numpy 1.23.4 which is incompatible. Successfully installed numpy-1.23.4 </code></pre> <p>==================================</p> <p>So combination of multiple approaches fixed the issue:</p> <ol> <li>pip uninstall keras</li> <li>pip uninstall keras-preprocessing</li> <li>pip uninstall tensorboard</li> <li>pip install --upgrade numpy</li> <li>If step 4 does not work [error or concerning warning], then pip uninstall numpy ; followed by pip install numpy</li> <li>python -m pip install tensorflow-macos That fix my environment problem.</li> </ol>
[ { "answer_id": 74368701, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 1, "selected": true, "text": "reject_collect" }, { "answer_id": 74368712, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n \n tibble(replicate = 1:1000) |>\n mutate(random_vector_index = map(replicate, \\(x) {\n set.seed(x)\n rnorm( 50, mean = 10, sd = 2)\n }),\n test_results_index = map(random_vector_index, \n \\(x) t.test(x,\n mu=10,\n alternative = \"two.sided\",\n conf.level = 0.95)),\n p.value = map_dbl(test_results_index, \\(x) x$p.value),\n reject_collect = map_lgl(p.value, \\(x) x < 0.05),\n CI_include_collect = map_lgl(test_results_index, \n \\(x) between(10,\n x$conf.int[1],\n x$conf.int[2]))) |>\n select(replicate, p.value, reject_collect, reject_collect, CI_include_collect)\n#> # A tibble: 1,000 x 4\n#> replicate p.value reject_collect CI_include_collect\n#> <int> <dbl> <lgl> <lgl> \n#> 1 1 0.397 FALSE TRUE \n#> 2 2 0.667 FALSE TRUE \n#> 3 3 0.614 FALSE TRUE \n#> 4 4 0.0767 FALSE TRUE \n#> 5 5 0.669 FALSE TRUE \n#> 6 6 0.562 FALSE TRUE \n#> 7 7 0.101 FALSE TRUE \n#> 8 8 0.678 FALSE TRUE \n#> 9 9 0.503 FALSE TRUE \n#> 10 10 0.00758 TRUE FALSE \n#> # ... with 990 more rows\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454331/" ]
74,368,412
<p>I have a Django application with a health check endpoint that's using <a href="https://github.com/revsys/django-health-check" rel="nofollow noreferrer">django-health-check</a>.</p> <p>In the <code>url_patterns</code> I have added the following line:</p> <pre><code> url(r'^ht/', include('health_check.urls')), </code></pre> <p>The issue is that the health check is filling all the Sentry transaction limits.</p> <p>How can I exclude the health check endpoint in Sentry?</p>
[ { "answer_id": 74411586, "author": "Leo", "author_id": 6914106, "author_profile": "https://Stackoverflow.com/users/6914106", "pm_score": 0, "selected": false, "text": "before_breadcrumb" }, { "answer_id": 74412613, "author": "Antoine Pinsard", "author_id": 1529346, "author_profile": "https://Stackoverflow.com/users/1529346", "pm_score": 2, "selected": true, "text": "def traces_sampler(ctx):\n if 'wsgi_environ' in ctx:\n url = ctx['wsgi_environ'].get('PATH_INFO', '')\n if url.startswith('/ht/'):\n return 0 # Don't trace any\n return 1 # Trace all\n\nsentry_sdk.init(\n # ...\n traces_sampler=traces_sampler,\n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262198/" ]
74,368,414
<p>I've the following XML (consider it as normal text) :</p> <pre><code> &lt;TextView android:layout_width=&quot;15dp&quot; android:layout_height=&quot;match_parent&quot; android:textSize=&quot;1.5sp&quot; /&gt; </code></pre> <p>I'm using the following code to extract numbers, for example <strong>15</strong> and <strong>1.5</strong>:</p> <pre><code>let largeOutputResult = inputXML.replace(/(\d+)(sp|dp)/g, (_,num,end) =&gt; `${num*1.5}${end}`); </code></pre> <p>The issue I found is when I run the code, it extracts <strong>15</strong>, <strong>1</strong> and <strong>5</strong>, not <strong>1.5</strong>, how I can fix that?</p> <p>Thank you.</p>
[ { "answer_id": 74368433, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 3, "selected": true, "text": "const text = `\\\n<ImageView\n android:layout_width=\"15dp\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"1.5dp\"\n/>`;\n\nconst output = text.replace(/(\\d*\\.?\\d+)(sp|dp)/g, (_, num, end) => `${num * 1.5}${end}`);\n\nconsole.log(output);" }, { "answer_id": 74372054, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\d*\\.?\\d+(?=[sd]p\\b)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954210/" ]
74,368,422
<p>I am trying to print the value of a local variable inside of main, from another function without using global variables. What would be the best way to do so?</p> <pre><code>#include &lt;stdio.h&gt; int function1(); int main(void) { int hello=10; printf(function1()); } int function1(int ip){ printf(&quot;hello%d&quot;,ip); } </code></pre> <p>I am expecting the <code>10</code> to be printed next to the <code>&quot;hello&quot;</code> but instead get a 0.</p>
[ { "answer_id": 74368476, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": "int function1();\n" }, { "answer_id": 74368634, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": false, "text": "int function1(int);\n\nint main(void) \n{\n int hello=10;\n function1(hello);\n function1(130);\n}\n\nint function1(int ip)\n{\n return printf(\"hello - %d\\n\",ip); \n}\n" }, { "answer_id": 74376632, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 0, "selected": false, "text": "GCC" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453967/" ]
74,368,426
<p>I just can ignore this property and I will get the same result, right?</p> <p>If so, what is the meaning of using text-decoration: none; as a declaration in CSS.</p> <p>This is my first question.</p> <p>I'm trying to understand CSS and it's declaration's properties.</p>
[ { "answer_id": 74368476, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": "int function1();\n" }, { "answer_id": 74368634, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": false, "text": "int function1(int);\n\nint main(void) \n{\n int hello=10;\n function1(hello);\n function1(130);\n}\n\nint function1(int ip)\n{\n return printf(\"hello - %d\\n\",ip); \n}\n" }, { "answer_id": 74376632, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 0, "selected": false, "text": "GCC" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367989/" ]
74,368,490
<p>How to convert during(milliseconds) from long to readable String in Java, such as 5 minutes and 2 seconds or 2 hours if no trailing minutes or seconds?</p> <p>I have tried TimeUtils, but it still requires a little script to concatenate strings.</p>
[ { "answer_id": 74368476, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": "int function1();\n" }, { "answer_id": 74368634, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": false, "text": "int function1(int);\n\nint main(void) \n{\n int hello=10;\n function1(hello);\n function1(130);\n}\n\nint function1(int ip)\n{\n return printf(\"hello - %d\\n\",ip); \n}\n" }, { "answer_id": 74376632, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 0, "selected": false, "text": "GCC" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454500/" ]
74,368,491
<p>I have multiple lengths of array in variables and I need to find which variable is greater and just change the color of that variable font. I have done this but issue is if 2 variable have same values so I need to color both of them right now its just showing one.</p> <p>My code</p> <pre><code> calculateconfirm(location1, location2, location3, location4, type) { var max = Number.NEGATIVE_INFINITY; var max_key = undefined; var obj = { 'location1': location1, 'location2': location2, 'location3': location3, 'location4': location4 }; for (var key in obj) { if (obj[key] &gt; max) { max_key = key; max = obj[key]; } } return max_key == type ? '#5D3FD3' : '#301934'; } </code></pre> <p>Html</p> <pre><code> &lt;tr *ngFor=&quot;let x of userdata&quot;&gt; &lt;td&gt;&lt;img src=&quot;{{x.data.userImage}}&quot; alt=&quot;&quot; style=&quot;height: 75px; width: 75px;&quot;&gt;&lt;/td&gt; &lt;td&gt;{{x.data.fullName}}&lt;/td&gt; &lt;td *ngIf=&quot;x.data.location.location1 == 'false'&quot;&gt;N/A&lt;/td&gt; &lt;td *ngIf=&quot;x.data.location.location1 != 'false'&quot; [style.color]=&quot;calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location1')&quot;&gt; {{x.data.location.location1}} &lt;td *ngIf=&quot;x.data.location2.location2 == 'false'&quot;&gt;N/A&lt;/td&gt; &lt;td *ngIf=&quot;x.data.location2.location2 != 'false'&quot; [style.color]=&quot;calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location2')&quot;&gt; {{x.data.location2.location2}} &lt;td *ngIf=&quot;x.data.location3.location3 == 'false'&quot;&gt;N/A&lt;/td&gt; &lt;td *ngIf=&quot;x.data.location3.location3 != 'false'&quot; [style.color]=&quot;calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location3')&quot;&gt; {{x.data.location3.location3}} &lt;td *ngIf=&quot;x.data.location4.location4 == 'false'&quot;&gt;N/A&lt;/td&gt; &lt;td *ngIf=&quot;x.data.location4.location4 != 'false'&quot; [style.color]=&quot;calculateconfirm(x.data.location.like.length, x.data.location2.like.length, x.data.location3.like.length, x.data.location4.like.length, 'location4')&quot;&gt; {{x.data.location4.location4}} &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Lets assume I have Obj like this</p> <pre><code>var obj = { 'location1': 2, 'location2': 1, 'location3': 5, 'location4': 5 }; </code></pre> <p>So I need to color location 3 and 5 both in html.</p>
[ { "answer_id": 74368476, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": "int function1();\n" }, { "answer_id": 74368634, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": false, "text": "int function1(int);\n\nint main(void) \n{\n int hello=10;\n function1(hello);\n function1(130);\n}\n\nint function1(int ip)\n{\n return printf(\"hello - %d\\n\",ip); \n}\n" }, { "answer_id": 74376632, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 0, "selected": false, "text": "GCC" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12791644/" ]
74,368,503
<p>I have a YAML document like this</p> <pre class="lang-yaml prettyprint-override"><code> services: - name: newlogd image: NEWLOGD_TAG cgroupsPath: /eve/services/newlogd oomScoreAdj: -999 - name: edgeview image: EDGEVIEW_TAG cgroupsPath: /eve/services/eve-edgeview oomScoreAdj: -800 - name: debug image: DEBUG_TAG cgroupsPath: /eve/services/debug oomScoreAdj: -999 - name: wwan image: WWAN_TAG cgroupsPath: /eve/services/wwan oomScoreAdj: -999 </code></pre> <p>I need to insert a new object AFTER given element e.g. with name == &quot;edgeview&quot;. so the output looks like this</p> <pre class="lang-yaml prettyprint-override"><code> services: - name: newlogd image: NEWLOGD_TAG cgroupsPath: /eve/services/newlogd oomScoreAdj: -999 - name: edgeview image: EDGEVIEW_TAG cgroupsPath: /eve/services/eve-edgeview oomScoreAdj: -800 - name: new_element_name image: new_element_image - name: debug image: DEBUG_TAG cgroupsPath: /eve/services/debug oomScoreAdj: -999 - name: wwan image: WWAN_TAG cgroupsPath: /eve/services/wwan oomScoreAdj: -999 </code></pre> <p>I couldn't find anything about it in YQ documentation. Is it even possible using YQ?</p> <p><strong>UPDATE:</strong> I'm using YQ <a href="https://github.com/mikefarah/yq" rel="nofollow noreferrer">https://github.com/mikefarah/yq</a> version 4.28.1. I was not aware that there several tools with the same name.</p>
[ { "answer_id": 74368476, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 2, "selected": false, "text": "int function1();\n" }, { "answer_id": 74368634, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": false, "text": "int function1(int);\n\nint main(void) \n{\n int hello=10;\n function1(hello);\n function1(130);\n}\n\nint function1(int ip)\n{\n return printf(\"hello - %d\\n\",ip); \n}\n" }, { "answer_id": 74376632, "author": "ryyker", "author_id": 645128, "author_profile": "https://Stackoverflow.com/users/645128", "pm_score": 0, "selected": false, "text": "GCC" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74368503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639353/" ]
74,368,516
<p>I always wondered how such pictures are made:</p> <p><a href="https://i.stack.imgur.com/3EKef.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3EKef.png" alt="enter image description here" /></a></p> <p>I am working with the R programming language. I would like to plot a parabola with &quot;random noise&quot; added to the parabola. I tried something like this:</p> <pre><code>x = 1:100 y = x^2 z = y + rnorm(1, 100,100) plot(x,z) </code></pre> <p><a href="https://i.stack.imgur.com/Higxe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Higxe.png" alt="enter image description here" /></a></p> <p>But this is still producing a parabola without &quot;noise&quot;.</p> <p>Can someone please show me how I can add &quot;noise&quot; to a parabola (or any function) in R?</p> <p>Thanks!</p>
[ { "answer_id": 74368538, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "x = 1:100\ny = x^2\nz = y + rnorm(length(y), 100,100)\n\nplot(x,z)\n" }, { "answer_id": 74369049, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 1, "selected": false, "text": "y" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,368,548
<p>I have a map of my country, and I try to resize it so as not to take up so much space on the screen, but for some reason, whenever I try to do so, a part of the map is erased as if a square had removed that area, would anyone know how to fix that?</p> <pre><code> </code></pre> <p>&lt;svg xmlns:mapsvg=&quot;http://mapsvg.com&quot;</p> <p>xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot;</p> <p>xmlns:rdf=&quot;http://www.w3.org/1999/02/22-rdf-syntax-ns#&quot;</p> <p>xmlns:svg=&quot;http://www.w3.org/2000/svg&quot;</p> <p>xmlns=&quot;http://www.w3.org/2000/svg&quot;</p> <p>mapsvg:geoViewBox=&quot;-90.125247 14.450692 -87.683841 13.152442&quot;</p> <p>width=&quot;792.89117&quot;</p> <p>height=&quot;431.65646&quot;&gt;</p> <pre><code> </code></pre>
[ { "answer_id": 74368538, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "x = 1:100\ny = x^2\nz = y + rnorm(length(y), 100,100)\n\nplot(x,z)\n" }, { "answer_id": 74369049, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 1, "selected": false, "text": "y" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454524/" ]
74,368,564
<p>I'm a beginner in Swift and have a task to change the bottom sheet message when the process of the app doesn't work in three minutes. So, the message will change from &quot;available&quot; to &quot;not available&quot; if the process does not work.</p> <p>I found code syntax like:</p> <pre class="lang-swift prettyprint-override"><code>Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true) </code></pre> <p>What I think:</p> <pre class="lang-swift prettyprint-override"><code>var waktu = 0 Timer.scheduledTimer(withTimeInterval: 180.0, repeats: false) { if waktu == 180 { timer.invalidate() //run the change message function } } </code></pre>
[ { "answer_id": 74368538, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "x = 1:100\ny = x^2\nz = y + rnorm(length(y), 100,100)\n\nplot(x,z)\n" }, { "answer_id": 74369049, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 1, "selected": false, "text": "y" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20325604/" ]
74,368,650
<p>Trying to install a package (flake8) onto a Docker container (or maybe it's an image). I've pip installed the package locally, and when I try to pip install it again, I get:</p> <pre><code>Requirement already satisfied: flake8 in c:\python39\lib\site-packages (5.0.4) </code></pre> <p>But then when I run this code snippet:</p> <pre><code>docker-compose run --rm app sh -c &quot;flake8&quot; </code></pre> <p>I get the following error:</p> <pre><code>sh: flake8: not found </code></pre> <p>Using VSCode. Any ideas? Thanks</p>
[ { "answer_id": 74369051, "author": "MingJie-MSFT", "author_id": 18359438, "author_profile": "https://Stackoverflow.com/users/18359438", "pm_score": 1, "selected": false, "text": "pip install flake8\n" }, { "answer_id": 74439783, "author": "Conor Romano", "author_id": 15749744, "author_profile": "https://Stackoverflow.com/users/15749744", "pm_score": 1, "selected": true, "text": "flake8>=3.9.2,<3.10\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15749744/" ]
74,368,655
<p>How do I properly catch errors when doing CRUD operations on firebase?</p> <p>I turned off the wifi and I was expecting to catch an error snack but all I see is the loader spinning forever and ever. If I turn the wifi backon, it eventually uploads the files</p> <pre><code>_uploadImages(context) async { setState(() { _isLoading = true; }); try { List filesList = []; var imgCount = await _getImageCountPerJob(); for (var photo in _imageFileList!) { final destination = 'job-images/$jobId/img/img_$imgCount'; imgCount++; final ref = FirebaseStorage.instance.ref(destination); var file = File(photo.path); await ref.putFile(file); var imageUrl = await ref.getDownloadURL(); filesList.add(imageUrl); } _cloudFunctions .updateJobColumn( documentId: jobId, fieldNameColumn: jobImagesListColumnt, fieldNameColumnValue: filesList, ) .then((value) { _displaySnackBarMessage(&quot;Success uploading images&quot;, context); setState(() { _imageFileList = []; }); }); } catch (err) { log('error'); _displaySnackBarMessage(&quot;Error uploading images&quot;, context); setState(() { _isLoading = false; }); } setState(() { _isLoading = false; }); } final job = FirebaseFirestore.instance.collection('job'); Future&lt;void&gt; updateJobApplicationColumn({ required String documentId, required String fieldNameColumn, required fieldNameColumnValue, }) async { try { await jobApplication.doc(documentId).update({ fieldNameColumn: fieldNameColumnValue, }); } catch (e) { throw CouldNotUpdateJobException(); } } </code></pre>
[ { "answer_id": 74369051, "author": "MingJie-MSFT", "author_id": 18359438, "author_profile": "https://Stackoverflow.com/users/18359438", "pm_score": 1, "selected": false, "text": "pip install flake8\n" }, { "answer_id": 74439783, "author": "Conor Romano", "author_id": 15749744, "author_profile": "https://Stackoverflow.com/users/15749744", "pm_score": 1, "selected": true, "text": "flake8>=3.9.2,<3.10\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17281101/" ]
74,368,673
<p>I am trying to build a custom validator in Blazor based on another field on the form. Requirement is to make Phone number mandatory when user checks <strong>Receive Text Messages</strong> checkbox. I googled a lot but was only able to find custom validator verifying empty or some hardcoded string. Is there a way I can validate a field based on another field's value in Blazor?</p> <p>PhoneNumberValidator:</p> <pre class="lang-cs prettyprint-override"><code>public class PhoneNumberValidaton : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return new ValidationResult(&quot;Phone Number is mandatory if you want to receive text messages&quot;, new[] { validationContext.MemberName }); } return null; } } </code></pre> <p>Model:</p> <pre class="lang-cs prettyprint-override"><code>public class UserModel { public int Id { get; set; } [Required] [Display(Name = &quot;First Name&quot;)] public string FirstName { get; set; } [Required] [Display(Name = &quot;Last Name&quot;)] public string LastName { get; set; } [PhoneNumberValidaton] [Display(Name = &quot;Phone Number&quot;)] public string Phone { get; set; } [Required] [Display(Name = &quot;Receive Text Messages&quot;)] public bool CanReceiveText { get; set; } } </code></pre>
[ { "answer_id": 74369440, "author": "Ibrahim Timimi", "author_id": 8316900, "author_profile": "https://Stackoverflow.com/users/8316900", "pm_score": 3, "selected": true, "text": "CanReceiveText" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524500/" ]
74,368,677
<p>I'm trying to make a wave game in Godot and I tried making for loops but I couldn't get them to work outside a function. But when I did put it in the function Godot won't recognize the function and give me this error - error(27,1): Unexpected token: Identifer:spawnEnemies</p> <p>Code:</p> <pre><code>extends Node2D var screenSize = get_viewport().get_visible_rect().size func _ready(): pass # Replace with function body. var scene = preload(&quot;res://scenes/enemyInstance.tscn&quot;) func _physics_process(delta): pass func spawnEnemy(): var instance = scene.instance() var rng = RandomNumberGenerator.new() var rndX = rng.randi_range(0, screenSize.x) var rndY = rng.randi_range(0, screenSize.y) instance.position.x = rndX instance.position.y = rndY add_child(instance) func spawnEnemies(number): for i in number: spawnEnemy() spawnEnemies(7) </code></pre> <p>I've tried removing the for loop or changing how the variables are but nothing worked.</p>
[ { "answer_id": 74369440, "author": "Ibrahim Timimi", "author_id": 8316900, "author_profile": "https://Stackoverflow.com/users/8316900", "pm_score": 3, "selected": true, "text": "CanReceiveText" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19327109/" ]
74,368,690
<p>I've been working on some custom html email templates. I'm having some trouble with my emails appearing differently when they are sent by different email services. I'm using AWS SES to send these emails to clients.</p> <p>I've been using <a href="https://app.postdrop.io" rel="nofollow noreferrer">Postdrop</a> to send test emails while I've been creating the template. Now that the AWS SES environment has been set up for my application, I can now send emails using the html template. The problem I'm getting is that when I send emails using AWS, the emails look different than they do when sent by Postdrop, even when viewing the email from the same email client.</p> <p>I used a code checker to see how what the email client was receiving was different for each email sender, and they seem almost exactly the same, except for some Unicode(I think it's Unicode?) differences. The only differences I noted was that SES adds <code>=E2=80=8B</code> between certain sections of code, while Postdrop adds an empty line in place of that, and a short section of code where Postdrop included <code>=2E</code> at the start of some of the classes, where SES did not(This is the &quot;External Class&quot; section shown in the picture.) It seems like these are related to tab or end-line characters, but I'm not sure. There is other Unicode code used as well, but both emails use the same code in those sections.</p> <p><strong>Here is an example of the input code:</strong></p> <p><a href="https://i.stack.imgur.com/gp78y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gp78y.png" alt="enter image description here" /></a></p> <p><strong>And here is what I'm getting from the different email senders:</strong></p> <p><a href="https://i.stack.imgur.com/yMLFI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yMLFI.jpg" alt="enter image description here" /></a></p> <p>These slight differences are causing the email sent by SES to appear incorrectly. Specifically, some of the media queries aren't working(while some still do), and there is additional spacing at the top.</p> <p>In the header of the emails, both say they are being encoded by UTF-8, although the way it's phrased is slightly different.</p> <p>Postdrop appears like this:</p> <pre><code>Content-Type: text/html; charset=&quot;utf-8&quot; Content-Transfer-Encoding: quoted-printable </code></pre> <p>and SES appears like this:</p> <pre><code>Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable </code></pre> <p>Not sure if that would affect anything. What is causing this issue, and how do I fix it?</p> <p><strong>Edit</strong></p> <p>Here is the code for the Lambda function that tells SES to send the email, but some of the identifying stuff(specific email addresses, amazon region, and file structure) have been removed just for safety:</p> <pre><code>import boto3 import logging import os import sys from emailbody import body from emailbodytext import bodytext from botocore.exceptions import ClientError def send_email(recipients): SENDER = &quot;&quot; # must be verified in AWS SES Email RECIPIENTS = recipients # must be verified in AWS SES Email AWS_REGION = &quot;&quot; # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) # Try to send the email. try: #Provide the contents of the email. response = client.send_templated_email( Destination={ 'ToAddresses': RECIPIENTS, }, Template='TemplateName', TemplateData = &quot;{}&quot;, Source=SENDER ) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print(&quot;Email sent! Message ID:&quot;), print(response['MessageId']) def delete_email_template(templateToDelete): AWS_REGION = &quot;&quot; # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) # Try to get the email template. try: #Provide the contents of the email. response = client.delete_template( TemplateName=templateToDelete ) return response # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print(response['MessageId']) def create_email_template(): AWS_REGION = &quot;&quot; #The name for the template TEMPLATENAME = &quot;Test&quot; # The subject line for the email. SUBJECT = &quot;Test Email&quot; #The email body EMAILBODY = body #The email text BODYTEXT = bodytext # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) #Provide the contents of the email. response = client.create_template( Template={ 'TemplateName': TEMPLATENAME, 'SubjectPart': SUBJECT, 'TextPart': BODYTEXT, 'HtmlPart': EMAILBODY } ) def lambda_handler(event, context): emails = ['', ''] create_email_template() send_email(emails) delete_email_template(&quot;Test&quot;) </code></pre>
[ { "answer_id": 74416150, "author": "Newbie", "author_id": 5424426, "author_profile": "https://Stackoverflow.com/users/5424426", "pm_score": 2, "selected": false, "text": "quoted-printable" }, { "answer_id": 74460257, "author": "Neo", "author_id": 405238, "author_profile": "https://Stackoverflow.com/users/405238", "pm_score": 0, "selected": false, "text": "The encoding: UTF-8 but may not preserve all special characters when a message was encoded with a different encoding format. Base64 preserves all special characters. The default value is UTF-8.\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3304179/" ]
74,368,697
<p>Say I want to run the command:</p> <pre><code>git reset --hard origin/abc </code></pre> <p>where <code>abc</code> is my current branch. How can I programmatically insert the current branch into the command instead of having to run <code>git branch --show</code>, copying the result, and pasting into the <code>reset</code> command?</p>
[ { "answer_id": 74368782, "author": "borrimorri", "author_id": 5274855, "author_profile": "https://Stackoverflow.com/users/5274855", "pm_score": 0, "selected": false, "text": "git reset --hard origin/$(git branch --show-current)" }, { "answer_id": 74371086, "author": "LeGEC", "author_id": 86072, "author_profile": "https://Stackoverflow.com/users/86072", "pm_score": 3, "selected": true, "text": "<branch>@{u}" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274855/" ]
74,368,706
<p><strong>Why does this give me a object null reference error:</strong></p> <pre><code>[HttpPost] public ActionResult WriteNote(NotesModel note) //notes == null { SendToDB(note.Author, note.Title, note.Note); return View(); //BREAKPOINT } </code></pre> <p><strong>And this does not:</strong></p> <pre><code>[HttpPost] public ActionResult WriteNote(NotesModel model) //model is not null { SendToDB(model.Author, model.Title, model.Note); return View(); //BREAKPOINT } </code></pre> <p>I've spend about 2 hours trying to figure out what is wrong and i just found this out by accident but have no idea why this works. No matter what name i choose for the object anything will do but note...</p> <p>Can anyone explain?</p> <p><strong>-----EDIT:</strong></p> <p><strong>TO RECREATE THIS ISSUE DO THE FOLLOWING</strong></p> <p>Create a new ASP.NET (Framework 4.8.1) MVC project. Create a Model called &quot;NotesModel.cs&quot; with the following content:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebsiteProject.Models { public class NotesModel { [Display(Name = &quot;Author&quot;)] public string Author { get; set; } [Display(Name = &quot;Title&quot;)] public string Title { get; set; } [Display(Name = &quot;Note&quot;)] public string Note { get; set; } } } </code></pre> <p>Next create a controller called &quot;NotesController.cs&quot; with the following content:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebsiteProject.Models; using System.Windows; namespace WebsiteProject.Controllers { public class NotesController : Controller { public ActionResult WriteNote() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult WriteNote(NotesModel note) { if (note == null) MessageBox.Show(&quot;IF YOU ARE SEEING THIS THEN note == NULL&quot;); return View(); } } } </code></pre> <p>Next go to the NotesController.cs file and right click on <code>public ActionResult WriteNote()</code> and select &quot;Add View&quot;, choose MVC 5 View.</p> <p>For Template choose: Create</p> <p>For Model Class Choose the NotesModel</p> <p>Go to the newly created view and launch the webapp, fill in the three textboxes and submit.</p> <p>Now you should see a textbox telling you that note == NULL, this is obviously wrong, it should have received data from the form.</p> <p>Now if you go to the NotesController.cs file and replace</p> <p><code>public ActionResult WriteNote(NotesModel note)</code></p> <p>With this</p> <p><code>public ActionResult WriteNote(NotesModel somethingelse)</code></p> <p>(Also change <code>note</code> to <code>somethingelse</code> in the <code>if</code> statement)</p> <p>It will no longer be null and actually receive the data from the form. you can check this by inserting a breakpoint at the <code>if</code> statement. Also the messagebox should not be popping up now.</p> <p>I hope this is detailed enough to recreate the issue.</p>
[ { "answer_id": 74370353, "author": "Jonathan Wood", "author_id": 522663, "author_profile": "https://Stackoverflow.com/users/522663", "pm_score": 0, "selected": false, "text": "model" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20268332/" ]
74,368,724
<p>I am trying to make a linear regression model using data that I have sorted into new categories. (Specifically I have taken age from the NHANES database and sorted different age ranges into generations)</p> <p>When I attempt to use R's <code>lm()</code> function on my new data I receive an output that accounts for all but one set of generational data which I will show and explain below.</p> <pre><code>library(tidyverse) library(janitor) library(NHANES) data(NHANES) View(NHANES) help(NHANES) Database &lt;- NHANES %&gt;% select(SleepHrsNight, BMI, AgeDecade, HHIncome, Age) %&gt;% # select variables of interest drop_na() # remove any rows with NA's to leave only complete observations Database%&gt;% ggplot(aes(x = SleepHrsNight, y=BMI))+ geom_point()+ labs(x = &quot;Quanity of Sleep (hours)&quot;, y = &quot;BMI Level&quot;, title = &quot;Quantity of Sleep vs. BMI&quot;) cor(Database$BMI, Database$SleepHrsNight) view(Database) ################### THIS IS THE CODE SORTS MY AGE DATA INTO GENERATIONS Database$AgeGeneration &lt;- ifelse(Database$Age &gt;= 10 &amp; Database$Age &lt;= 25,&quot;Gen Z&quot;, ifelse(Database$Age &gt;= 26 &amp; Database$Age &lt;=41, &quot;Millenials&quot;, ifelse(Database$Age &gt;= 42 &amp; Database$Age &lt;= 57, &quot;Gen X&quot;, ifelse( Database$Age &gt; 57, &quot;Baby Boomers&quot;,0)))) BMI_SleepHrsNight_AgeGeneration_model = Database %&gt;% lm(BMI ~ SleepHrsNight + AgeGeneration, data = .) summary(BMI_SleepHrsNight_AgeGeneration_model) Regression_model &lt;- Database %&gt;% lm(BMI~SleepHrsNight+AgeGeneration,.) summary(Regression_model) </code></pre> <p><strong>THIS IS THE OUTPUT</strong></p> <pre><code>Call: lm(formula = BMI ~ SleepHrsNight + AgeGeneration, data = .) Residuals: Min 1Q Median 3Q Max -14.389 -4.616 -1.251 3.479 53.592 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) (Intercept) 30.35296 0.46202 65.697 &lt;2e-16 *** SleepHrsNight -0.13893 0.06169 -2.252 0.0244 * AgeGenerationGen X -0.29029 0.22710 -1.278 0.2012 AgeGenerationGen Z -2.78956 0.25964 -10.744 &lt;2e-16 *** AgeGenerationMillenials -0.38842 0.22671 -1.713 0.0867 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 6.706 on 6726 degrees of freedom Multiple R-squared: 0.02216, Adjusted R-squared: 0.02158 F-statistic: 38.11 on 4 and 6726 DF, p-value: &lt; 2.2e-16 </code></pre> <p>The code above is missing data from the &quot;Baby Boomers&quot; and I have no idea why. When I view the database the Baby Boomer data shows up but for some reason it seems to not exist when I summarize the <code>lm() </code>function. I also used this method on a set of data that was made in an identical way and I received the same issue.</p>
[ { "answer_id": 74368759, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "Baby Boomers" }, { "answer_id": 74369030, "author": "Zhiqiang Wang", "author_id": 11741943, "author_profile": "https://Stackoverflow.com/users/11741943", "pm_score": 2, "selected": false, "text": "Baby Boomers" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454659/" ]
74,368,741
<p>I want to make the operations on <a href="https://textsaver.flap.tv/lists/55f9" rel="nofollow noreferrer">structured text</a> available here using bash script language. However, my knowledge makes the task very challenging.</p> <p>Input sample:</p> <pre><code>&quot;4-QUEIJOS&quot;: Mucarela Provolone Catupiry Ricota Oregano &quot;A-MODA&quot;: Mucarela Presunto Calabresa Bacon Tomate Milho Oregano &quot;ALHO-E-OLEO&quot;: Mucarela Alho oleo Oregano &quot;PEITO-DE-PERU-ESPECIAL&quot;: Mucarela Peito-de-Peru Catupiry Oregano </code></pre> <p>Output sample</p> <pre><code>&quot;4-QUEIJOS&quot;: [&quot;mucarela&quot;, &quot;provolone&quot;, &quot;catupiry&quot;, &quot;ricota&quot;, &quot;oregano&quot;], &quot;A-MODA&quot;: [&quot;mucarela&quot;, &quot;presunto&quot;, &quot;calabresa&quot;, &quot;bacon&quot;, &quot;tomate&quot;, &quot;milho&quot;, &quot;oregano&quot;], &quot;ALHO-E-OLEO&quot;: [&quot;mucarela&quot;, &quot;alho&quot;, &quot;oleo&quot;, &quot;oregano&quot;], &quot;PEITO-DE-PERU-ESPECIAL&quot;: [&quot;Mucarela&quot;, &quot;peito-de-peru&quot;, &quot;catupiry&quot;, &quot;oregano&quot;] </code></pre> <p>As you can see above, we need to:</p> <ol> <li>Put lower case to words after the character &quot;:&quot;;</li> <li>Add commas between these words above;</li> <li>put them between brackets [...]</li> </ol> <p>The cherry-at-the-top is the commas at the end of each line except the last.</p>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16251726/" ]
74,368,747
<p>I have a list of strings like this</p> <pre><code>string_list&lt;-c(&quot;&gt;=23&quot;, &quot;&gt;=50&quot;, &quot;large than 23 years&quot;, &quot;Yes&quot;, &quot;No2&quot;, &quot;Yes4&quot;, &quot;Negative&quot;, &quot;Positive9&quot;, &quot;Negative10&quot;) </code></pre> <p>Is there a way to remove the numbers after Yes, No, Positive, and Negative while not affecting the rest of the string? I used string_remove but I can't identify this specific pattern. Here is the list I wanted to have:</p> <pre><code>string_list&lt;-c(&quot;&gt;=23&quot;, &quot;&gt;=50&quot;, &quot;large than 23 years&quot;, &quot;Yes&quot;, &quot;No&quot;, &quot;Yes&quot;, &quot;Negative&quot;, &quot;Positive&quot;, &quot;Negative&quot;) </code></pre> <p>Thanks!</p>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17608782/" ]
74,368,760
<p>I faced 2 scenarios where terraform did not point out an error during the execution of terraform plan and I am wondering if is this a bug or if this is how bucket/iam policies work ( i.e determined at the time of terraform apply )</p> <p>scenario 1 : when there was an error in condition for s3 bucket policy <code>Bool</code> was written as <code>bool</code></p> <pre><code>data &quot;aws_iam_policy_document&quot; &quot;alb_log&quot; { statement { effect = &quot;Allow&quot; actions = [&quot;s3:PutObject&quot;] resources = [&quot;${aws_s3_bucket.alb_log.arn}/*&quot;] principals { type = &quot;AWS&quot; identifiers = [data.aws_elb_service_account.main.arn] } } statement { sid = &quot;AllowSSLRequestsOnly&quot; effect = &quot;Deny&quot; actions = [&quot;s3:*&quot;] resources = [ aws_s3_bucket.alb_log.arn, &quot;${aws_s3_bucket.alb_log.arn}/*&quot; ] condition { test = &quot;bool&quot; values = [ &quot;false&quot; ] variable = &quot;aws:SecureTransport&quot; } principals { type = &quot;*&quot; identifiers = [&quot;*&quot;] } } } resource &quot;aws_s3_bucket_policy&quot; &quot;alb_log&quot; { bucket = aws_s3_bucket.alb_log.id policy = data.aws_iam_policy_document.alb_log.json } </code></pre> <p>scenario 2 : I added principals to iam policy, terraform plan should point this but the fact principals cannot be added in iam policy is told during terraform apply</p> <pre><code>data &quot;aws_iam_policy_document&quot; &quot;artifact2&quot; { statement { sid = &quot;AllowSSLRequestsOnly&quot; effect = &quot;Deny&quot; actions = [&quot;s3:*&quot;] resources = [ &quot;arn:aws:s3:::${aws_s3_bucket.artifact2.id}&quot;, &quot;arn:aws:s3:::${aws_s3_bucket.artifact2.id}/*&quot; ] condition { test = &quot;Bool&quot; values = [ &quot;false&quot; ] variable = &quot;aws:SecureTransport&quot; } principals { type = &quot;*&quot; identifiers = [&quot;*&quot;] } } } resource &quot;aws_iam_policy&quot; &quot;firehose&quot; { policy = data.aws_iam_policy_document.artifact2.json } </code></pre>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13126651/" ]
74,368,771
<p>When I start a HelloWorld App on react-native using &quot;expo start&quot; command getting the error below. The emulator is up and running . Expo go is already installed. But for some reason app is not installing. Any pointers to resolve this would be very helpful.</p> <pre><code>Couldn't start project on Android: Error running adb: Error running app. args: [-p, host.exp.exponent, -c, android.intent.category.LAUNCHER, 1] arg: &quot;-p&quot; arg: &quot;host.exp.exponent&quot; arg: &quot;-c&quot; arg: &quot;android.intent.category.LAUNCHER&quot; arg: &quot;1&quot; data=&quot;host.exp.exponent&quot; data=&quot;android.intent.category.LAUNCHER&quot; ** SYS_KEYS has no physical keys but with factor 2.0%. </code></pre> <p><a href="https://i.stack.imgur.com/cKco6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cKco6.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380410/" ]
74,368,797
<p>I'm making a categorized column for <code>year-month</code> for my view and have this as a formula:</p> <pre><code>@Text(@Year (CertEnd:CQIEnd:InspEnd)) + &quot;-&quot; + @Text(@Month(CertEnd:CQIEnd:InspEnd)) </code></pre> <p>If the month any anything before October, the month comes out as single digit.</p> <p>How to make single digit months double digit, because I want to add sorting as well?</p>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8000620/" ]
74,368,799
<p>I tried this but not working :</p> <pre><code> init() { let navBarAppearance = UINavigationBar.appearance() navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] } </code></pre>
[ { "answer_id": 74368835, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 4, "selected": true, "text": "sed" }, { "answer_id": 74370733, "author": "TheAnalogyGuy", "author_id": 6317990, "author_profile": "https://Stackoverflow.com/users/6317990", "pm_score": 3, "selected": false, "text": "--debug" }, { "answer_id": 74372116, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 2, "selected": false, "text": "sed -E 's/\\S+/\\L\"&\",/2g;s/^: (.*),/: [\\1],/;$s/,$//' file\n" }, { "answer_id": 74372727, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": false, "text": "awk" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8771798/" ]
74,368,810
<p>I'm passing a column-name to one function. I want to reference in the function AND in another it calls.</p> <p>This works as I expected</p> <pre><code>library(dplyr) updown &lt;- function(df, columnName){ COL &lt;- enquo(columnName) df %&gt;% mutate(UP = toupper(!!COL), DOWN = tolower(!!COL)) } updown(band_members, columnName = band) # A tibble: 3 x 4 name band UP DOWN &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; 1 Mick Stones STONES stones 2 John Beatles BEATLES beatles 3 Paul Beatles BEATLES beatles </code></pre> <p>I put the second <code>mutate</code> into a second function call</p> <pre><code>updown2 &lt;- function(df, columnName){ COL &lt;- enquo(columnName) df %&gt;% mutate(UP = toupper(!!COL)) %&gt;% updown3(columnName = columnName) } updown3 &lt;- function(df, columnName){ COL &lt;- enquo(columnName) df %&gt;% mutate(DOWN = tolower(!!COL)) } updown2(band_members, columnName = band) </code></pre> <p>But got the error</p> <pre><code> Error in `h()`: ! Problem with `mutate()` input `DOWN`. ✖ object 'band' not found ℹ Input `DOWN` is `tolower(columnName)`. Run `rlang::last_error()` to see where the error occurred. </code></pre> <p>How should I access (via <code>enquo</code>) the NSE columnName in <code>updown2</code>, then pass it from <code>updown2</code> to <code>updown3</code>?</p>
[ { "answer_id": 74368921, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": false, "text": "{{ }}" }, { "answer_id": 74368959, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "COL" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004016/" ]
74,368,811
<p>Im on python and I tried to get price data($25.99)from below Amazon webpage.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/B09HWZQQZJ" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/Guffercty-kred-Sublimation-Mechanical-Keyboard/dp/B09HWZQQZJ/ref=sr_1_14?crid=3UHD6OMRY6RYG&amp;keywords=keycaps&amp;qid=1667444474&amp;qu=eyJxc2MiOiI4Ljc5IiwicXNhIjoiOC41OCIsInFzcCI6IjcuOTMifQ%3D%3D&amp;sprefix=keycap%2Caps%2C275&amp;sr=8-14&amp;th=1</a></p> <p>I used both beautiful soup and selenium, but my selenium code doesn't work.</p> <pre><code>#with beautiful soup import requests from bs4 import BeautifulSoup PRODUCT=&quot;https://www.amazon.com/Guffercty-kred-Sublimation-Mechanical-Keyboard/dp/B09HWZQQZJ/ref=sr_1_14?crid=3UHD6OMRY6RYG&amp;keywords=keycaps&amp;qid=1667444474&amp;qu=eyJxc2MiOiI4Ljc5IiwicXNhIjoiOC41OCIsInFzcCI6IjcuOTMifQ%3D%3D&amp;sprefix=keycap%2Caps%2C275&amp;sr=8-14&amp;th=1&quot; response = requests.get(PRODUCT, headers={&quot;Accept-Language&quot;:&quot;ko,en-US;q=0.9,en;q=0.8,sv;q=0.7,ja;q=0.6&quot;, &quot;User-Agent&quot;:&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36&quot;}) soup = BeautifulSoup(response.text, &quot;html.parser&quot;) price = float(soup.find(name=&quot;span&quot;, class_=&quot;a-offscreen&quot;).getText()) print(price) </code></pre> <p>above code perfectly works for me and returns the price. code prints $25.99 on the prompter.</p> <p>However, below code with selenium doesn't work.</p> <pre><code>#with selenium from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By service = Service(&quot;/my/chrome/driver/path/chromedriver&quot;) driver = webdriver.Chrome(service=service) driver.get(url=&quot;https://www.amazon.com/Guffercty-kred-Sublimation-Mechanical-Keyboard/dp/B09HWZQQZJ/ref=sr_1_14?crid=3UHD6OMRY6RYG&amp;keywords=keycaps&amp;qid=1667444474&amp;qu=eyJxc2MiOiI4Ljc5IiwicXNhIjoiOC41OCIsInFzcCI6IjcuOTMifQ%3D%3D&amp;sprefix=keycap%2Caps%2C275&amp;sr=8-14&amp;th=1&quot;) price = driver.find_element(By.CSS_SELECTOR, 'span .a-offscreen') print(price.text) </code></pre> <p>unlike the bs4 code, selenium code doesn't show me anything on the prompter.</p> <p>I thought &quot;find_element(By.CSS_SELECTOR, 'span .a-offscreen')&quot; in selenium works the same as &quot;find(name='span', class_'a-offscreen')&quot; in bs4.</p> <p>I also tried By.XPATH as well, but it doesn't work either. Am I missing something?</p>
[ { "answer_id": 74368921, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": false, "text": "{{ }}" }, { "answer_id": 74368959, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "COL" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19875981/" ]
74,368,821
<p>I have a client service, with a method:</p> <pre><code>get (params) { return this.http.get(url, { params: params }); } </code></pre> <p>and then a service that performs this:</p> <pre><code>fetch () { return this.client.get(this.params); } </code></pre> <p>and then a component that makes use of that service:</p> <pre><code># in template &lt;a (click)=&quot;clickHandler()&quot;&gt;click me&lt;/a&gt; &lt;some-other-component&gt;&lt;/some-other-component&gt; # method in component class clickHandler () { this.service.fetch(); } </code></pre> <p>My question is, if I want <code>SomeOtherComponent</code> to be able to do something when this api call is completed, what is the best way to handle that so that it can subscribe to the get call?</p> <p>I know I could do something like:</p> <pre><code># in template &lt;some-other-component [observable]=&quot;observable&quot;&gt;&lt;/some-other-component&gt; # method in component class clickHandler () { this.observable = this.service.fetch(); } </code></pre> <p>And say within that <code>SomeOtherComponent</code> are other child components that each want to make use of the results of that web call... Would passing the observable directly like this be the best way to go? So each of them call <code>.subscribe(first()).pipe(...)</code> and do what they need to with it?</p>
[ { "answer_id": 74368921, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": false, "text": "{{ }}" }, { "answer_id": 74368959, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "COL" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/594763/" ]
74,368,843
<p>I am trying to update the Migration, however, it says the package is not referenced even though I set the default project to the correct one. See the image below. In fact, I can start the program and access the database correctly. Not sure what it causing it.</p> <p><a href="https://i.stack.imgur.com/IHSLM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IHSLM.png" alt="Referenced Message" /></a></p> <p>I am referencing it in <code>program.cs</code></p> <pre><code>builder.Services.AddSqlServerContext&lt;LairageContext&gt;(configuration.GetConnectionString(&quot;Lairage&quot;)); ... public static IServiceCollection AddSqlServerContext&lt;TContext&gt;(this IServiceCollection services, string connectionstring, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) where TContext : DbContext =&gt; services .AddDbContext&lt;TContext&gt;(options =&gt; options.UseSqlServer( connectionstring, actions =&gt; actions.MigrationsAssembly(&quot;Marel.Lairage.Innova.Data&quot;) .EnableRetryOnFailure() ), serviceLifetime); </code></pre>
[ { "answer_id": 74368921, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": false, "text": "{{ }}" }, { "answer_id": 74368959, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "COL" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15119845/" ]
74,368,856
<p>I need some help with mariadb queries. I'm trying to set an alias column with the result of another select.</p> <p>I have 3 tables:</p> <ul> <li>Units_dimension.</li> <li>Units.</li> <li>Readings.</li> </ul> <p>Units_dimension table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>dimension</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>temperature</td> </tr> <tr> <td>2</td> <td>humidity</td> </tr> <tr> <td>3</td> <td>pressure</td> </tr> </tbody> </table> </div> <p>Units table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>dimension_id</th> <th>unit</th> <th>representation</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>Celsius</td> <td>°C</td> </tr> <tr> <td>2</td> <td>1</td> <td>Farenheit</td> <td>°F</td> </tr> <tr> <td>3</td> <td>1</td> <td>Kelvin</td> <td>K</td> </tr> <tr> <td>4</td> <td>2</td> <td>Percentage</td> <td>%</td> </tr> <tr> <td>5</td> <td>3</td> <td>HectoPascal</td> <td>hPa</td> </tr> </tbody> </table> </div> <p>Readings table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>station_id</th> <th>datetime</th> <th>unit_id</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>ESP0001</td> <td>2022-10-31 01:00:00.000</td> <td>1</td> <td>23.5</td> </tr> <tr> <td>2</td> <td>ESP0001</td> <td>2022-10-31 01:00:00.000</td> <td>4</td> <td>79</td> </tr> <tr> <td>3</td> <td>ESP0001</td> <td>2022-10-31 01:00:00.000</td> <td>5</td> <td>1019.6</td> </tr> <tr> <td>4</td> <td>ESP0001</td> <td>2022-10-31 02:00:00.000</td> <td>1</td> <td>23.3</td> </tr> <tr> <td>5</td> <td>ESP0001</td> <td>2022-10-31 02:00:00.000</td> <td>4</td> <td>79</td> </tr> <tr> <td>5</td> <td>ESP0001</td> <td>2022-10-31 02:00:00.000</td> <td>5</td> <td>1019.6</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> </tbody> </table> </div> <p>I want to get the value column in a select with alias from the unit dimension.</p> <p>Example SELECT r.datetime, r.value AS (?1) FROM readings r WHERE station_id = 'ESP0001' and unit_id = ?2</p> <p>?1 is temperature or humidity or pressure, etc.</p> <p>?2 is the unit_id.</p> <p>I tried something like that:</p> <pre class="lang-sql prettyprint-override"><code>SELECT r.datetime, r.value AS (SELECT ud.dimension FROM units u LEFT JOIN unit_dimension ud ON (ud.id = u.dimension_id) WHERE u.id = 1) FROM readings r WHERE r.unit_id = 1; </code></pre> <p>But I have an SQL Error [1064] [42000]: (conn=67) You have an error in your SQL syntax;</p> <p>Thanks.</p>
[ { "answer_id": 74373356, "author": "deblocker", "author_id": 4845566, "author_profile": "https://Stackoverflow.com/users/4845566", "pm_score": 2, "selected": true, "text": "SELECT r.`datetime`, r.`value`, ud.`dimension`\n FROM readings r, units u, unit_dimension ud\n WHERE u.id = r.unit_id \n AND ud.id = u.dimension_id\n AND r.station_id = 'ESP0001'\n AND r.unit_id = 1 -- Celsius\n" }, { "answer_id": 74374420, "author": "am4rtinez", "author_id": 13344115, "author_profile": "https://Stackoverflow.com/users/13344115", "pm_score": 0, "selected": false, "text": "SELECT ud.dimension \nFROM units u, unit_dimension ud \nWHERE ud.id = u.dimension_id \nAND u.id = ${req.params.unit_id};\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13344115/" ]
74,368,859
<pre><code>this.wiredUserData = [ {&quot;result&quot;: {&quot;fields&quot;: {&quot;Id&quot;:{&quot;value&quot;:&quot;005xx000001X85BAAS&quot;}, &quot;Username&quot;:{&quot;value&quot;:&quot;emily@gmail.com&quot;}}}}, {&quot;result&quot;: {&quot;fields&quot;: {&quot;Id&quot;:{&quot;value&quot;:&quot;005xx000001X7sHAAS&quot;}, &quot;Username&quot;:{&quot;value&quot;:&quot;kristina@gmail.com&quot;}}}} ] const uid = &quot;005xx000001X85B&quot; usernameData(uid) { if (this.wiredUserData) { this.wiredUserData.forEach(function (item) { let wiredUserId = item.result.fields.Id.value.slice(0, 15); console.log(wiredUserId, &quot;wired&quot;); console.log(uid, &quot;uid&quot;); let wiredUsername = item.result.fields.Username.value; if (uid === wiredUserId) { return wiredUsername; } }); } return ''; } </code></pre> <p>I am attempting to return the username value (e.g. kristina@gmail.com) when the function is called if the uid and Id match.</p> <p>Hi, I am looping over <code>wiredUserData</code> and getting an error Expected to return a value at the end of function. What am I missing here? Should I use another kind of for loop ?</p>
[ { "answer_id": 74373356, "author": "deblocker", "author_id": 4845566, "author_profile": "https://Stackoverflow.com/users/4845566", "pm_score": 2, "selected": true, "text": "SELECT r.`datetime`, r.`value`, ud.`dimension`\n FROM readings r, units u, unit_dimension ud\n WHERE u.id = r.unit_id \n AND ud.id = u.dimension_id\n AND r.station_id = 'ESP0001'\n AND r.unit_id = 1 -- Celsius\n" }, { "answer_id": 74374420, "author": "am4rtinez", "author_id": 13344115, "author_profile": "https://Stackoverflow.com/users/13344115", "pm_score": 0, "selected": false, "text": "SELECT ud.dimension \nFROM units u, unit_dimension ud \nWHERE ud.id = u.dimension_id \nAND u.id = ${req.params.unit_id};\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454788/" ]
74,368,863
<p>I am trying to get the youtube channel name and the number of subscribers using the below code:</p> <pre><code>var youtubeAuthResponse = [],youtubeChannelResponse = []; function authenticate() { showNewLoader('show'); return gapi.auth2.getAuthInstance() .signIn({scope: &quot;https://www.googleapis.com/auth/youtube.readonly&quot;}) .then(function(response) { console.log( response); youtubeAuthResponse['token_details'] = response.tc; youtubeAuthResponse['google_email'] = ''; youtubeAuthResponse['google_id'] = ''; showNewLoader('hide'); }, function(err) { console.error(&quot;Error signing in&quot;, err); showNewLoader('hide');}); } function loadClient() { showNewLoader('show'); gapi.client.setApiKey(&quot;XXXX&quot;); return gapi.client.load(&quot;https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest&quot;) .then(function() { execute();}, function(err) { console.error(&quot;Error loading GAPI client for API&quot;, err);showNewLoader('hide');}); } /*Make sure the client is loaded and sign-in is complete before calling this method.*/ function execute() { return gapi.client.youtube.channels.list({ &quot;part&quot;: [ &quot;snippet&quot;, &quot;statistics&quot; ], &quot;mine&quot;: true }) .then(function(response) { /*Handle the results here (response.result has the parsed body).*/ youtubeChannelResponse = response.result; storeYoutubeData(); }, function(err) { console.error(&quot;Execute error&quot;, err); showNewLoader('hide') }).then(function(){ }); } gapi.load(&quot;client:auth2&quot;, function() { gapi.auth2.init({client_id: &quot;XXXXXX&quot;, 'access_type':'offline'}); }); </code></pre> <p>After signing in, I get the following error from google:</p> <pre><code>&quot;The request uses the &lt;code&gt;mine&lt;/code&gt; parameter but is not properly authorized.&quot; </code></pre> <p>Also the consent screen is never displayed.</p> <p><a href="https://i.stack.imgur.com/8HjJ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HjJ7.png" alt="enter image description here" /></a></p> <p>Any help on this is greatly appreciated.</p> <p>@DaImTo</p>
[ { "answer_id": 74436093, "author": "Zeynep Evecen", "author_id": 13856050, "author_profile": "https://Stackoverflow.com/users/13856050", "pm_score": 0, "selected": false, "text": "const response = await \nfetch(\"https://www.googleapis.com/youtube/v3/channels? \npart=snippet,statistic&mine=true&key=[API_KEY]\",{\n \" Authorization: Bearer `${accessToken}`\"\n}) //here just add bearer\n}catch(error){\n//err\n}```\n" }, { "answer_id": 74481884, "author": "aparent", "author_id": 6427745, "author_profile": "https://Stackoverflow.com/users/6427745", "pm_score": 0, "selected": false, "text": "'prompt':'select_account'" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1852924/" ]
74,368,888
<p>here is my UPDATE page code.</p> <pre><code>using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Data.SqlClient; namespace WebApplication2.Pages.Users { public class EditModel : PageModel { public UserInfo userInfo = new UserInfo(); public String errorMessage = &quot;&quot;; public String successMessage = &quot;&quot;; public void OnGet() { String id=Request.Query[&quot;id&quot;]; try { String connectionString = &quot;Data Source=DESKTOP-5406L1M;Initial Catalog=crud;Integrated Security=True&quot;; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); String sql = &quot;SELECT * FROM users WHERE id=@id&quot;; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue(&quot;@id&quot;, id); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { userInfo.id = &quot;&quot;+reader.GetInt32(0); userInfo.name = reader.GetString(1); userInfo.email = reader.GetString(2); userInfo.phone = reader.GetString(3); userInfo.address = reader.GetString(4); } } } } } catch(Exception ex) { errorMessage = ex.Message; } } public void OnPost() { userInfo.id = Request.Form[&quot;id&quot;]; userInfo.name = Request.Form[&quot;name&quot;]; userInfo.email = Request.Form[&quot;email&quot;]; userInfo.phone = Request.Form[&quot;phone&quot;]; userInfo.address = Request.Form[&quot;address&quot;]; if (userInfo.id.Length==0 ||userInfo.name.Length == 0 || userInfo.email.Length == 0 || userInfo.phone.Length == 0 || userInfo.address.Length == 0) { errorMessage = &quot;All the field are required&quot;; return; } try { String connectionString = &quot;Data Source=DESKTOP-5406L1M;Initial Catalog=crud;Integrated Security=True&quot;; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); String sql =&quot;UPDATE users &quot; + &quot;SET name=@name, email=@email, phone=@phone, address=@address &quot; + &quot;WHERE id=@id&quot;; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue(&quot;@name&quot;, userInfo.name); command.Parameters.AddWithValue(&quot;@email&quot;, userInfo.email); command.Parameters.AddWithValue(&quot;@phone&quot;, userInfo.phone); command.Parameters.AddWithValue(&quot;@address&quot;, userInfo.address); command.Parameters.AddWithValue(&quot;@id&quot;, userInfo.id); command.ExecuteNonQuery(); } } } catch(Exception ex) { errorMessage=ex.Message; return; } Response.Redirect(&quot;/Users/Index&quot;); } } } </code></pre> <p>`</p> <h2>Here is my Index page (userInfo class)</h2> <blockquote> <p>Index page (userInfo class)</p> </blockquote> <pre><code>using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Data.SqlClient; namespace WebApplication2.Pages.Users { public class IndexModel : PageModel { public List&lt;UserInfo&gt; ListUsers=new List&lt;UserInfo&gt;(); public void OnGet() { try { String connectionString = &quot;Data Source=DESKTOP-5406L1M;Initial Catalog=crud;Integrated Security=True&quot;; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); String sql = &quot;SELECT * FROM users&quot;; using (SqlCommand command =new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { UserInfo userInfo = new UserInfo(); userInfo.id = &quot;&quot; + reader.GetInt32(0); userInfo.name = reader.GetString(1); userInfo.email = reader.GetString(2); userInfo.phone = reader.GetString(3); userInfo.address = reader.GetString(4); userInfo.created_at = reader.GetDateTime(5).ToString(); ListUsers.Add(userInfo); } } } } } catch(Exception ex) { Console.WriteLine(&quot;Exception:&quot; + ex.ToString()); } } } public class UserInfo { public string id; public string name; public string email; public string phone; public string address; public string created_at; } } </code></pre> <p>On the update page, I got an error</p> <blockquote> <p>**Conversion failed when converting the nvarchar value '=2' to data type int. ** can anyone help me how to fix it? my code seems to be correct. but I got an error. .................................................</p> </blockquote> <p>Data Base Structure</p> <p><a href="https://i.stack.imgur.com/xyAfI.jpg" rel="nofollow noreferrer">Data Base Structure</a></p>
[ { "answer_id": 74436093, "author": "Zeynep Evecen", "author_id": 13856050, "author_profile": "https://Stackoverflow.com/users/13856050", "pm_score": 0, "selected": false, "text": "const response = await \nfetch(\"https://www.googleapis.com/youtube/v3/channels? \npart=snippet,statistic&mine=true&key=[API_KEY]\",{\n \" Authorization: Bearer `${accessToken}`\"\n}) //here just add bearer\n}catch(error){\n//err\n}```\n" }, { "answer_id": 74481884, "author": "aparent", "author_id": 6427745, "author_profile": "https://Stackoverflow.com/users/6427745", "pm_score": 0, "selected": false, "text": "'prompt':'select_account'" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454790/" ]
74,368,897
<p>I have a ASP.NET Core 6 API deployed to Azure using the F1 free App Plan. Calling any endpoint returns a status code of 500.</p> <p>I used the Log stream feature. Below my signature I will post the whole thing but the highlights are these:</p> <ul> <li>IIS was not able to access the web.config file for the Web site</li> <li>The authenticated user does not have permission to use this DLL.</li> <li>Install the .NET Extensibility feature if the request is mapped to a managed handler</li> </ul> <p>My ASP.NET Core 6 API does not have a web.config file at all. It has appsettings.json file but not web.config file. Should I add one?</p> <p>Below my sig I will add the full log. I appreciate any help! Thanks, Dan</p> <pre class="lang-cs prettyprint-override"><code>2022-11-08T14:52:02 Welcome, you are now connected to log-streaming service. The default timeout is 2 hours. Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds). </code></pre> <p>IIS Detailed Error - 500.0 - Internal Server Error</p> <h3>HTTP Error 500.0 - Internal Server Error</h3> <h4>The page cannot be displayed because an internal server error has occurred.</h4> <h4>Most likely causes:</h4> <ul> <li>IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.</li> <li>IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.</li> <li>IIS was not able to process configuration for the Web site or application.</li> <li>The authenticated user does not have permission to use this DLL.</li> <li>The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.</li> </ul> <h4>Things you can try:</h4> <ul> <li>Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account.</li> <li>Check the event logs to see if any additional information was logged.</li> <li>Verify the permissions for the DLL.</li> <li>Install the .NET Extensibility feature if the request is mapped to a managed handler.</li> <li>Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439" rel="nofollow noreferrer">here</a>.</li> </ul> <h4>Detailed Error Information:</h4> <pre class="lang-cs prettyprint-override"><code>Module AspNetCoreModuleV2Notification ExecuteRequestHandlerHandler aspNetCoreError Code 0x00000000 Requested URL https://FlowCastApi20221108072930:80/api/cohortPhysical Path C:\home\site\wwwroot\api\cohortLogon Method AnonymousLogon User Anonymous </code></pre> <h4>More Information:</h4> <p>This error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error.</p> <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=500,0,0x00000000,14393" rel="nofollow noreferrer">View more information »</a></p> <p>Microsoft Knowledge Base Articles:</p> <pre class="lang-cs prettyprint-override"><code>2022-11-08 14:52:09.840 +00:00 [Error] Microsoft.EntityFrameworkCore.Database.Connection: An error occurred using the connection to database 'flowcast-dev' on server 'tcp:greenshoes-dev.database.windows.net,1433'. 2022-11-08 14:52:09.853 +00:00 [Error] Microsoft.EntityFrameworkCore.Query: An exception occurred while iterating over the results of a query for context type 'FlowCastApi.Model.DataContext'.Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open server 'greenshoes-dev' requested by the login. Client with IP address '20.49.104.46' is not allowed to access the server. To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()--- End of stack trace from previous location ---at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()ClientConnectionId:ec461d75-6cc2-4508-9541-47d546a25d0dError Number:40615,State:1,Class:14ClientConnectionId before routing:f9b3f656-f418-4e09-ac95-a3ab8ace69a6Routing Destination:e194283991a1.tr29051.eastus1-a.worker.database.windows.net,11042Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open server 'greenshoes-dev' requested by the login. Client with IP address '20.49.104.46' is not allowed to access the server. To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()--- End of stack trace from previous location ---at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()ClientConnectionId:ec461d75-6cc2-4508-9541-47d546a25d0dError Number:40615,State:1,Class:14ClientConnectionId before routing:f9b3f656-f418-4e09-ac95-a3ab8ace69a6Routing Destination:e194283991a1.tr29051.eastus1-a.worker.database.windows.net,11042 2022-11-08 14:52:09.872 +00:00 [Error] Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer: Connection ID &quot;15204152343613408971&quot;, Request ID &quot;800006cc-0000-d300-b63f-84710c7967bb&quot;: An unhandled exception was thrown by the application.Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open server 'greenshoes-dev' requested by the login. Client with IP address '20.49.104.46' is not allowed to access the server. To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()--- End of stack trace from previous location ---at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)at FlowCastApi.Controllers.BaseController`1.GetAllAsync(Int32 count, Int32 skip, String searchTerm, String sortBy) in C:\_source\Greenshoes\api_dotnet\FlowCastApi\Controllers\Base\BaseController.cs:line 41at lambda_method5(Closure , Object )at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()ClientConnectionId:ec461d75-6cc2-4508-9541-47d546a25d0dError Number:40615,State:1,Class:14ClientConnectionId before routing:f9b3f656-f418-4e09-ac95-a3ab8ace69a6Routing Destination:e194283991a1.tr29051.eastus1-a.worker.database.windows.net,11042 </code></pre>
[ { "answer_id": 74373544, "author": "Harshitha", "author_id": 19648279, "author_profile": "https://Stackoverflow.com/users/19648279", "pm_score": 2, "selected": true, "text": "ASP.Net CORE Web API" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1380649/" ]
74,368,902
<p>I have a <code>contentEditable</code> component:</p> <p><strong>EditableComponent.js</strong></p> <pre><code>const EditableComponent = (props) =&gt; { return &lt;p contentEditable&gt;{props.children}&lt;/p&gt;; }; </code></pre> <p>In the <code>ParentComponent</code> I can add <code>EditableComponent</code>s to an <code>array (someArr)</code> with <code>useState</code>, and then I pass <code>someArr</code> and <code>setSomeArray</code> via <code>props</code> to another component (<code>AllEditable</code>) to render it:</p> <p><strong>ParentComponent.js</strong></p> <pre><code>import EditableComponent from &quot;./components&quot;; import AllEditable from &quot;./components&quot;; const ParentComponent = () =&gt; { const [someArr, setSomeArr] = useState([]); const handleNewEditable = () =&gt; { setContentArr((prevContentArr) =&gt; { return [...prevContentArr, &lt;EditableComponent /&gt;]; }); }; return ( &lt;div className=&quot;wrapper&quot;&gt; &lt;AllEditable someArr={someArr} setSomeArr={setSomeArr} /&gt; &lt;div&gt; &lt;button onClick={handleNewEditable}&gt;Add&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ); }; </code></pre> <p>Each rendered component (<code>EditableComponent</code>) have a <code>span</code> with the content 'X' that should delete the target <code>onClick</code>:</p> <p><strong>AllEditable.js</strong></p> <pre><code>const AllEditable= (props) =&gt; { const deleteContentHandler = (index) =&gt; { props.setSomeArr((prevState) =&gt; { return prevState.filter((_, idx) =&gt; idx !== index); }); }; return ( &lt;div&gt; {props.someArr.map((content, idx) =&gt; { return ( &lt;div key={`content-${idx}`}&gt; &lt;span onClick={() =&gt; {deleteContentHandler(idx);}}&gt; X &lt;/span&gt; &lt;div&gt;{content}&lt;/div&gt; &lt;/div&gt; ); })} &lt;/div&gt; ); }; </code></pre> <h2>The problem:</h2> <p>It doesn't matter which component I'm trying to delete, it removes the <strong>last</strong> component (even in the <code>Components</code> section in the developer tools) and I'm pretty sure that the logic behind deleting (<code>filter</code>) works well.<br /></p> <p>I tried deleting the <code>contentEditable</code> attribute, and added some unique random text in each component and then it <strong>worked as expected!</strong>.<br /></p> <h2>Things I tried</h2> <ul> <li>Creating a new <code>array</code> without the removed target</li> <li>Nesting the components in <code>someArr</code> in objects with <code>key: index</code>, example: <code>{idx: 0, content: &lt;EditableComponent /&gt;}</code></li> <li>Added a <code>function - onDoubleClick</code> for each <code>EditableComponent</code> to toggle the attribute <code>contentEditable</code>, true or false.</li> <li>Replaced the element in <code>EditableComponent</code> to <code>&lt;textarea&gt;&lt;/textarea&gt;</code> instead of <code>&lt;p contentEditable&gt;&lt;/p&gt;</code></li> </ul>
[ { "answer_id": 74373544, "author": "Harshitha", "author_id": 19648279, "author_profile": "https://Stackoverflow.com/users/19648279", "pm_score": 2, "selected": true, "text": "ASP.Net CORE Web API" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559436/" ]
74,368,912
<p>I can't seem to find an answer to my question. Everything I've read on the matter seems to not quite connect and I'm starting to think what I want is impossible.</p> <p>I'm working on a very very very light database management system, it's a college project and in my group I'm tasked with the main functions. Here's my problem:</p> <p>We will run the project as <code>project.exe commands1.txt commands2.txt commands3.txt</code> for example. Now, I have to create a std::vector containing objects of the &quot;File&quot; class so they can be used later by my colleagues doing the parsing. This is the class code (not finished, still working on)</p> <pre class="lang-cpp prettyprint-override"><code>class File { protected: std::string name; std::fstream file; public: File() {} File( // TO ADD REGEX std::string name ) { if (name != &quot;&quot;) this-&gt;name = name; if (name != &quot;&quot; &amp;&amp; !this-&gt;file) this-&gt;file.open(consts::path + name); } ~File( ) { this-&gt;name = &quot;&quot;; if (this-&gt;file) this-&gt;file.close(); } std::string getName( ) { return this-&gt;name; } void setName( std::string name ) { if (name != &quot;&quot;) // TO ADD REGEX this-&gt;name = name; } std::fstream* getFile( ) { return &amp;(this-&gt;file); } bool getStatus( ) { if (this-&gt;file) return true; else return false; } }; </code></pre> <p>Also my main:</p> <pre class="lang-cpp prettyprint-override"><code>int main( int argc, char* argv[] ) { std::string current_exec_name = argv[0]; std::vector&lt;std::string&gt; all_args; all_args.assign(argv, argv + argc); std::vector&lt;Files::File&gt; commands = new // ??? } </code></pre> <p>How do I create a vector with n objects of the class File, so that each one is ran with the constructor <code>File( std::string name )</code>, with name being the equivalent argument in argv[ ]?</p> <p>Read everywhere that you can initialize them like (<a href="https://www.cs.technion.ac.il/users/yechiel/c++-faq/arrays-call-default-ctor.html" rel="nofollow noreferrer">C++ FAQ</a>)</p> <pre class="lang-cpp prettyprint-override"><code>class Fred { public: Fred(int i, int j); ← assume there is no default constructor ... }; int main() { Fred a[10] = { Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), // The 10 Fred objects are Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7) // initialized using Fred(5,7) }; ... } </code></pre> <p>but I can't use this style since I don't know how many commands (.txts) will be sent.</p>
[ { "answer_id": 74368953, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "push_back()" }, { "answer_id": 74369336, "author": "JaMiT", "author_id": 9837301, "author_profile": "https://Stackoverflow.com/users/9837301", "pm_score": 2, "selected": true, "text": "all_args" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20353864/" ]
74,368,920
<p>Hi we have a system that already has a large userbase (100k+) of microsoft users which we push updates to, using the refresh token we have saved during their inital signup.</p> <p>The REST APi will get deprecated on the 30th of November in favour of the Graph API. <a href="https://devblogs.microsoft.com/microsoft365dev/outlook-rest-api-v2-0-deprecation-notice" rel="nofollow noreferrer">https://devblogs.microsoft.com/microsoft365dev/outlook-rest-api-v2-0-deprecation-notice</a></p> <p>I have upgraded all API calls to the new graph api but am faced with the following error: <code>CompactToken parsing failed with error code: 8004920A</code></p> <p>From further digging it seems like it is caused since the tokens are not interchangable between the two APIs: <a href="https://learn.microsoft.com/en-us/answers/questions/1010061/migration-from-rest-to-graph-refreshed-token-throw.html" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/answers/questions/1010061/migration-from-rest-to-graph-refreshed-token-throw.html</a></p> <p>So is there a way to port these users into the new API without having them to go through the oauth flow again, since we don't have a functionality to request this from the users?</p>
[ { "answer_id": 74368953, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "push_back()" }, { "answer_id": 74369336, "author": "JaMiT", "author_id": 9837301, "author_profile": "https://Stackoverflow.com/users/9837301", "pm_score": 2, "selected": true, "text": "all_args" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10340220/" ]
74,368,928
<p>I am trying to solve the Golf Code challenge in freecodecamp and I can't really figure out what is wrong with my code here is the direct link. [The link][1] contains the code I am trying to run, just visit the link.</p> <p><strong>My JS:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"]; function golfScore(par, strokes) { // Only change code below this line var msg=names; switch(par,strokes){ case strokes=1: msg=names[0]; break; case strokes &lt;= par -2: msg=names[1]; break; case strokes=par-1: msg=names[2]; break; case strokes=par: msg=names[3]; break; case strokes=par+1: msg=names[4]; break; case strokes=par+2: msg=names[5]; break; case strokes &gt;= par +3: msg=names[6]; break; } return msg; // Only change code above this line } golfScore(5, 4);</code></pre> </div> </div> </p> <p><strong>Requirement:</strong></p> <p>Passed:golfScore(4, 1) should return the string Hole-in-one!</p> <p><strong>Failed:golfScore(4, 2) should return the string Eagle</strong></p> <p><strong>Failed:golfScore(5, 2) should return the string Eagle</strong></p> <p>Passed:golfScore(4, 3) should return the string Birdie</p> <p>Passed:golfScore(4, 4) should return the string Par</p> <p>Passed:golfScore(1, 1) should return the string Hole-in-one!</p> <p>Passed:golfScore(5, 5) should return the string Par</p> <p>Passed:golfScore(4, 5) should return the string Bogey</p> <p>Passed:golfScore(4, 6) should return the string Double Bogey</p> <p><strong>Failed:golfScore(4, 7) should return the string Go Home!</strong></p> <p><strong>Failed:golfScore(5, 9) should return the string Go Home!</strong></p> <p>Strokes Return: 1 &quot;Hole-in-one!&quot;</p> <pre><code> &lt;= par - 2 &quot;Eagle&quot; par - 1 &quot;Birdie&quot; par &quot;Par&quot; par + 1 &quot;Bogey&quot; par + 2 &quot;Double Bogey&quot; &gt;= par + 3 &quot;Go Home!&quot; </code></pre> <p>Actually, I found the solutions in 'if else()' but, I am trying with 'switch()' as well but those <strong>bold requirements</strong> are not being a success. [1]: <a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/golf-code" rel="nofollow noreferrer">https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/golf-code</a></p>
[ { "answer_id": 74369028, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74369070, "author": "Jhilton", "author_id": 9520479, "author_profile": "https://Stackoverflow.com/users/9520479", "pm_score": 2, "selected": true, "text": "Switch" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18347257/" ]
74,368,944
<p>I am rather new at VBA. Mostly learning it via youtube video.</p> <p>I need a little guidance for VBA code that would allow me,</p> <ol> <li>When I click the &quot;UPDATE RECEIPT&quot; button, it adds / updates value marked as A (in the RECEIPT sheet) to ROW C in the DATABASE sheet based on corresponding Invoice number marked as B</li> </ol> <p><a href="https://i.stack.imgur.com/gqvdB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gqvdB.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/DR2C7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DR2C7.png" alt="enter image description here" /></a></p> <p>I found a previous posting by TheInternet on April 6, 2018, and tried using it as based but failed miserably.</p> <pre><code>Sub RecordReceipt() x = 1 'this will find the column that matches the date and stores that as the copy location. While Sheets(&quot;Sheet10&quot;).Cells(1, x).Value &lt;&gt; Sheets(&quot;Sheet9&quot;).Range(&quot;J15&quot;) x = x + 1 Wend 'this portion copies the data to the designated coordinates found by the first portion and delete the information from L8 and L11. Sheets(&quot;Sheet10&quot;).Cells(2, x).Value = Sheets(&quot;Sheet9&quot;).Range(&quot;Receipt!H5&quot;).Value Sheets(&quot;Sheet10&quot;).Range(&quot;&quot;).Value = &quot;&quot; End Sub </code></pre> <p>Really need your help :)</p>
[ { "answer_id": 74369028, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74369070, "author": "Jhilton", "author_id": 9520479, "author_profile": "https://Stackoverflow.com/users/9520479", "pm_score": 2, "selected": true, "text": "Switch" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454792/" ]
74,368,999
<p>A middleware function <code>getSession(request, opts): void</code> retrieves a <code>session</code> from the database and attaches it to the <code>request</code>, using some <code>opts</code>.</p> <ul> <li>If the route is not protected, it will return early;</li> <li>If the route is protected and no <code>account</code> is stored for the <code>session</code>, it will redirect to the /home route;</li> <li>If the route is protected and no <code>profile</code> is stored for the <code>session</code>, it will redirect to the /create-profile route.</li> </ul> <p>Thus, a <code>request.session</code> will have either:</p> <ul> <li>No <code>account</code>,</li> <li>An <code>account</code>, or</li> <li>An <code>account</code> and a <code>profile</code>.</li> </ul> <p><strong>Problem:</strong></p> <p>How can I infer the type of <code>request.session</code> by the <code>request</code> and <code>opts</code> provided to <code>getSession()</code>?</p> <p><strong>Example:</strong></p> <p>The current types, implementation and usage of <code>getSession()</code> are provided below.</p> <pre class="lang-js prettyprint-override"><code>// utils/types.ts interface Session { id: number; // ... account: Account | null; } interface Account { id: number; // ... profile: Profile | null; } interface Profile { id: number; // ... } interface HttpRequest extends Request { session: Session; } </code></pre> <pre class="lang-js prettyprint-override"><code>// utils/session.ts const getSession = async (request: HttpRequest, opts: { protected?: boolean } = {}) =&gt; { // Set request.session as session retrieved from database // EXAMPLE: session with an account and no profile request.session = { id: 1, account: { id: 1, profile: null } }; // If route is not protected: return early if (!opts.protected) { return; } // If route is protected and there is no account: redirect to /home route if (!request.session.account) { throw new Response(null, { status: 302, headers: { Location: &quot;/home&quot; } }); } // If route is protected and there is no profile: redirect to /create-profile route if (!request.session.account?.profile) { throw new Response(null, { status: 302, headers: { Location: &quot;/create-profile&quot; } }); } }; </code></pre> <pre class="lang-js prettyprint-override"><code>// routes/create-profile.tsx const loader = async (request: HttpRequest) =&gt; { try { await getSession(request, { protected: true }); // TODO: // Infer if the request.session has an account or profile after calling getSession() // EXAMPLE: // If route is protected and no redirect to /home page: // Infer that there is an account, i.e. request.session.account is not null const account = request.session.account; return null; } catch (error) { return error; } }; </code></pre>
[ { "answer_id": 74369786, "author": "Marat", "author_id": 15775222, "author_profile": "https://Stackoverflow.com/users/15775222", "pm_score": 0, "selected": false, "text": "interface HttpRequest<SessionType> extends Request {\n session: SessionType\n}\n" }, { "answer_id": 74380161, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 2, "selected": true, "text": "getSession()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74368999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11150983/" ]
74,369,007
<p>Using the Python <code>dataclass</code> decorator generates signatures with arguments in a particular order:</p> <pre><code>from dataclasses import dataclass from inspect import signature @dataclass class Person: age: int name: str = 'John' print(signature(Person)) </code></pre> <p>Gives <code>(age: int, name: str = 'John') -&gt; None</code>.</p> <p>Is there a way to capture the order of arguments given when Person is instantiated? That is: <code>Person(name='Jack', age=10) -&gt; ('name', 'age')</code>. I'm at a loss because writing an <code>__init__</code> method on <code>Person</code> defeats most reasons for using the <code>dataclass</code> decorator. I don't want to lose the type hints you get when creating a <code>Person</code>, but I need to serialize the instance to JSON with keys in the order used at initialization.</p>
[ { "answer_id": 74369072, "author": "Silvio Mayolo", "author_id": 2288659, "author_profile": "https://Stackoverflow.com/users/2288659", "pm_score": 1, "selected": true, "text": "__init__" }, { "answer_id": 74371802, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 2, "selected": false, "text": "dataclasses" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/687112/" ]
74,369,046
<p>I'm very new to Julia, and I'm trying to just pass an array of numbers into a function and count the number of zeros in it. I keep getting the error:</p> <blockquote> <p>ERROR: UndefVarError: array not defined</p> </blockquote> <p>I really don't understand what I am doing wrong, so I'm sorry if this seems like such an easy task that I can't do.</p> <pre><code>function number_of_zeros(lst::array[]) count = 0 for e in lst if e == 0 count + 1 end end println(count) end lst = [0,1,2,3,0,4] number_of_zeros(lst) </code></pre>
[ { "answer_id": 74372141, "author": "Shayan", "author_id": 11747148, "author_profile": "https://Stackoverflow.com/users/11747148", "pm_score": 2, "selected": false, "text": "count" }, { "answer_id": 74372468, "author": "Nils Gudat", "author_id": 2499892, "author_profile": "https://Stackoverflow.com/users/2499892", "pm_score": 3, "selected": false, "text": "Array" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454998/" ]
74,369,180
<p>I am trying to implement a Success Confirmation popup modal after a successful axios.delete call.</p> <p>The delete is working and even console.log() works inside of my conditional rendering but I've noticed that my initial state is false, on successful delete (inside of my try block) the state changes to true but then once the component re-renders it chnages back to false, causing my popup modal to not render.</p> <p>I'm not sure if the try block is the issue or the way I'm trying to render the popup modal.</p> <blockquote> <p>Initial State</p> </blockquote> <pre><code>const [showSuccess, setShowSuccess] = useState(false); </code></pre> <blockquote> <p>axios request</p> </blockquote> <pre><code>const deleteService = async (id: number) =&gt; { try { const JWT = await getCookie(&quot;auth&quot;); const { data } = await axios( `/api/serviceType/${id}`, { method: &quot;DELETE&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, Authorization: JWT, }, }); setData(data); // Success Alert Popup setShowSuccess(true); } catch (e) { // Error Alert Popup setShowAlert(true); } }; </code></pre> <p>The alert state change inside of the catch block works as needed!</p> <blockquote> <p>Conditional Render</p> </blockquote> <pre><code>// Table state update on submit useEffect(() =&gt; { fetchData(data); }, [data]); // Success Alert if (showSuccess === true) { return ( &lt;&gt; &lt;Modal show={show} onHide={() =&gt; {setShowSuccess(false); handleClose(); }} backdrop=&quot;static&quot;&gt; &lt;Modal.Header closeButton style={{ backgroundColor: &quot;#00E676&quot;}}&gt;&lt;/Modal.Header&gt; &lt;AlertDialog title={&quot;Success!&quot;} message={&quot;Service Type was successfully deleted.&quot;} /&gt; &lt;/Modal&gt; &lt;/&gt; ) } if (showAlert === true) { return ( &lt;&gt; &lt;Modal show={show} onHide={() =&gt; {setShowAlert(false); handleClose(); }} backdrop=&quot;static&quot;&gt; &lt;Modal.Header closeButton style={{ backgroundColor: &quot;#FF1744&quot;}}&gt;&lt;/Modal.Header&gt; &lt;AlertDialog title={&quot;Error Deleting Data&quot;} message={&quot;There was an error deleting the Service.&quot;} /&gt; &lt;/Modal&gt; &lt;/&gt; ) } return ( &lt;&gt; &lt;Trash onClick={handleShow}/&gt; &lt;Modal show={show} backdrop=&quot;static&quot; onHide={handleClose}&gt; &lt;Modal.Header closeButton&gt; &lt;Modal.Title&gt;Delete Service&lt;/Modal.Title&gt; &lt;/Modal.Header&gt; &lt;Modal.Body&gt; Are you sure you want to delete this Service? This process cannot be undone. &lt;/Modal.Body&gt; &lt;Modal.Footer&gt; &lt;Button variant=&quot;outline-dark&quot; onClick={handleClose}&gt; Cancel &lt;/Button&gt; &lt;Button type=&quot;submit&quot; variant=&quot;danger&quot; onClick={() =&gt; deleteService(id)}&gt; Delete &lt;/Button&gt; &lt;/Modal.Footer&gt; &lt;/Modal&gt; &lt;/&gt; ); </code></pre> <p>The error modal and confirm modal work, but the success modal is not.</p> <blockquote> <p>Entire Component</p> </blockquote> <pre><code>import React, { useState, useEffect } from 'react'; import { getCookie } from &quot;../../../utils/cookies&quot;; import axios from &quot;axios&quot;; import Button from 'react-bootstrap/Button'; import Modal from 'react-bootstrap/Modal'; import { Trash } from 'react-bootstrap-icons'; import AlertDialog from '../../../alerts/AlertDialog'; export default function DeleteService({ fetchData, id }) { const [show, setShow] = useState(false); const handleClose = () =&gt; setShow(false); const handleShow = () =&gt; setShow(true); const [isLoading, setIsLoading] = useState(true); const [data, setData] = useState([]); // Success Dialog const [showSuccess, setShowSuccess] = useState(false); console.log(showSuccess) // Error Dialog const [showAlert, setShowAlert] = useState(false); // DELETE const deleteService = async (id: number) =&gt; { try { const JWT = await getCookie(&quot;auth&quot;); const { data } = await axios( `/api/serviceType/${id}`, { method: &quot;DELETE&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, Authorization: JWT, }, }); setData(data); setIsLoading(false); // Hides Modal on submission setShow(false); // Success Alert Popup setShowSuccess(true); } catch (e) { setIsLoading(false); // Error Alert Popup setShowAlert(true); } }; // Table state update on submit useEffect(() =&gt; { fetchData(data); }, [data]); // Success Alert if (showSuccess === true) { return ( &lt;&gt; &lt;Modal show={show} onHide={() =&gt; {setShowSuccess(false); handleClose(); }} backdrop=&quot;static&quot;&gt; &lt;Modal.Header closeButton style={{ backgroundColor: &quot;#00E676&quot;}}&gt;&lt;/Modal.Header&gt; &lt;AlertDialog title={&quot;Success!&quot;} message={&quot;Service was successfully deleted.&quot;} /&gt; &lt;/Modal&gt; &lt;/&gt; ) } if (showAlert === true) { return ( &lt;&gt; &lt;Modal show={show} onHide={() =&gt; {setShowAlert(false); handleClose(); }} backdrop=&quot;static&quot;&gt; &lt;Modal.Header closeButton style={{ backgroundColor: &quot;#FF1744&quot;}}&gt;&lt;/Modal.Header&gt; &lt;AlertDialog title={&quot;Error Deleting Data&quot;} message={&quot;There was an error deleting the Service.&quot;} /&gt; &lt;/Modal&gt; &lt;/&gt; ) } return ( &lt;&gt; &lt;Trash onClick={handleShow}/&gt; &lt;Modal show={show} backdrop=&quot;static&quot; onHide={handleClose}&gt; &lt;Modal.Header closeButton&gt; &lt;Modal.Title&gt;Delete Service&lt;/Modal.Title&gt; &lt;/Modal.Header&gt; &lt;Modal.Body&gt; Are you sure you want to delete this Service? This process cannot be undone. &lt;/Modal.Body&gt; &lt;Modal.Footer&gt; &lt;Button variant=&quot;outline-dark&quot; onClick={handleClose}&gt; Cancel &lt;/Button&gt; &lt;Button type=&quot;submit&quot; variant=&quot;danger&quot; onClick={() =&gt; deleteService(id)}&gt; Delete &lt;/Button&gt; &lt;/Modal.Footer&gt; &lt;/Modal&gt; &lt;/&gt; ); } </code></pre>
[ { "answer_id": 74369572, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "show" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13155727/" ]
74,369,244
<p>I have a page with a select option that automatically closes when clicked on some mobile devices (Chrome/Android). This problem does not occur on the desktop nor when I debug in chrome as mobile. It's a Shopify site, coded with the language &quot;liquid&quot;, which basically is html.</p> <p>After some days testing, I discovered thats the issue is happening because of some compatibilities problems with the Facebook Pixels code, and my page, thats refreshing and closes my select. After that I ve tryed some JS solutions to stop this event occurs like event.preventDefault(); and event.stopPropagation(), but not worked.</p> <p>Here's my code:</p> <pre><code>&lt;div class=&quot;selector-wrapper js product-form__item&quot;&gt; &lt;label for=&quot;SingleOptionSelector-{{ section.id }}-{{ forloop.index0 }}&quot;&gt;{{ option.name }}&lt;/label&gt; &lt;select class=&quot;single-option-selector single-option-selector-{{ section.id }} product-form__input&quot; id=&quot;SingleOptionSelector-{{ forloop.index0 }}&quot; data-name=&quot;{{ option.name }}&quot; data-index=&quot;option{{ forloop.index }}&quot;&gt; {% for value in option.values %} &lt;option value=&quot;{{ value | escape }}&quot; {% if option.selected_value==value %} selected=&quot;selected&quot; {% endif %}&gt;{{ value }}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/div&gt; &lt;script&gt; document.getElementById('SingleOptionSelector-0').onmouseup=function(e) {e.preventDefault();e.stopPropagation();}; &lt;/script&gt; </code></pre> <p>I have tried everything and Googled everything I could for several days and can't find a solution. Any ideias?</p> <p>Thanks for your help.</p>
[ { "answer_id": 74369572, "author": "Chris Hamilton", "author_id": 12914833, "author_profile": "https://Stackoverflow.com/users/12914833", "pm_score": 1, "selected": false, "text": "show" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13673711/" ]
74,369,254
<p>for a string:</p> <pre><code>0.1 --&gt; 0.10 0.2 --&gt; 0.20 0.3 --&gt; 0.30 0.35 --&gt; 0.35 </code></pre> <p>Example:</p> <pre><code>print(str(round(variableB.count('X') /len(variableA), 2))) </code></pre> <p>I tried <code>print(&quot;%.2f&quot; %str(round(variableB.count('X')/len(variableA),2)))</code>, but I got <code>TypeError: must be real number, not str</code></p> <p>then I tried</p> <pre><code>print (&quot;%.2f&quot; % int(str(round(variableB.count('X') /len(variableA), 2)))) </code></pre> <p>but I got <code>TypeError: invalid literal for int() with base 10: '0.47'</code></p> <p>same result with <code>&quot;%02d&quot; %</code></p>
[ { "answer_id": 74369284, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 1, "selected": false, "text": "%" }, { "answer_id": 74369290, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 2, "selected": false, "text": ">>> num = 3.1\n>>> f\"{num:.2f}\"\n'3.10'\n" }, { "answer_id": 74369313, "author": "nigh_anxiety", "author_id": 17030540, "author_profile": "https://Stackoverflow.com/users/17030540", "pm_score": 1, "selected": false, "text": "a = 0.1\nb = 0.2\n\n#old formatting\nprint(\"%.2f\"%a) # output 0.10\n\n# f-strings in 3.5+\nprint(f\"{b:.2f}\") # output 0.20\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208016/" ]
74,369,294
<p>I have a table that is already defined and populated. Now what I'm trying to do is to find a specific column and after that create a new column, at the moment I have the code to handle this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { something(); }); function something() { var newTh = ""; var th = $(`#tblTable th[data-something="1"]`).last(); newTh = `&lt;th data-something="1-1"&gt; New Column &lt;/th&gt;`; th.after(newTh); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table id="tblTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th data-something="1"&gt;Name&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id="tblBody"&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt;100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt;100&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt;100&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>The column is added properly but it's keeping the value from the pre-existing column. What can I do to move the content after/before adding a new column?</p>
[ { "answer_id": 74369393, "author": "dollar", "author_id": 20166094, "author_profile": "https://Stackoverflow.com/users/20166094", "pm_score": 3, "selected": true, "text": "$(document).ready(function() {\n something();\n});\n\nfunction something() {\n var newTh = \"\";\n var th = $(`#tblTable th[data-something=\"1\"]`).last();\n var index = th.index();\n newTh = `<th data-something=\"1-1\">New Column</th>`;\n\n th.after(newTh);\n\n $(\"#tblBody\").find(\"tr\").each(function(){\n var tr = $(this);\n tr.find(\"td\").eq(index).after(`<td>new column value</td>`);\n });\n}" }, { "answer_id": 74369394, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 0, "selected": false, "text": "<td>" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74369294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6855073/" ]