qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,174,757
<p>I had an error every time I restarted my App: <code>This widget has been unmounted, so the State no longer has a context (and should be considered defunct).</code> and saw that something was not correct with my initstate. The initState was:</p> <pre><code> @override void initState() { SchedulerBinding.instance.addPostFrameCallback((_) { BlocProvider.of&lt;TutSkippedCubit&gt;(context).load(); }); super.initState(); } </code></pre> <p>the methods loads the data from sharedprefs if I have already skipped the tut or not. Now I solved this issue with removing the initState method and putting the function call inside the widget build:</p> <pre><code> @override Widget build(BuildContext context) { BlocProvider.of&lt;TutSkippedCubit&gt;(context).load(); .... </code></pre> <p>The widget build gets called when the pages loads, so, isn't it the same as the initial state? For what exactly is the methode initState() and I have the feeling that my way of handling this problem is a bad practise, but what would be a better way, how do I solve it?</p>
[ { "answer_id": 74174839, "author": "Brice Kamhoua", "author_id": 16731199, "author_profile": "https://Stackoverflow.com/users/16731199", "pm_score": 0, "selected": false, "text": "BlocProvider.<T>(context)" }, { "answer_id": 74174859, "author": "Alberto de Jesús García Peña",...
2022/10/23
[ "https://Stackoverflow.com/questions/74174757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19913052/" ]
74,174,768
<p>I have the following dataset called <code>df</code>:</p> <pre><code>structure(list(col1 = c(&quot;a b&quot;, &quot;d e&quot;, &quot;g f&quot;, &quot;h j&quot;, &quot;j k&quot;, &quot;y z&quot;, &quot;e f&quot;, &quot;b c&quot;, &quot;f g&quot;, &quot;c d&quot;, &quot;y z&quot;, &quot;t u&quot;)), class = &quot;data.frame&quot;, row.names = c(NA, -12L)) </code></pre> <p>For this dataset, I have two vector with matches: A vector called <code>matching1 &lt;- c(&quot;a b&quot;, &quot;b c&quot;, &quot;c d&quot;)</code> and a vector called <code>matching2 &lt;- c(&quot;c d&quot;,&quot;e f&quot;,&quot;f g&quot;)</code>. In my <code>df</code>, I would like to create a new column and assign a value for a match. For the vector <code>matching1</code>, I would like to assign a value of 1, for the vector <code>matching2</code> I would like to assign a value of 2 and for every string not matched a value of 3. Ideally, the value assignment for vector <code>matching2</code> would not change the previous value assigment because the vector <code>matching1</code> and <code>matching2</code> both feature the string <code>&quot;d e&quot;</code>. I know I can use:</p> <pre><code>matches1 &lt;- paste0(na.omit(matching1), &quot;&quot;, collapse = &quot;|&quot;) </code></pre> <p>to create a collapsed vector with <code>or</code> and I have tried to combine it with <code>case_when</code>. However <code>case_when</code> does only allow single patterns and the list of potential matches in my original dataset is very long, so I would like to avoid spelling out every condition explicitely.</p> <p>The output should look like this:</p> <pre><code>structure(list(col1 = c(&quot;a b&quot;, &quot;d e&quot;, &quot;g f&quot;, &quot;h j&quot;, &quot;j k&quot;, &quot;y z&quot;, &quot;e f&quot;, &quot;b c&quot;, &quot;f g&quot;, &quot;c d&quot;, &quot;y z&quot;, &quot;t u&quot;), col2 = c(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;3&quot;, &quot;3&quot;, &quot;3&quot;, &quot;2&quot;, &quot;1&quot;, &quot;2&quot;, &quot;1&quot;, &quot;3&quot;, &quot;3&quot;)), class = &quot;data.frame&quot;, row.names = c(NA, -12L)) </code></pre>
[ { "answer_id": 74174961, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 3, "selected": true, "text": "df$ans<-ifelse(df$col1 %in% matching2, 2, 3)\ndf$ans<-ifelse(df$col1 %in% matching1, 1, df$ans)\n" }, { "a...
2022/10/23
[ "https://Stackoverflow.com/questions/74174768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11045110/" ]
74,174,781
<p>I have this df and trying to clean it. How to convert irs_pop,latitude,longitude and fips in real floats and ints? <a href="https://i.stack.imgur.com/Z7Owr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z7Owr.png" alt="enter image description here" /></a></p> <p>The code below returns <code>float() argument must be a string or a real number, not 'set'</code></p> <pre><code>mask['latitude'] = mask['latitude'].astype('float64') mask['longitude'] = mask['irs_pop'].astype('float64') mask['irs_pop'] = mask['irs_pop'].astype('int64') mask['fips'] = mask['fips'].astype('int64') </code></pre> <p>Code below returns <code>sequence item 0: expected str instance, float found</code></p> <pre><code>mask['fips'] = mask['fips'].apply(lambda x: ','.join(x)) </code></pre> <p><code>mask = mask.astype({'fips' : 'int64'})</code> returns <code>int() argument must be a string, a bytes-like object or a real number, not 'set'</code></p>
[ { "answer_id": 74174961, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 3, "selected": true, "text": "df$ans<-ifelse(df$col1 %in% matching2, 2, 3)\ndf$ans<-ifelse(df$col1 %in% matching1, 1, df$ans)\n" }, { "a...
2022/10/23
[ "https://Stackoverflow.com/questions/74174781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8291387/" ]
74,174,799
<p>i am a beginner at html/css and i am following a tutorial to make a navbar with flexboxes i just copied the code but it is not working properly i want to align all items in a row but when i run it in center is just stack things up</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Roboto+Slab&amp;display=swap'); *{ box-sizing: border-box; background-color: #EFF7E1; text-decoration: none; } li,a,button{ font-family: 'Roboto Slab', serif; font-weight: 400; font-size: 20px; text-decoration: none; } header{ background-image: -moz-linear-gradient(#0000ff #A2d0c1); display: flex; justify-content: space-between; align-items: center; padding: 20px 12%; } nav_links li{ display: inline-block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="menustyle.css"&gt; &lt;meta charset="UTF-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;img src="Adidas_Logo.svg.png" alt="logo" style="width: 100px;"&gt; &lt;nav&gt; &lt;ul class="nav_links"&gt; &lt;li&gt;&lt;a href="#"&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Categories&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Notifications&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;a href="#" class="cta"&gt;&lt;button&gt;Card&lt;/button&gt;&lt;/a&gt; &lt;/header&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> i tried it on all browsers</p>
[ { "answer_id": 74174836, "author": "BOZ", "author_id": 11151040, "author_profile": "https://Stackoverflow.com/users/11151040", "pm_score": 1, "selected": false, "text": ".nav_links" }, { "answer_id": 74174848, "author": "3tw", "author_id": 16942902, "author_profile": ...
2022/10/23
[ "https://Stackoverflow.com/questions/74174799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13805565/" ]
74,174,807
<p>i am trying to use the isEnabled and setIsEnabled useState Hook to update the icon of the play button. When I hit the playbutton, the icon changes appropriately with the useState Hook assumingly triggering a re render, but hitting the restart btn (although i am calling the setIsEnabled) is not triggering a re render of the playbutton icon. Is there a way to force reload it or is there something I'm doing wrong with the useState hook</p> <p>---- ActionBtn.jsx ------</p> <pre><code> export const ActionButton = (props: { name: string; themeColor: string; timerReference: any; }) =&gt; { // tracker for whether timer is active const [isEnabled, setIsEnabled] = useState(false); // handle button press for each button // settings btn const openSettings = () =&gt; { addHapticFeedback(&quot;light&quot;); alert(&quot;settings&quot;); }; // play &amp; pause btn const toggleTimer = () =&gt; { // toggle play or pause button setIsEnabled(!isEnabled); addHapticFeedback(&quot;light&quot;); if (isEnabled) { props.timerReference.current.pause(); } else { props.timerReference.current.play(); } }; // restart btn const restartTimer = () =&gt; { // deactivate timer setIsEnabled(false); addHapticFeedback(&quot;light&quot;); props.timerReference.current.reAnimate(); props.timerReference.current.pause(); }; // define type of action button based on prop passed if (props.name === &quot;settings&quot;) { return ( &lt;TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={openSettings} &gt; &lt;SettingsIcon size={iconSize} fillColor={iconColor} /&gt; &lt;/TouchableOpacity&gt; ); } else if (props.name === &quot;play&quot;) { return ( &lt;TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={toggleTimer} &gt; &lt;PlayIcon size={iconSize} fillColor={iconColor} isEnabled={isEnabled} /&gt; &lt;/TouchableOpacity&gt; ); } else if (props.name === &quot;restart&quot;) { return ( &lt;TouchableOpacity style={[styles.button, { backgroundColor: props.themeColor }]} onPress={restartTimer} &gt; &lt;RestartIcon size={iconSize} fillColor={iconColor} /&gt; &lt;/TouchableOpacity&gt; ); } else { return &lt;View /&gt;; } }; ----- ICONS.jsx ------ export const PlayIcon = (props: { size: number; fillColor: string; isEnabled: boolean; }) =&gt; { return props.isEnabled ? ( &lt;Svg width={props.size} height={props.size} viewBox=&quot;0 0 40 40&quot;&gt; &lt;Path d=&quot;M25 31.6666C24.0833 31.6666 23.2989 31.3405 22.6467 30.6883C21.9933 30.035 21.6667 29.25 21.6667 28.3333V11.6666C21.6667 10.75 21.9933 9.96553 22.6467 9.31331C23.2989 8.65998 24.0833 8.33331 25 8.33331H28.3333C29.25 8.33331 30.035 8.65998 30.6883 9.31331C31.3406 9.96553 31.6667 10.75 31.6667 11.6666V28.3333C31.6667 29.25 31.3406 30.035 30.6883 30.6883C30.035 31.3405 29.25 31.6666 28.3333 31.6666H25ZM11.6667 31.6666C10.75 31.6666 9.96555 31.3405 9.31333 30.6883C8.65999 30.035 8.33333 29.25 8.33333 28.3333V11.6666C8.33333 10.75 8.65999 9.96553 9.31333 9.31331C9.96555 8.65998 10.75 8.33331 11.6667 8.33331H15C15.9167 8.33331 16.7017 8.65998 17.355 9.31331C18.0072 9.96553 18.3333 10.75 18.3333 11.6666V28.3333C18.3333 29.25 18.0072 30.035 17.355 30.6883C16.7017 31.3405 15.9167 31.6666 15 31.6666H11.6667Z&quot; fill={props.fillColor} /&gt; &lt;/Svg&gt; ) : ( &lt;Svg width={props.size} height={props.size} viewBox=&quot;0 0 55 55&quot;&gt; &lt;Path d=&quot;M21.84 41.277c-.762.495-1.534.523-2.316.084-.78-.437-1.17-1.113-1.17-2.028V15.667c0-.915.39-1.592 1.17-2.03.782-.438 1.554-.41 2.317.086l18.635 11.833c.686.458 1.03 1.106 1.03 1.944 0 .838-.344 1.486-1.03 1.944L21.841 41.277Z&quot; fill={props.fillColor} /&gt; &lt;/Svg&gt; ); }; export const RestartIcon = (props: { size: number; fillColor: string }) =&gt; { return ( &lt;Svg width={props.size} height={props.size} viewBox=&quot;0 0 46 46&quot;&gt; &lt;Path d=&quot;M24.875 22.25L29.5625 26.9375C29.9062 27.2812 30.0781 27.7187 30.0781 28.25C30.0781 28.7812 29.9062 29.2187 29.5625 29.5625C29.2188 29.9062 28.7812 30.0781 28.25 30.0781C27.7188 30.0781 27.2812 29.9062 26.9375 29.5625L21.6875 24.3125C21.5 24.125 21.3594 23.9137 21.2656 23.6787C21.1719 23.445 21.125 23.2031 21.125 22.9531V15.5C21.125 14.9687 21.305 14.5231 21.665 14.1631C22.0238 13.8044 22.4688 13.625 23 13.625C23.5312 13.625 23.9769 13.8044 24.3369 14.1631C24.6956 14.5231 24.875 14.9687 24.875 15.5V22.25ZM23 39.875C19.2188 39.875 15.8281 38.7575 12.8281 36.5225C9.82812 34.2887 7.8125 31.375 6.78125 27.7812C6.625 27.2187 6.68 26.6875 6.94625 26.1875C7.21125 25.6875 7.625 25.375 8.1875 25.25C8.71875 25.125 9.19562 25.2419 9.61812 25.6006C10.0394 25.9606 10.3281 26.4062 10.4844 26.9375C11.2969 29.6875 12.8675 31.9062 15.1962 33.5937C17.5237 35.2812 20.125 36.125 23 36.125C26.6562 36.125 29.7575 34.8512 32.3037 32.3037C34.8512 29.7575 36.125 26.6562 36.125 23C36.125 19.3437 34.8512 16.2419 32.3037 13.6944C29.7575 11.1481 26.6562 9.875 23 9.875C20.8438 9.875 18.8281 10.375 16.9531 11.375C15.0781 12.375 13.5 13.75 12.2188 15.5H15.5C16.0312 15.5 16.4769 15.6794 16.8369 16.0381C17.1956 16.3981 17.375 16.8437 17.375 17.375C17.375 17.9062 17.1956 18.3512 16.8369 18.71C16.4769 19.07 16.0312 19.25 15.5 19.25H8C7.46875 19.25 7.02375 19.07 6.665 18.71C6.305 18.3512 6.125 17.9062 6.125 17.375V9.875C6.125 9.34375 6.305 8.89812 6.665 8.53813C7.02375 8.17938 7.46875 8 8 8C8.53125 8 8.97687 8.17938 9.33687 8.53813C9.69562 8.89812 9.875 9.34375 9.875 9.875V12.4062C11.4688 10.4062 13.4144 8.85937 15.7119 7.76562C18.0081 6.67187 20.4375 6.125 23 6.125C25.3438 6.125 27.5394 6.57 29.5869 7.46C31.6331 8.35125 33.4144 9.55437 34.9306 11.0694C36.4456 12.5856 37.6488 14.3669 38.54 16.4131C39.43 18.4606 39.875 20.6562 39.875 23C39.875 25.3437 39.43 27.5387 38.54 29.585C37.6488 31.6325 36.4456 33.4137 34.9306 34.9287C33.4144 36.445 31.6331 37.6487 29.5869 38.54C27.5394 39.43 25.3438 39.875 23 39.875Z&quot; fill={props.fillColor} /&gt; &lt;/Svg&gt; ); }; </code></pre>
[ { "answer_id": 74174836, "author": "BOZ", "author_id": 11151040, "author_profile": "https://Stackoverflow.com/users/11151040", "pm_score": 1, "selected": false, "text": ".nav_links" }, { "answer_id": 74174848, "author": "3tw", "author_id": 16942902, "author_profile": ...
2022/10/23
[ "https://Stackoverflow.com/questions/74174807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11683609/" ]
74,174,829
<p>i need to get the maximum interval between two consecutive numbers. Numbers are entered as arguments. Wrote some solution, but don't know how to move on. How can this problem be solved?</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 maxInterv = (...args) =&gt; { let maxInterval = 0; let interval = 0; for (let i = 0; i &lt; args.length; i++) { interval = args[i + 1] - args[i]; } }; const result = maxInterv(3, 5, 2, 7, 11, 0, -2); //11 console.log(result)</code></pre> </div> </div> </p>
[ { "answer_id": 74174878, "author": "Jan Krupiński", "author_id": 12620340, "author_profile": "https://Stackoverflow.com/users/12620340", "pm_score": 0, "selected": false, "text": "maxInterval" }, { "answer_id": 74174884, "author": "Konrad", "author_id": 5089567, "auth...
2022/10/23
[ "https://Stackoverflow.com/questions/74174829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20291334/" ]
74,174,833
<p>I am making a shopping page and I have products displayed. Every time a user clicks on a product, router should render the product page where all the info on the product will be.</p> <p>I have my routes set up like this:</p> <pre><code>&lt;BrowserRouter&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/products&quot; element={&lt;Products /&gt;}&gt; &lt;Route path=&quot;:productId&quot; element={&lt;SelectedProduct /&gt;} /&gt; &lt;/Route&gt; &lt;/Routes&gt; &lt;/BrowserRouter&gt; </code></pre> <p>And inside of <code>&lt;Products /&gt;</code> I have:</p> <pre><code>return ( &lt;div className=&quot;full-products-container&quot;&gt; &lt;div className=&quot;displayed-products-container&quot;&gt; {productsToDisplay.map((product) =&gt; ( &lt;Link to={`/products/${product.id}`} key={product.id} className=&quot;product-box&quot; &gt; &lt;img src={product.image} className=&quot;product-image-displayed&quot; /&gt; &lt;div className=&quot;product-name&quot;&gt;{product.name}&lt;/div&gt; &lt;div className=&quot;product-price&quot;&gt;${formatNumber(product.price)}&lt;/div&gt; &lt;/Link&gt; ))} &lt;/div&gt; &lt;Outlet /&gt; &lt;/div&gt; ); </code></pre> <p>And now every time a product is clicked, the <code>&lt;SelectedProduct /&gt;</code> component gets rendered inside of my <code>&lt;Products /&gt;</code> component?</p> <p>How do I make it that every time a product is clicked, the <code>&lt;SelectedProduct /&gt;</code> renders entirely? And not inside of it's parent?</p>
[ { "answer_id": 74174878, "author": "Jan Krupiński", "author_id": 12620340, "author_profile": "https://Stackoverflow.com/users/12620340", "pm_score": 0, "selected": false, "text": "maxInterval" }, { "answer_id": 74174884, "author": "Konrad", "author_id": 5089567, "auth...
2022/10/23
[ "https://Stackoverflow.com/questions/74174833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19788174/" ]
74,174,835
<p>I'm trying to detect collision in some cases, headshot, not headshot, missing the target. Here is how I tried to achieve it:</p> <pre><code> private void OnCollisionEnter(Collision collision) { if (interations.won &amp;&amp; interations.currentlyPickedUpObject == null) { if (collision.collider == head) { Debug.Log(&quot;HeadShot&quot;); } if (collision.collider == body || collision.collider == feet) { Debug.Log(&quot;Not a HeadShot&quot;); } else { Debug.Log(&quot;You've missed the target&quot;); } } } </code></pre> <p>The issue I'm facing is that the if and the else both get executed! shouldn't the else block get executed only if the if conditions are not met? why is this happening? I want to execute the else part only if the two conditions are false!</p> <p><a href="https://i.stack.imgur.com/j0aYX.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74174878, "author": "Jan Krupiński", "author_id": 12620340, "author_profile": "https://Stackoverflow.com/users/12620340", "pm_score": 0, "selected": false, "text": "maxInterval" }, { "answer_id": 74174884, "author": "Konrad", "author_id": 5089567, "auth...
2022/10/23
[ "https://Stackoverflow.com/questions/74174835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20316475/" ]
74,174,838
<p>Here are two times in db in time format: &quot;10:00:00&quot; and &quot;11:00:00&quot;.</p> <p>I have tried to compare them:</p> <pre><code> $starttime = Carbon::parse($icomingdate['&quot;starttime']); $endtime = Carbon::parser($icomingdate[&quot;endtime&quot;]); if($starttime + 30 &gt; $endtime &amp;&amp; $endtime &lt;= '23:59:00') { echo &quot;Greated then start time + 30 minutes&quot;; } </code></pre> <p>How to do that properly in Carbon?</p> <p>My full code is:</p> <pre><code> $date1 = [&quot;date&quot; =&gt; &quot;2022-10-23&quot;, &quot;starttime&quot; =&gt; &quot;10:00:00&quot;, &quot;endtime&quot; =&gt; &quot;11:00:00&quot;]; $date2 = [&quot;date&quot; =&gt; &quot;2022-10-23&quot;, &quot;starttime&quot; =&gt; &quot;11:00:00&quot;, &quot;endtime&quot; =&gt; &quot;12:00:00&quot;]; $icomedate = [&quot;date&quot; =&gt; &quot;2022-10-23&quot;, &quot;starttime&quot; =&gt; &quot;10:00:00&quot;, &quot;endtime&quot; =&gt; &quot;10:30:00&quot;]; $dates = [$date1, $date2]; try { $starttime = Carbon::parse($icomedate[&quot;starttime&quot;]); $endtime = Carbon::parse($icomedate[&quot;endtime&quot;]); $date = Carbon::parse($icomedate[&quot;date&quot;]); $interval = 30; if ($endtime &lt; $starttime) { throw new Error(&quot;End time should be greate start time&quot;); } if($endtime &lt; $starttime-&gt;addMinutes($interval)) { throw new \Exception(&quot;Interval&quot;); } if($endtime &gt; $date-&gt;endOfDay()) { throw new \Exception(&quot;End time can not be more then end of day&quot;); } if($starttime &lt; $date-&gt;startOfDay()) { throw new \Exception(&quot;End time can not be less then start of day&quot;); } foreach ($dates as $date) { $stime = Carbon::parse($date[&quot;starttime&quot;]); $etime = Carbon::parse($date[&quot;endtime&quot;]); if ($starttime &gt;= $stime &amp;&amp; $starttime &lt;= $etime) { throw new \Exception(&quot;Start\Endtime time crossed&quot;); } } } catch (\Exception $e) { dd($e-&gt;getMessage()); } </code></pre> <p>So I try to check times for selected date.</p>
[ { "answer_id": 74174878, "author": "Jan Krupiński", "author_id": 12620340, "author_profile": "https://Stackoverflow.com/users/12620340", "pm_score": 0, "selected": false, "text": "maxInterval" }, { "answer_id": 74174884, "author": "Konrad", "author_id": 5089567, "auth...
2022/10/23
[ "https://Stackoverflow.com/questions/74174838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317207/" ]
74,174,842
<p>I've used a recursive loop to find path between words formed by one-letter changes. For example:</p> <p>MAN--&gt;CUT</p> <ul> <li>MAN</li> <li>CAN</li> <li>CAT</li> <li>CUT</li> </ul> <p>The recursive function uses <strong>while</strong> to look at the one-letter neighbors of a word and find the neighbor that is most like the goal word. Then using that word it goes deeper, up to a depth of two more than the letter difference between the start and goal word. (This seems to be sufficient for most cases, although proving this is a whole other matter)</p> <p>The problem is my recursive function is giving me trouble. At first I just tried to use a &quot;break&quot; but the recursion would keep running after. So, I searched here for methods to fix that issue. To save you reading all of the classes and functions I've made I created a stripped down version that produced the same error.</p> <pre><code>def recurse(c): try: while c&gt;0: print(c) c-=1 if c==5: raise StopIteration recurse(c-1) except StopIteration: print(&quot;We found the word. Stop the recursion.&quot;) recurse(12) </code></pre> <p>If you run this code the exception will be raised multiple time and the recursion won't stop. I read about this method using exceptions to stop a recursion in its tracks in another post here, but the case of use was a bit different.</p> <p>Have I implemented this incorrectly?</p>
[ { "answer_id": 74174843, "author": "futurebird", "author_id": 4752610, "author_profile": "https://Stackoverflow.com/users/4752610", "pm_score": 0, "selected": false, "text": "def recurse(c):\n\n while c>0:\n print(c)\n c-=1\n if c==5:\n raise StopIteration\n\n ...
2022/10/23
[ "https://Stackoverflow.com/questions/74174842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4752610/" ]
74,174,864
<p>I'm trying to open a Dialog using the click event of a button inside a different blazor component, to do that I created an AppState class with a boolean variable. At the onclick event the variable is updated, so the AppState class works correctly but the Dialog does not open. Could you tell me how to solve the problem?</p> <p>This is my Dialog component</p> <pre><code>@inject AppState appState; &lt;div class=&quot;popup-container&quot;&gt; &lt;SfDialog Target=&quot;.popup-container&quot; Width=&quot;680px&quot; Height=&quot;480px&quot; IsModal=&quot;true&quot; ShowCloseIcon=&quot;true&quot; @bind-Visible=&quot;@appState.PopupCampaignVisibility&quot;&gt; &lt;DialogTemplates&gt; &lt;Content&gt; &lt;div class=&quot;popup-content&quot;&gt; &lt;div class=&quot;svg-container&quot;&gt; /// &lt;/div&gt; &lt;div class=&quot;text-container&quot;&gt; // &lt;/div&gt; &lt;div class=&quot;button-container&quot;&gt; &lt;SfButton&gt;Inizia da zero!&lt;/SfButton&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Content&gt; &lt;/DialogTemplates&gt; &lt;/SfDialog&gt; &lt;/div&gt; </code></pre> <p>This is in my AppState class</p> <pre><code> public bool PopupCampaignVisibility { get; set; } = false; </code></pre> <p>This is in my MainLayout Component</p> <pre><code>&lt;PopupCampagna Name=&quot;Mauro&quot;&gt;&lt;/PopupCampagna&gt; </code></pre> <p>That's the component where i would like to open the Dialog</p> <pre><code>@inject AppState appState; &lt;div class=&quot;container-fluid p-0 navbarinf&quot;&gt; &lt;div class=&quot;row h-100 m-0&quot;&gt; &lt;div class=&quot;col-12 h-100 main-container&quot;&gt; &lt;div class=&quot;text-container&quot;&gt; // &lt;/div&gt; &lt;div class=&quot;button-container&quot;&gt; &lt;button @onclick=&quot;@(() =&gt; ShowPopupCampaign(true))&quot;&gt;//&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; @code { [Parameter] public string Name { get; set; } [Parameter] public string UrlSite { get; set; } void ShowPopupCampaign(bool b) { appState.PopupCampaignVisibility = b; } } </code></pre>
[ { "answer_id": 74174843, "author": "futurebird", "author_id": 4752610, "author_profile": "https://Stackoverflow.com/users/4752610", "pm_score": 0, "selected": false, "text": "def recurse(c):\n\n while c>0:\n print(c)\n c-=1\n if c==5:\n raise StopIteration\n\n ...
2022/10/23
[ "https://Stackoverflow.com/questions/74174864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12831982/" ]
74,174,881
<p>I have an array and want to change name in object { id: 4, name: 'name4' } to 'name6'</p> <pre><code>const example = [ { id: '1234', desc: 'sample1', items: [ { id: 1, name: 'name1' }, { id: 2, name: 'testItem2' } ] }, { id: '3456', desc: 'sample2', items: [ { id: 4, name: 'name4' }, { id: 5, name: 'testItem5' } ] }, </code></pre> <p>I try in this way but it isn't working</p> <pre><code>const name = 'name4'; const result = example?.forEach((group) =&gt; group.items.forEach((item) =&gt; if (item.name === name) { return item.name === 'name6'; } return null; }) ); </code></pre>
[ { "answer_id": 74174897, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": -1, "selected": false, "text": "const example = [{\n id: '1234',\n desc: 'sample1',\n items: [{\n id: 1,\n name: 'name1'\n ...
2022/10/23
[ "https://Stackoverflow.com/questions/74174881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13861133/" ]
74,174,928
<p>I have simple code</p> <pre><code>#include &lt;iostream&gt; #include &lt;set&gt; using namespace std; class Example { string name; public: Example(string name) { this -&gt; name = name; } string getName() const {return name;} }; bool operator&lt;(Example a, Example b) { return a.getName() &lt; b.getName(); } int main() { set&lt;Example&gt; exp; Example first(&quot;first&quot;); Example second(&quot;second&quot;); exp.insert(first); exp.insert(second); for(set&lt;Example&gt;::iterator itr = exp.begin(); itr != exp.end(); ++itr) { //cout&lt;&lt;*itr.getName(); - Not working cout&lt;&lt;(*itr).getName()&lt;&lt;endl; } } </code></pre> <p>I wonder why <code>*itr.getName()</code> doesn't work but <code>(*itr).getName()</code> works fine. What is the difference between <code>*itr</code> and <code>(*itr)</code> in this case?</p>
[ { "answer_id": 74174969, "author": "Nathan Pierson", "author_id": 12334309, "author_profile": "https://Stackoverflow.com/users/12334309", "pm_score": 3, "selected": true, "text": "." }, { "answer_id": 74174998, "author": "smac89", "author_id": 2089675, "author_profile...
2022/10/23
[ "https://Stackoverflow.com/questions/74174928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317241/" ]
74,174,949
<p>I am struggling getting the difference of two Timestamps in milliseconds.</p> <p>My current approach was</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM EXTRACT(EPOCH FROM(NOW()::TIMESTAMP - '2022-10-23 16:34:53.227')) </code></pre> <p>which was described on a bad website as returning the difference in seconds but in fact returning the difference defined as an interval.</p> <p>It so happens, that i am unable to multiply a factor of 1000 to get the value as milliseconds. I've then tried to cast the result as numeric or decimal, bigint, int8 and int but none these want let me use any calculation nor comparison.</p> <p>Can someone tell me, what i am misunderstanding here?</p> <p><a href="https://i.stack.imgur.com/jbU0X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jbU0X.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/80hHe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80hHe.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74174969, "author": "Nathan Pierson", "author_id": 12334309, "author_profile": "https://Stackoverflow.com/users/12334309", "pm_score": 3, "selected": true, "text": "." }, { "answer_id": 74174998, "author": "smac89", "author_id": 2089675, "author_profile...
2022/10/23
[ "https://Stackoverflow.com/questions/74174949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12720020/" ]
74,174,950
<p>I am applying the following code to obtain the max CBU. Can I also get the list of selected items in a knapsack? Here is my code</p> <pre><code>def knapsack(CBU, weight, Capacity): return knapsacksolution(CBU, weight, Capacity, 0) def knapsacksolution(CBU, weight, Capacity, currentIndex): if Capacity &lt;= 0 or currentIndex &gt;= len(CBU): return 0 CBU1 = 0 #selecting a box at currentindex if CBU[currentIndex] &lt;= Capacity: CBU1 = CBU[currentIndex] + knapsacksolution(CBU, weight, Capacity - CBU[currentIndex], currentIndex+1) #excluding a box at currentindex CBU2 = knapsacksolution(CBU, weight, Capacity, currentIndex+1) return max(CBU1, CBU2) def main(): weight = [20,15,17,24] CBU = [3,2,3,4] Capacity = 8 OptimalCBU = knapsack(CBU, weight, Capacity) print('Optimal CBU for CBU:{} with weight:{} for Capacity:{} is:{}'.format(CBU, weight, Capacity, OptimalCBU)) if __name__ == '__main__': main() </code></pre> <p><strong>Result is as follow</strong> Optimal CBU for CBU:[3, 2, 3, 4] with weight:[20, 15, 17, 24] for Capacity:8 is:8</p>
[ { "answer_id": 74174969, "author": "Nathan Pierson", "author_id": 12334309, "author_profile": "https://Stackoverflow.com/users/12334309", "pm_score": 3, "selected": true, "text": "." }, { "answer_id": 74174998, "author": "smac89", "author_id": 2089675, "author_profile...
2022/10/23
[ "https://Stackoverflow.com/questions/74174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317189/" ]
74,175,012
<p>I use <code>ag</code> to select filenames and pipe them into <code>fzy</code> with the following script</p> <pre><code>set &quot;$(ag -g &quot;\.gz$&quot; archives/ | fzy )&quot; echo &quot;selected file: $1&quot; </code></pre> <p>How can I run a function on all files in the folder <code>archives</code> , so <strong>only files in are selected, that are newer than already existing files with the same name the folder <code>itp-files/</code>?</strong> and pipe only those into <code>fzy</code> then?</p> <p>I tried something like</p> <pre><code>for f in $(ag --nonumbers -g &quot;\.gz$&quot; archives/); do echo do something with $f and only output if file is older than the same in itp-files/; done | fzy </code></pre> <p>But I am not sure how to compare the filetimes ike this</p>
[ { "answer_id": 74278454, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 0, "selected": false, "text": "xargs" }, { "answer_id": 74289269, "author": "Dominique", "author_id": 4279155, "author_profile":...
2022/10/23
[ "https://Stackoverflow.com/questions/74175012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069083/" ]
74,175,148
<p>I created a database with sqlite3 and I want to open it in DB Browser. Problem is I have no idea where to find the database so I can open it there. And when I look in my 'sqlite3' directory under conda (I'm doing all this in jupyternotebook), I can't find any databases I created.</p> <p>I can run other commands with this database I created so I know it exists. I just don't know where it's located.</p> <pre><code>import sqlite3 as sql conn = sql.connect('z') cur = conn.cursor() x = cur.execute('''SELECT year FROM z;''').fetchall() print(x) conn.close() </code></pre> <p>This works as a query, but I don't know where &quot;z&quot; is located. How do I find whre z is stored?</p> <p>I'm not sure if this is a coding question, but if it isn't, then could someone tell me where to go for questions like this?</p>
[ { "answer_id": 74175163, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " conn = sql.connect('z')\n" }, { "answer_id": 74175270, "author": "PChemGuy", "author_id": 17472988, ...
2022/10/23
[ "https://Stackoverflow.com/questions/74175148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19463812/" ]
74,175,196
<p>I am trying to retrieve a list of elements from a webpage that contain a specific string. I'm evaluating the XPath using a selenium <code>ISearchContext.FindElement(By.XPath(...))</code>, so the XPath engine is the one supported by the browser.</p> <p>Below is a minimal sample page created by me, but in a real world scenario I cannot modify the page's structure:</p> <pre class="lang-html prettyprint-override"><code>&lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;Nav Item 1&lt;/li&gt; &lt;li&gt;Nav Item 2&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;main&gt; &lt;div class=&quot;content&quot;&gt; &lt;p class=&quot;description&quot;&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab deserunt dolore eius est facere incidunt magni minus molestiae natus, nesciunt nostrum, officia perspiciatis placeat provident reiciendis saepe sed, sit voluptates.&lt;/p&gt; &lt;p class=&quot;price&quot;&gt;1.150&lt;span class=&quot;comma&quot;&gt;,&lt;/span&gt;&lt;sup&gt;00&lt;/sup&gt; &lt;span class=&quot;currency&quot;&gt;EUR&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;aside&gt; &lt;p class=&quot;price&quot;&gt;1.150&lt;span class=&quot;comma&quot;&gt;,&lt;/span&gt;&lt;sup&gt;00&lt;/sup&gt; &lt;span class=&quot;currency&quot;&gt;EUR&lt;/span&gt;&lt;/p&gt; &lt;/aside&gt; &lt;footer&gt; 1&lt;span&gt;.&lt;/span&gt;150&lt;span class=&quot;comma&quot;&gt;,&lt;/span&gt;&lt;sup&gt;00&lt;/sup&gt; &lt;span class=&quot;currency&quot;&gt;EUR&lt;/span&gt; &lt;/footer&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The elements I'm looking for are <code>[p.price, p.price, footer]</code>; basically <strong>only</strong> the &quot;deepest&quot; elements containing the string <code>1.150,00 EUR</code>.</p> <p>If I evaluate the following XPath in Chrome's Developer Tools Console</p> <pre class="lang-js prettyprint-override"><code>$x(&quot;//*[contains(., '1.150,00 EUR')][contains(ancestor::*, '1.150,00 EUR')][not(contains(child::*, '1.150,00 EUR'))]&quot;) </code></pre> <p>the result I get is <code>[body, div.content, p.price, p.price, footer]</code>.</p> <p>I'm looking for a solution that still lets me remain in the Selenium context so I can further access element properties (such as element position). It doesn't necessarily have to involve XPath and I am also open to using another browser.</p>
[ { "answer_id": 74175450, "author": "LMC", "author_id": 2834978, "author_profile": "https://Stackoverflow.com/users/2834978", "pm_score": 0, "selected": false, "text": "$x(\"//*[.='EUR']/parent::*[contains(., '1.150,00 EUR')]\")\n" }, { "answer_id": 74175673, "author": "Conal ...
2022/10/23
[ "https://Stackoverflow.com/questions/74175196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3502980/" ]
74,175,249
<p>I'm trying to scrape this website <a href="https://www.pararius.com/english" rel="nofollow noreferrer">https://www.pararius.com/english</a> to get rental information. I want to scrape all pages on this site.</p> <p>I've looked through similar questions on stackoverflow regarding scrapy pagination issues, but none seem to reflect my issue.</p> <p>Everything in my code works except for the section where I want to follow 'next_page' links. I have written another spider for another book website using the exact same concept and it works perfectly. I'm failing to join the next_page link to the start url and have scrapy automatically scrape the next page.</p> <p>Here's my code:</p> <pre><code>import scrapy from time import sleep class ParariusScraper(scrapy.Spider): name = 'pararius' start_urls = ['https://www.pararius.com/apartments/amsterdam/'] def parse(self, response): base_url = 'https://www.pararius.com/apartments/amsterdam' for section in response.css('section.listing-search-item'): yield { 'Title': section.css('h2.listing-search-item__title &gt; a::text').get().strip(), 'Location': section.css('div.listing-search-item__sub-title::text').get().strip(), 'Price': section.css('div.listing-search-item__price::text').get().strip(), 'Size': section.css('li.illustrated-features__item::text').get().strip(), 'Link':f&quot;{base_url}{section.css('h2.listing-search-item__title a').attrib['href']}&quot; } sleep(1) next_page = response.css('li.pagination__item a').attrib['href'].split('/')[-1] print(next_page) if next_page: yield response.follow(next_page, self.parse) </code></pre> <p>When I run this code, the crazy think that happens is that my code only scrapes page-2 results and not even the first page which is the start_url as seen in my code.</p> <p>I would like to know how I can fix this and have my code start working as expected. Thanks and I hope to get your support.</p>
[ { "answer_id": 74175964, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 1, "selected": true, "text": "response.urljoin()" }, { "answer_id": 74176200, "author": "Fazlul", "author_id": 12848411, "a...
2022/10/23
[ "https://Stackoverflow.com/questions/74175249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19179376/" ]
74,175,296
<p>I have to write a method that makes sure two objects are not on each other position-wise. The coordinates of these objects have to be randomly generated.</p> <p>My idea is a while-loop with getX() &amp; getY() methods, that generates new coordinates till the two objects are not on the same spot.</p> <p>Like this:</p> <pre><code>int x = getRandom(x); int y = getRandom(y); while(object1.getX() == object2.getX() &amp;&amp; object1.getY() == object2.getY()){ int x = getRandom(min, max); int y = getRandom(min, max); } </code></pre> <p>The code works most of the time. I don't get any error messages, but in the interaction window it can be seen that the rule is not always applied. Does someone maybe have an idea, what I am doing wrong?</p>
[ { "answer_id": 74175342, "author": "Bastian Hologne", "author_id": 20317450, "author_profile": "https://Stackoverflow.com/users/20317450", "pm_score": -1, "selected": false, "text": "int x = getRandom(x);\nint y = getRandom(y);\nwhile((object1.getX() == object2.getX()) && (object1.getY()...
2022/10/23
[ "https://Stackoverflow.com/questions/74175296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317493/" ]
74,175,359
<p>I need to write a function to calculate minimal sum of the local maximum of the subarrays of an array where every item is a positive integer with possible duplicates.</p> <p>For example, we have an array <code>[2, 3, 1, 4, 5, 6]</code> and the number of sub arrays is <code>3</code>. We want to get the min sum of the local max of the sub arrays. What that means is that, for example, one possible way to divide the current array into 3 sub arrays is <code>[[2,3], [1], [4,5,6]]</code> and the local maxs for each subarray is <code>3, 1, 6</code> respectively. And the sum of the local maxs is <code>3 + 1 + 6 = 10</code>. For this particular array, <code>[2, 3, 1, 4, 5, 6]</code>, this is the minimal sum of all its possible sub-array variations.</p> <p>My approach is to first get all the possible sub-array variations for a given array. and get the min sum of them.</p> <pre class="lang-js prettyprint-override"><code> function getSubarrays(array, numOfSubarray) { const results = [] const recurse = (index, subArrays) =&gt; { if (index === array.length &amp;&amp; subArrays.length === numOfSubarray) { results.push([...subArrays]) return } if (index === array.length) return // 1. push current item to the current subarray // when the remaining items are more than the remaining sub arrays needed if (array.length - index - 1 &gt;= numOfSubarray - subArrays.length) { recurse( index + 1, subArrays.slice(0, -1).concat([subArrays.at(-1).concat(array[index])]) ) } // 2. start a new subarray when the current subarray is not empty if (subArrays.at(-1).length !== 0) recurse(index + 1, subArrays.concat([[array[index]]])) } recurse(0, [[]], 0) return results } function getMinSum(arrays) { return arrays.reduce( (minSum, array) =&gt; Math.min( minSum, array.reduce((sum, subarray) =&gt; sum + Math.max(...subarray), 0) ), Infinity ) } getMinSum(getSubarrays([[2,3], [1], [4,5,6]], 3)) // 10 </code></pre> <p>However, I think the time complexity for my solution is really high. My guess is that it is on the order of <code>2^n</code> (feel free to correct me if I am wrong). I wonder if there is a more efficient way to calculate this.</p>
[ { "answer_id": 74175342, "author": "Bastian Hologne", "author_id": 20317450, "author_profile": "https://Stackoverflow.com/users/20317450", "pm_score": -1, "selected": false, "text": "int x = getRandom(x);\nint y = getRandom(y);\nwhile((object1.getX() == object2.getX()) && (object1.getY()...
2022/10/23
[ "https://Stackoverflow.com/questions/74175359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7624223/" ]
74,175,367
<p>I'm trying to inspect the behaviour of the <code>pandas.DataFrame.groupby</code> and <code>pandas.DataFrame.pivot_table</code> methods and I've come up to this difference which I can't explain by myself.</p> <p>It seems that the specification of <code>dropna=True</code> (default for both) has different consequences in the two cases, which might be somehow enforced by the different descriptions which are given within the docs.</p> <p>For <a href="https://pandas.pydata.org/pandas-docs/version/1.3/reference/api/pandas.DataFrame.pivot_table.html#pandas-dataframe-pivot-table" rel="nofollow noreferrer"><code>pandas.DataFrame.pivot_table</code></a>:</p> <blockquote> <p>dropna: bool, default True</p> <p><em><strong>Do not include columns whose entries are all NaN.</strong></em></p> </blockquote> <p>For <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby</code></a>:</p> <blockquote> <p>dropna: bool, default True</p> <p><em><strong>If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups.</strong></em></p> </blockquote> <p>This said, while I can totally understand the description given for the <code>.pivot_table()</code> method looking at the example I'll show in a while, I can't get through the nuances of the <code>dropna</code> behaviour in <code>.groupby()</code>.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'age': [31, np.nan, 28, 22, 54, np.nan, 49, 60, 25, np.nan], 'country_live': ['Italy', 'Spain', 'Italy', 'Spain', 'France', 'Italy', 'Spain', 'Spain', 'France', 'Spain'], 'employment_status': ['Fully employed by a company / organization', 'Partially employed by a company / organization', 'Working student', 'Working student', 'Fully employed by a company / organization', 'Partially employed by a company / organization', 'Fully employed by a company / organization', 'Fully employed by a company / organization', 'Working student', 'Partially employed by a company / organization'] }, ) df = df.assign(age=lambda t: t['age'].astype('Int64'), \ country_live=lambda t: t['country_live'].astype('category'), \ employment_status=lambda t: t['employment_status'].astype('category')) </code></pre> <p>With <code>.pivot_table()</code>:</p> <pre><code>df.pivot_table(index='country_live', columns='employment_status', values='age', aggfunc='mean', dropna=True) </code></pre> <p><a href="https://i.stack.imgur.com/WNlEP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNlEP.png" alt="enter image description here" /></a></p> <p>With <code>.groupby()</code> I'd instead get (while expecting the same result obtained above):</p> <pre><code>df.groupby(by=['country_live', 'employment_status'], dropna=True)['age'] \ .mean() \ .unstack() </code></pre> <p><a href="https://i.stack.imgur.com/2arlF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2arlF.png" alt="enter image description here" /></a></p> <p>Can someone explain the reason(s) why the two do not work the same (thus implicitly explaining the behaviour of <code>dropna</code> in <code>.groupby()</code>)?</p>
[ { "answer_id": 74175342, "author": "Bastian Hologne", "author_id": 20317450, "author_profile": "https://Stackoverflow.com/users/20317450", "pm_score": -1, "selected": false, "text": "int x = getRandom(x);\nint y = getRandom(y);\nwhile((object1.getX() == object2.getX()) && (object1.getY()...
2022/10/23
[ "https://Stackoverflow.com/questions/74175367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13350341/" ]
74,175,371
<p>Before rendering a page for a given route, I'd like to synchronously fetch the necessary data first. Ideally, I'd like to have the data fetching within the page component, but I'm not opposed to doing it in the router files. I've read and tried various ways of doing it, but part of the challenge comes from the fact that there are also multiple ways of building components and the usage of certain features vary.</p> <p>In my case, I'm building single file components using the Composition API and <code>&lt;script setup&gt;</code> syntax. The <a href="https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-before-navigation" rel="nofollow noreferrer">Vue Router</a> documentation link talks about &quot;fetching before navigation&quot; in which I could reach for <code>beforeRouteEnter</code> or <code>beforeRouteUpdate</code>, but this is shown using the Options API. They do have the page for the <a href="https://router.vuejs.org/guide/advanced/composition-api.html" rel="nofollow noreferrer">Composition API</a> mentioning I could use <code>onBeforeRouteUpdate</code>, but that uses the <code>setup()</code> function. I figured I'd try it out anyway with <code>&lt;script setup&gt;</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;script setup&gt; import { onBeforeRouteUpdate } from 'vue-router' onBeforeRouteUpdate(() =&gt; { console.log('onBeforeRouteUpdate') }) &lt;/script&gt; </code></pre> <p>However, this does not execute. The closest method I've tried that works is fetching the data in the router, using the <code>beforeEnter</code> guard, and setting the data onto the <code>meta</code> property, which can then get accessed on the route instance in the component:</p> <pre><code>beforeEnter: (to, from, next) =&gt; { fetch('https://pokeapi.co/api/v2/pokemon/ditto') .then(res =&gt; res.json()) .then(res =&gt; { to.meta.pokemon = res; next(); }); } </code></pre> <p>But with this, which is noted in the documentation, <code>beforeEnter</code> only triggers when entering the route. Params changes will not retrigger this, meaning that I'd have to set up a watcher on the route in the component anyway. I might as well just have had all this logic in the component itself.</p> <p>I just can't seem to find a good way to do this, but I might have overlooked something. If anyone has some pointers or advice, I'd appreciate it. Thanks in advance.</p>
[ { "answer_id": 74175342, "author": "Bastian Hologne", "author_id": 20317450, "author_profile": "https://Stackoverflow.com/users/20317450", "pm_score": -1, "selected": false, "text": "int x = getRandom(x);\nint y = getRandom(y);\nwhile((object1.getX() == object2.getX()) && (object1.getY()...
2022/10/23
[ "https://Stackoverflow.com/questions/74175371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4927864/" ]
74,175,393
<p>So, lets say I had a JSON File like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;content&quot;: [ { &quot;word&quot;: &quot;cat&quot;, &quot;adjectives&quot;: [ { &quot;type&quot;: &quot;textile&quot;, &quot;adjective&quot;: &quot;fluffy&quot; }, { &quot;type&quot;: &quot;visual&quot;, &quot;adjective&quot;: &quot;small&quot; } ] }, { &quot;word&quot;: &quot;dog&quot;, &quot;adjectives&quot;: [ { &quot;type&quot;: &quot;textile&quot;, &quot;adjective&quot;: &quot;fluffy&quot; }, { &quot;type&quot;: &quot;visual&quot;, &quot;adjective&quot;: &quot;big&quot; } ] }, { &quot;word&quot;: &quot;chocolate&quot;, &quot;adjectives&quot;: [ { &quot;type&quot;: &quot;visual&quot;, &quot;adjective&quot;: &quot;small&quot; }, { &quot;type&quot;: &quot;gustatory&quot;, &quot;adjective&quot;: &quot;sweet&quot; } ] } ] } </code></pre> <p>Now, say I wanted to search for two words. For example, &quot;Fluffy&quot; and &quot;Small.&quot; The problem with this is that both words' adjectives contain small, and so I would have to manually search for which one contains fluffy. So, how would I do this in a quicker manner?</p> <p>In other words, how would I find the word(s) with both &quot;fluffy&quot; and &quot;small&quot;</p> <p>EDIT: Sorry, new asker. Anything that words in a terminal is fair game. <code>jq</code> is a really great JSON searcher, and so this is preferred, and sorry for the confusion. I also fixed the JSON</p>
[ { "answer_id": 74175342, "author": "Bastian Hologne", "author_id": 20317450, "author_profile": "https://Stackoverflow.com/users/20317450", "pm_score": -1, "selected": false, "text": "int x = getRandom(x);\nint y = getRandom(y);\nwhile((object1.getX() == object2.getX()) && (object1.getY()...
2022/10/23
[ "https://Stackoverflow.com/questions/74175393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17984166/" ]
74,175,401
<p>I am having a weird issue where I change the location of all my code &amp; data to a different location with more disk space, then I soft link my projects &amp; data to those locations with more space. I assume there must be some file handle issue because wandb's logger is throwing me issues. So my questions:</p> <ol> <li>how do I have wandb only log online and not locally? (e.g. stop trying to log anything to <code>./wandb</code>[or any secret place it might be logging to] since it's creating issues). Note my code was running fine after I stopped logging to wandb so I assume that was the issue. note that the <code>dir=None</code> is the default to wandb's param.</li> <li>how do I resolve this issue entirely so that it works seemlessly with all my projects softlinked somewhere else?</li> </ol> <hr /> <h1>More details on the error</h1> <pre><code>Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1087, in emit self.flush() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1067, in flush self.stream.flush() OSError: [Errno 116] Stale file handle Call stack: File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 930, in _bootstrap self._bootstrap_inner() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 973, in _bootstrap_inner self.run() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/vendor/watchdog/observers/api.py&quot;, line 199, in run self.dispatch_events(self.event_queue, self.timeout) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/vendor/watchdog/observers/api.py&quot;, line 368, in dispatch_events handler.dispatch(event) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/vendor/watchdog/events.py&quot;, line 454, in dispatch _method_map[event_type](event) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/filesync/dir_watcher.py&quot;, line 275, in _on_file_created logger.info(&quot;file/dir created: %s&quot;, event.src_path) Message: 'file/dir created: %s' Arguments: ('/shared/rsaas/miranda9/diversity-for-predictive-success-of-meta-learning/wandb/run-20221023_170722-1tfzh49r/files/output.log',) --- Logging error --- Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1087, in emit self.flush() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1067, in flush self.stream.flush() OSError: [Errno 116] Stale file handle Call stack: File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 930, in _bootstrap self._bootstrap_inner() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 973, in _bootstrap_inner self.run() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/internal/internal_util.py&quot;, line 50, in run self._run() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/internal/internal_util.py&quot;, line 101, in _run self._process(record) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/internal/internal.py&quot;, line 263, in _process self._hm.handle(record) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/internal/handler.py&quot;, line 130, in handle handler(record) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/internal/handler.py&quot;, line 138, in handle_request logger.debug(f&quot;handle_request: {request_type}&quot;) Message: 'handle_request: stop_status' Arguments: () N/A% (0 of 100000) | | Elapsed Time: 0:00:00 | ETA: --:--:-- | 0.0 s/it Traceback (most recent call last): File &quot;/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py&quot;, line 1814, in &lt;module&gt; main() File &quot;/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py&quot;, line 1747, in main train(args=args) File &quot;/home/miranda9/diversity-for-predictive-success-of-meta-learning/div_src/diversity_src/experiment_mains/main_dist_maml_l2l.py&quot;, line 1794, in train meta_train_iterations_ala_l2l(args, args.agent, args.opt, args.scheduler) File &quot;/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/torch_uu/training/meta_training.py&quot;, line 167, in meta_train_iterations_ala_l2l log_zeroth_step(args, meta_learner) File &quot;/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/logging_uu/wandb_logging/meta_learning.py&quot;, line 92, in log_zeroth_step log_train_val_stats(args, args.it, step_name, train_loss, train_acc, training=True) File &quot;/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/logging_uu/wandb_logging/supervised_learning.py&quot;, line 55, in log_train_val_stats _log_train_val_stats(args=args, File &quot;/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/logging_uu/wandb_logging/supervised_learning.py&quot;, line 116, in _log_train_val_stats args.logger.log('\n') File &quot;/home/miranda9/ultimate-utils/ultimate-utils-proj-src/uutils/logger.py&quot;, line 89, in log print(msg, flush=flush) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/lib/redirect.py&quot;, line 640, in write self._old_write(data) OSError: [Errno 116] Stale file handle wandb: Waiting for W&amp;B process to finish... (failed 1). Press Control-C to abort syncing. wandb: Synced vit_mi Adam_rfs_cifarfs Adam_cosine_scheduler_rfs_cifarfs 0.001: args.jobid=101161: https://wandb.ai/brando/entire-diversity-spectrum/runs/1tfzh49r wandb: Synced 6 W&amp;B file(s), 0 media file(s), 0 artifact file(s) and 0 other file(s) wandb: Find logs at: ./wandb/run-20221023_170722-1tfzh49r/logs --- Logging error --- Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/interface/router_sock.py&quot;, line 27, in _read_message resp = self._sock_client.read_server_response(timeout=1) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/lib/sock_client.py&quot;, line 283, in read_server_response data = self._read_packet_bytes(timeout=timeout) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/lib/sock_client.py&quot;, line 269, in _read_packet_bytes raise SockClientClosedError() wandb.sdk.lib.sock_client.SockClientClosedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/interface/router.py&quot;, line 70, in message_loop msg = self._read_message() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/interface/router_sock.py&quot;, line 29, in _read_message raise MessageRouterClosedError wandb.sdk.interface.router.MessageRouterClosedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1087, in emit self.flush() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1067, in flush self.stream.flush() OSError: [Errno 116] Stale file handle Call stack: File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 930, in _bootstrap self._bootstrap_inner() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 973, in _bootstrap_inner self.run() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 910, in run self._target(*self._args, **self._kwargs) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/interface/router.py&quot;, line 77, in message_loop logger.warning(&quot;message_loop has been closed&quot;) Message: 'message_loop has been closed' Arguments: () /home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/tempfile.py:817: ResourceWarning: Implicitly cleaning up &lt;TemporaryDirectory '/srv/condor/execute/dir_27749/tmpmvf78q6owandb'&gt; _warnings.warn(warn_message, ResourceWarning) /home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/tempfile.py:817: ResourceWarning: Implicitly cleaning up &lt;TemporaryDirectory '/srv/condor/execute/dir_27749/tmpt5etqpw_wandb-artifacts'&gt; _warnings.warn(warn_message, ResourceWarning) /home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/tempfile.py:817: ResourceWarning: Implicitly cleaning up &lt;TemporaryDirectory '/srv/condor/execute/dir_27749/tmp55lzwviywandb-media'&gt; _warnings.warn(warn_message, ResourceWarning) /home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/tempfile.py:817: ResourceWarning: Implicitly cleaning up &lt;TemporaryDirectory '/srv/condor/execute/dir_27749/tmprmk7lnx4wandb-media'&gt; _warnings.warn(warn_message, ResourceWarning) </code></pre> <hr /> <p>Error:</p> <pre><code>====&gt; about to start train loop Starting training! WARNING:urllib3.connectionpool:Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1129)'))': /api/5288891/envelope/ --- Logging error --- Traceback (most recent call last): File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/logging/__init__.py&quot;, line 1086, in emit stream.write(msg + self.terminator) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/wandb/sdk/lib/redirect.py&quot;, line 640, in write self._old_write(data) OSError: [Errno 116] Stale file handle Call stack: File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 930, in _bootstrap self._bootstrap_inner() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 973, in _bootstrap_inner self.run() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/threading.py&quot;, line 910, in run self._target(*self._args, **self._kwargs) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/sentry_sdk/worker.py&quot;, line 128, in _target callback() File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/sentry_sdk/transport.py&quot;, line 467, in send_envelope_wrapper self._send_envelope(envelope) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/sentry_sdk/transport.py&quot;, line 384, in _send_envelope self._send_request( File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/sentry_sdk/transport.py&quot;, line 230, in _send_request response = self._pool.request( File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/urllib3/request.py&quot;, line 78, in request return self.request_encode_body( File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/urllib3/request.py&quot;, line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/urllib3/poolmanager.py&quot;, line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File &quot;/home/miranda9/miniconda3/envs/metalearning_gpu/lib/python3.9/site-packages/urllib3/connectionpool.py&quot;, line 780, in urlopen log.warning( Message: &quot;Retrying (%r) after connection broken by '%r': %s&quot; Arguments: (Retry(total=2, connect=None, read=None, redirect=None, status=None), SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1129)')), '/api/5288891/envelope/') </code></pre> <hr /> <h1>Bounty</h1> <p>My suggestions on what might solve this are:</p> <ol> <li>Figuring out a way to stop wandb logging locally or minimize the amount of logging wandb is logging locally.</li> <li>Figure out what is exactly being logged and minimize the space.</li> <li>have the logging work even if all the folders are being symlinked. (imho this should work out of the box)</li> <li>figuring out a systematic and simple way to find where the stale file handles are coming from.</li> </ol> <p>I am surprised moving <strong>everything</strong> to <code>/shared/rsaas/miranda9/</code> and running experiments from there did not solve the issue.</p> <hr /> <p>cross:</p> <ul> <li><a href="https://community.wandb.ai/t/how-to-stop-logging-locally-but-only-save-to-wandbs-servers-and-have-wandb-work-using-soft-links/3305" rel="nofollow noreferrer">https://community.wandb.ai/t/how-to-stop-logging-locally-but-only-save-to-wandbs-servers-and-have-wandb-work-using-soft-links/3305</a></li> <li><a href="https://www.reddit.com/r/learnmachinelearning/comments/ybvo73/how_to_stop_logging_locally_but_only_save_to/" rel="nofollow noreferrer">https://www.reddit.com/r/learnmachinelearning/comments/ybvo73/how_to_stop_logging_locally_but_only_save_to/</a></li> <li>gitissue: <a href="https://github.com/wandb/wandb/issues/4409" rel="nofollow noreferrer">https://github.com/wandb/wandb/issues/4409</a></li> </ul>
[ { "answer_id": 74284077, "author": "DialFrost", "author_id": 17698532, "author_profile": "https://Stackoverflow.com/users/17698532", "pm_score": 0, "selected": false, "text": "./wandb" } ]
2022/10/23
[ "https://Stackoverflow.com/questions/74175401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1601580/" ]
74,175,412
<p>I'm trying to save my commands in a folder instead of in one file to keep things organized, but I don't know how to import the commands.</p> <p>This is the main file:</p> <pre><code>import discord from discord.ext import commands client = commands.Bot(command_prefix=&quot;&gt;&quot;) @client.event async def on_connect(): print(f'Logged In As {client.user}') client.run(token) </code></pre> <p>And this is a test command I made:</p> <pre><code>import discord from discord.ext import commands @client.command() async def ping(ctx): delay = client.latency * 1000 await ctx.reply(f'Ping is {int(delay)} Milliseconds') print(f&quot;Pinged In {ctx.guild} -- {ctx.channel}&quot;) </code></pre> <p>The command is saved in a folder named &quot;commands&quot; in the same directory as main.py. How would I import the commands?</p> <p><strong>Sorry If The Question Is Hard To Understand, I Couldn't Find A Better Way To Put It</strong></p>
[ { "answer_id": 74176045, "author": "Oluwafemi Sule", "author_id": 5189811, "author_profile": "https://Stackoverflow.com/users/5189811", "pm_score": -1, "selected": false, "text": "import discord\nfrom discord.ext import commands\n\n@commands.command()\nasync def ping(ctx):\n delay = c...
2022/10/23
[ "https://Stackoverflow.com/questions/74175412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20303051/" ]
74,175,424
<p>When I run the spacy lemmatizer, it does not lemmatize the word &quot;consulting&quot; and therefore I suspect it is failing.</p> <p>Here is my code:</p> <pre><code>nlp = spacy.load('en_core_web_trf', disable=['parser', 'ner']) lemmatizer = nlp.get_pipe('lemmatizer') doc = nlp('consulting') print([token.lemma_ for token in doc]) </code></pre> <p>And my output:</p> <pre><code>['consulting'] </code></pre>
[ { "answer_id": 74176045, "author": "Oluwafemi Sule", "author_id": 5189811, "author_profile": "https://Stackoverflow.com/users/5189811", "pm_score": -1, "selected": false, "text": "import discord\nfrom discord.ext import commands\n\n@commands.command()\nasync def ping(ctx):\n delay = c...
2022/10/23
[ "https://Stackoverflow.com/questions/74175424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14948754/" ]
74,175,432
<p>I have a React App(v18.2.0) with react-router-dom(v5.2.0). The navigation works correctly but when I click the browser's Back button the URL changes but no state is updated and the page doesn't get re-rendered. I tried so many different things and none of them works.</p> <p>A case for example, is when I call the CreateUserComponent on the ListUserComponent, then if i want to go backwards using the browser back button the URL changes to the List component but the screen keeps the same.</p> <p>So my question is how can I get the page to load when the user goes back, because i do not know what i am doing wrong?</p> <p>App.js</p> <pre><code>import React from 'react'; import './App.css'; import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'; import ListUserComponent from './components/ListUserComponent'; import HeaderComponent from './components/HeaderComponent'; import FooterComponent from './components/FooterComponent'; import CreateUserComponent from './components/CreateUserComponent'; import UpdateUserComponent from './components/UpdateUserComponent'; import ViewUserComponent from './components/ViewUserComponent'; function App() { return ( &lt;div&gt; &lt;Router forceRefresh={true}&gt; &lt;HeaderComponent /&gt; &lt;div className=&quot;container&quot;&gt; &lt;Switch&gt; &lt;Route path = &quot;/&quot; exact component = {ListUserComponent}&gt;&lt;/Route&gt; &lt;Route path = &quot;/users&quot; component = {ListUserComponent}&gt;&lt;/Route&gt; &lt;Route path = &quot;/add-user/:id&quot; component = {CreateUserComponent}&gt;&lt;/Route&gt; &lt;Route path = &quot;/view-user/:id&quot; component = {ViewUserComponent}&gt;&lt;/Route&gt; &lt;/Switch&gt; &lt;/div&gt; &lt;FooterComponent /&gt; &lt;/Router&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>CreateUserComponent.jsx</p> <pre><code>import React, { Component } from 'react'; import UserService from '../services/UserService'; class CreateUserComponent extends Component { constructor(props) { super(props) this.state = { //Step 2 id: this.props.match.params.id, firstName: '', lastName: '', email: '', password: '' } this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this); this.changeLastNameHandler = this.changeLastNameHandler.bind(this); this.saveOrUpdateUser = this.saveOrUpdateUser.bind(this); } //Step 3 componentDidMount() { //Step 4 if (this.state.id === 'add') { return } else { UserService.getUserById(this.state.id).then((res) =&gt; { let user = res.data; this.setState({ firstName: user.firstName, lastName: user.lastName, emailId: user.emailId }); }); } } saveOrUpdateUser = (e) =&gt; { e.preventDefault(); let user = { firstName: this.state.firstName, lastName: this.state.lastName, email: this.state.email, password: this.state.password }; console.log('user =&gt; ' + JSON.stringify(user)); //Step 5 if (this.state.id === 'add') { UserService.createUser(user).then(res =&gt; { this.props.history.push('/users'); }); } else { UserService.updateUser(user, this.state.id).then(res =&gt; { this.props.history.push('/users'); }); } } changeFirstNameHandler = (event) =&gt; { this.setState({ firstName: event.target.value }); } changeLastNameHandler = (event) =&gt; { this.setState({ lastName: event.target.value }); } changeEmailHandler = (event) =&gt; { this.setState({ email: event.target.value }); } changePasswordHandler = (event) =&gt; { this.setState({ password: event.target.value }); } cancel() { this.props.history.push('/users'); } getTitle() { if (this.state.id === 'add') { return &lt;h3 className=&quot;text-center&quot;&gt;Modificar Usuario&lt;/h3&gt; } else { return &lt;h3 className=&quot;text-center&quot;&gt;Añadir Usuario&lt;/h3&gt; } } render() { return ( &lt;div&gt; &lt;div className=&quot;container&quot;&gt; &lt;div className=&quot;row&quot;&gt; &lt;div className=&quot;card col-md-6 offset-md-3 offset-md-3&quot;&gt; { this.getTitle() } &lt;div className=&quot;card-body&quot;&gt; &lt;form&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label&gt;Nombre: &lt;/label&gt; &lt;input placeholder=&quot;Nombre&quot; name=&quot;firstName&quot; className=&quot;form-control&quot; value={this.state.firstName} onChange={this.changeFirstNameHandler} /&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label&gt; Apellidos: &lt;/label&gt; &lt;input placeholder=&quot;Apellidos&quot; name=&quot;lastName&quot; className=&quot;form-control&quot; value={this.state.lastName} onChange={this.changeLastNameHandler} /&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label&gt; Email: &lt;/label&gt; &lt;input placeholder=&quot;Email&quot; name=&quot;email&quot; className=&quot;form-control&quot; value={this.state.email} onChange={this.changeEmailHandler} /&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label&gt; Contraseña: &lt;/label&gt; &lt;input placeholder=&quot;Contraseña&quot; name=&quot;password&quot; className=&quot;form-control&quot; value={this.state.password} onChange={this.changePasswordHandler} /&gt; &lt;/div&gt; &lt;button className=&quot;btn btn-success&quot; onClick={this.saveOrUpdateUser}&gt;Guardar&lt;/button&gt; &lt;button className=&quot;btn btn-danger&quot; onClick={this.cancel.bind(this)} style={{ marginLeft: &quot;10px&quot; }}&gt;Cancelar&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } } export default CreateUserComponent; </code></pre> <p>package.json</p> <pre><code>{ &quot;name&quot;: &quot;frontend&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;, &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;axios&quot;: &quot;^1.1.3&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot;, &quot;react-router-dom&quot;: &quot;^5.2.0&quot;, &quot;react-scripts&quot;: &quot;5.0.1&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] } } </code></pre>
[ { "answer_id": 74176045, "author": "Oluwafemi Sule", "author_id": 5189811, "author_profile": "https://Stackoverflow.com/users/5189811", "pm_score": -1, "selected": false, "text": "import discord\nfrom discord.ext import commands\n\n@commands.command()\nasync def ping(ctx):\n delay = c...
2022/10/23
[ "https://Stackoverflow.com/questions/74175432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317617/" ]
74,175,461
<p>Please help me. The website works fine in the local host, but it is having error in the C panel. How to solve? the path is: app/config/app.php</p> <p><a href="https://i.stack.imgur.com/UhgWO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UhgWO.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74176045, "author": "Oluwafemi Sule", "author_id": 5189811, "author_profile": "https://Stackoverflow.com/users/5189811", "pm_score": -1, "selected": false, "text": "import discord\nfrom discord.ext import commands\n\n@commands.command()\nasync def ping(ctx):\n delay = c...
2022/10/23
[ "https://Stackoverflow.com/questions/74175461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317626/" ]
74,175,476
<p>I want to develop an authentication mechanism for 3rd party applications using keycloak initial access tokens. But I want to do this <strong>only by using the access tokens</strong> that I have generated in the keycloak. For example, I will give a generated token to the user and allow him to log into the application. Is this possible? How can i do that? <a href="https://i.stack.imgur.com/MvSX8.png" rel="nofollow noreferrer">Initial Access Token</a></p>
[ { "answer_id": 74190213, "author": "DevMesh", "author_id": 3082137, "author_profile": "https://Stackoverflow.com/users/3082137", "pm_score": -1, "selected": false, "text": " <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter...
2022/10/23
[ "https://Stackoverflow.com/questions/74175476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12573630/" ]
74,175,479
<p>I have a table that looks like this: TableA</p> <pre><code> id| origin1 | origin2 | col4 .... 1 | a | a | 434 2 | c | b | 439 3 | d | d | 8734 </code></pre> <p>I want to get all the unique values between col b and col c, I used union for this:</p> <pre><code>SELECT * FROM ( SELECT origin1 as url, 'home' as source FROM TableA UNION SELECT origin2 as url, 'home2' FROM TableA ) AS data </code></pre> <p>I need to get the id per each row, in order to join the results to several tables including table a -</p> <pre><code>select id_1 as id, url, col 4,.... FROM ( SELECT origin1 as url, 'home' as source, id as id_1 FROM TableA UNION SELECT origin2 as url, 'home2', id FROM TableA ) AS data left join TableA on id_1 = TableA.id </code></pre> <p>expected results:</p> <pre><code> id| url | col4 .... 1 | a | 434 2 | c | 439 2 | b | 439 3 | d | 8734 </code></pre> <p>Actual results - too many rows are added by the id.</p> <p>is it possible to add the id for each row without duplication?</p>
[ { "answer_id": 74190213, "author": "DevMesh", "author_id": 3082137, "author_profile": "https://Stackoverflow.com/users/3082137", "pm_score": -1, "selected": false, "text": " <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter...
2022/10/23
[ "https://Stackoverflow.com/questions/74175479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4370694/" ]
74,175,480
<p>The cookie url_user is not stored, why?</p> <p>This is the index.html:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;script defer src=&quot;objectosPredef.js&quot; pe=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; rel=&quot;noopener&quot; target=&quot;_blank&quot; href=&quot;mystyles.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;button class=&quot;btn btn-danger&quot; onclick=&quot;SetCoockie()&quot;&gt;ESTABLECE COOCKIE&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This is the javascript &quot;objectosPredef.js&quot;:</p> <pre><code>function SetCoockie() { document.cookie = &quot;url_usuario = myname&quot;; } </code></pre> <p><a href="https://i.stack.imgur.com/TZluD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TZluD.png" alt="enter image description here" /></a></p> <p>Could you please help me?</p>
[ { "answer_id": 74175546, "author": "Nogare", "author_id": 5476122, "author_profile": "https://Stackoverflow.com/users/5476122", "pm_score": 2, "selected": false, "text": "file://" }, { "answer_id": 74175575, "author": "Mustafa Reda", "author_id": 13395150, "author_pro...
2022/10/23
[ "https://Stackoverflow.com/questions/74175480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6812738/" ]
74,175,493
<p>Snowflake csv upload turned the date format into &quot;0022-10-02&quot;. Is there a best way to change the &quot;0022&quot; format to &quot;2022&quot; format as <code>NEW_DATE</code> shows?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ORDER_DATE</th> <th>NEW_DATE</th> </tr> </thead> <tbody> <tr> <td>0022-10-02</td> <td>2022-10-02</td> </tr> <tr> <td>0022-10-02</td> <td>2022-10-03</td> </tr> </tbody> </table> </div> <p>I've tried:</p> <pre><code>df[&quot;ORDER_DATE&quot;] = pd.to_datetime(df[&quot;ORDER_DATE&quot;], format='%YYYY%mm%dd', errors='ignore') def swap(x): return re.sub(&quot;^00&quot;, &quot;20&quot;, x) if type(x) is str else x df.applymap(swap) print(df) </code></pre> <p>This still shows &quot;0022&quot; in the <code>ORDER_DATE</code> column.</p> <p>I've also tried:</p> <pre><code>df[&quot;ORDER_DATE&quot;] = pd.DataFrame({&quot;ORDER_DATE&quot;: [&quot;10-02-22&quot;, &quot;10-02-22&quot;] }) df.apply(lambda x:x.replace(&quot;^00&quot;, &quot;20&quot;, regex=True)) print(df) </code></pre> <p>Output changes the dates in the <code>ORDER_DATE</code> column but it's not ideal, because I'd like to be able to automate the date conversion process from Snowflake.</p>
[ { "answer_id": 74175546, "author": "Nogare", "author_id": 5476122, "author_profile": "https://Stackoverflow.com/users/5476122", "pm_score": 2, "selected": false, "text": "file://" }, { "answer_id": 74175575, "author": "Mustafa Reda", "author_id": 13395150, "author_pro...
2022/10/23
[ "https://Stackoverflow.com/questions/74175493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20315495/" ]
74,175,512
<p>My value from json : &quot;[[2.1,2.2],[1.0,2.5]]&quot;. How to convert this string to List&lt;List&gt; ?</p>
[ { "answer_id": 74175579, "author": "Richard Heap", "author_id": 9597706, "author_profile": "https://Stackoverflow.com/users/9597706", "pm_score": 0, "selected": false, "text": "List<dynamic>" }, { "answer_id": 74180674, "author": "shuvo", "author_id": 1417879, "author...
2022/10/23
[ "https://Stackoverflow.com/questions/74175512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7362630/" ]
74,175,514
<p>I have a timer bar showing the remaining time of a contest. As the user answers more questions of the event, scrolling down, I want the timer to be fixed in its position. I know this can be achieved by setting the CSS <code>position</code> to <code>fixed</code>.</p> <p>But <code>fixed</code> needs either a <code>width</code> set for the element, or <code>left</code> and <code>right</code> values. My problem is that the layout of the page is boxed, with margins at the left and right of the &quot;box&quot;, and it depends on the user's viewport, how much width there is for the box in the middle...</p> <p>How can I calculate the width once the page loads and then set that width to the timer bar in order for <code>fixed</code> property to get the data it needs?</p> <p>I tried setting it to 100%, but for <code>position: fixed</code> 100% means 100% of the viewport, not of the parent element, so the bar grows from the right, outside of the viewport (if you can get what I mean), since there are margins on the left and right of the boxed layout...</p>
[ { "answer_id": 74175581, "author": "Monica", "author_id": 20317707, "author_profile": "https://Stackoverflow.com/users/20317707", "pm_score": 0, "selected": false, "text": "width: 50vw;" }, { "answer_id": 74175593, "author": "Leland", "author_id": 3072442, "author_pro...
2022/10/23
[ "https://Stackoverflow.com/questions/74175514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15576971/" ]
74,175,542
<p>I'm trying to create a unique pointer to a <code>&lt;Node&gt;</code> type variable:</p> <pre><code>#include &lt;memory&gt; struct Node { int val; std::unique_ptr&lt;Node&gt; next; Node(int value, std::unique_ptr&lt;Node&gt; nextNode) : val(value), next(std::move(nextNode)){}; } int main() { Node headNode = Node(1, nullptr); std::unique_ptr&lt;Node&gt; head = std::make_unique&lt;Node&gt;(headNode); return 0; } </code></pre> <p>And when I'm compiling this code I'm getting the following error:</p> <pre><code>error: call to implicitly-deleted copy constructor of 'Node' return unique_ptr&lt;_Tp&gt;(new _Tp(_VSTD::forward&lt;_Args&gt;(__args)...)); ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ note: in instantiation of function template specialization 'std::make_unique&lt;Node, Node &amp;&gt;' requested here std::unique_ptr&lt;Node&gt; head = std::make_unique&lt;Node&gt;(headNode); ^ note: copy constructor of 'Node' is implicitly deleted because field 'next' has a deleted copy constructor std::unique_ptr&lt;Node&gt; next; ^ note: copy constructor is implicitly deleted because 'unique_ptr&lt;Node&gt;' has a user-declared move constructor unique_ptr(unique_ptr&amp;&amp; __u) _NOEXCEPT </code></pre>
[ { "answer_id": 74175569, "author": "Sam Varshavchik", "author_id": 3943312, "author_profile": "https://Stackoverflow.com/users/3943312", "pm_score": 4, "selected": true, "text": "std::make_unique<Node>(headNode);\n" }, { "answer_id": 74175596, "author": "b442", "author_id...
2022/10/23
[ "https://Stackoverflow.com/questions/74175542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12282570/" ]
74,175,563
<p>I am trying to make a column with time duration (hours - first one would be 1.424 hrs for example). My data looks like this.</p> <p><a href="https://i.stack.imgur.com/zqzK8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zqzK8.png" alt="enter image description here" /></a></p> <p>Clock_Start and Clock_Stop are objects.</p> <p><a href="https://i.stack.imgur.com/uFQyI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uFQyI.png" alt="enter image description here" /></a></p> <p>I have tried the following:</p> <pre><code>df['Duration'] = (df_nyc['Clock_Stop'] - df['Clock_Start']).astype('timedelta64[m]').astype(int) </code></pre> <p>... But I get the following error:</p> <blockquote> <p>TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'</p> </blockquote> <p>Can anybody tell me what I am doing wrong here? Any help would be greatly appreciated :)</p>
[ { "answer_id": 74175569, "author": "Sam Varshavchik", "author_id": 3943312, "author_profile": "https://Stackoverflow.com/users/3943312", "pm_score": 4, "selected": true, "text": "std::make_unique<Node>(headNode);\n" }, { "answer_id": 74175596, "author": "b442", "author_id...
2022/10/23
[ "https://Stackoverflow.com/questions/74175563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9092167/" ]
74,175,564
<p>I have a flutter app targeting Android. I want to change the default font for the app but nothing seems to work.</p> <p>I have added the <code>google_fonts</code> package. I have then modified <code>theme</code> in <code>main.dart</code> <code>MaterialApp</code> as follows:</p> <pre><code> MaterialApp( theme: ThemeData( textTheme: GoogleFonts.latoTextTheme( Theme.of(context).textTheme, ), ), darkTheme: ThemeData.dark(), themeMode: ThemeMode.dark, ), </code></pre> <p>This doesn't work. The font does not change.</p> <p>I can change individual text widget font using the below syntax and that does work:</p> <pre><code> Text('Some Text', style: GoogleFonts.robotoMono(), ), </code></pre> <p>I have also tried downloading a font and adding it to font assets:</p> <pre><code>fonts: - family: Noto fonts: - asset: fonts/NotoSans-Regular.ttf </code></pre> <p>Next, I referred to it in <code>main.dart</code>, but that does not work either:</p> <pre><code> theme: ThemeData( fontFamily: 'Noto', ), </code></pre> <p>Using the below code returns <code>monospace</code>. Not sure what that is, I thought the default font should be Roboto.</p> <pre><code>print('font: ${DefaultTextStyle.of(context).style.fontFamily}'); </code></pre> <p>I have tried to run <code>flutter clean</code>, to uninstall the app, but none of this helps.</p> <p>How can I go about troubleshooting this?</p> <p><strong>UPDATE</strong></p> <p>Found the problem. I was confused about the dark and light themes</p>
[ { "answer_id": 74175654, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "void main() {\nWidgetsFlutterBinding.ensureInitialized(); // add this before runApp\nrunApp(MyApp());\n }\n" }, ...
2022/10/23
[ "https://Stackoverflow.com/questions/74175564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7123641/" ]
74,175,583
<p>The Office Addin for Excel provides the method:</p> <pre><code>OfficeRuntime.auth.getAccessToken(OfficeRuneTime.authOptions) </code></pre> <p>to call the Azure Active Directory, log in the user and gain access to the users profile. The method brings up a dialog box asking the users consent for the <em>Office App</em> to access their profile. The consent box also includes the grants to my Web App (Angular web site that runs in the Excel Taskpane) and includes the words <em>&quot;If you accept, will also have access to your user profile information&quot;</em></p> <p>All good. But my Web App communicates with my API, which requires an additional granting of consent for my API to access the users profile.</p> <p><strong>Is there any way to cause the dialog box invoked by 'getAcccessToken' to also grant permission to my API?</strong></p> <p>When I login using MSAL as a fallback method (not getAccessToken(), but using an excel dialog box with MSAL configured as per the various Microsoft Walkthoughts), the consent box DOES include both my WebApp and my WebAPI. And authentication works correctly.</p> <p>I note that the Manifest file has a tag. I had hoped that adding the Scope to my API in here would cause the Office-Addin to request consent to it, but no banana, it does nothing.</p> <p>Any Ideas?</p> <p>I do note that getAccessToken() deliberately does not return an access token to MS Graph, with the Microsoft Documentation citing 'security concerns', and such access to Graph must be via Server Side Code using the On-Behalf-Of flow, perhaps similar reasoning does not permit me to gain consent to any API using getAccessToken(), but what then are these section in the manifest file for? I have really struggled to get SSO working with Office Addins, there are so many nuances and unexpected behaviours.</p>
[ { "answer_id": 74175654, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "void main() {\nWidgetsFlutterBinding.ensureInitialized(); // add this before runApp\nrunApp(MyApp());\n }\n" }, ...
2022/10/23
[ "https://Stackoverflow.com/questions/74175583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6630192/" ]
74,175,616
<p>I am new to flutter and I want to add shadow to an image in Card (shadow just to an image not the text), how can I do that? Below is the snippet of my code, please let me know how can I do that, thank you.</p> <pre><code>child: Container( height: 70, child: Card( child: ListTile( onTap: () {}, title: Text(eventList[index].event_name), leading: CircleAvatar( backgroundImage: NetworkImage(eventList[index].imageURL), ), ), ), ), </code></pre>
[ { "answer_id": 74175654, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "void main() {\nWidgetsFlutterBinding.ensureInitialized(); // add this before runApp\nrunApp(MyApp());\n }\n" }, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74175616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19410964/" ]
74,175,641
<p>In the example below, classes <code>AA</code> and <code>BB</code> are instantiated with params <code>a</code> and <code>b</code> and feature the <code>foo</code> method. The only difference between classes <code>AA</code> and <code>BB</code> is that in the <code>AA</code> <code>foo</code> method, the intermediate variable <code>z</code> is prefixed with the class instance reference <code>self</code> while in class <code>BB</code> it is not. What is the correct methodology here? When should <code>self</code> be used within class methods and when should it not be used? I've always been confused by this!</p> <pre><code>class AA: def __init__(self, a, b): self.a = a self.b = b def foo(self): self.z = self.a + self.b return self.z * self.a class BB: def __init__(self, a, b): self.a = a self.b = b def foo(self): z = self.a + self.b return z * self.a </code></pre>
[ { "answer_id": 74175677, "author": "HichamDz38", "author_id": 3502460, "author_profile": "https://Stackoverflow.com/users/3502460", "pm_score": -1, "selected": false, "text": "class AA:\ndef __init__(self, a, b):\n self.a = a\n self.b = b\n\ndef foo(self):\n self.z = self.a + se...
2022/10/24
[ "https://Stackoverflow.com/questions/74175641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238328/" ]
74,175,643
<p>I'm making a turn-based grid-based game with a top-down perspective. Enemies move when the player moves, like a traditional roguelike.</p> <p>Each character in the game (including the hero and enemies) has a futurePosition attribute that determines where they're supposed to move next. When the player presses a direction key, the hero's futurePosition is set to the direction indicated by the key, then every enemies' futurePosition is updated as well. The code in the Update() function of those characters looks like this :</p> <pre><code>public virtual void Update() { if (MustMoveObject()) { transform.position = Vector3.MoveTowards(transform.position, futurePosition, inverseMoveTime * Time.deltaTime); } else if (attacking) { Attack(); futurePosition = Vector3Int.RoundToInt(futurePosition); } } </code></pre> <p>Note: MustMoveObject() returns true if futurePosition and transform.position are not equal</p> <p>If the game detects there's an enemy in the direction the player is going towards, it will attack it instead. The code looks like this:</p> <pre><code>MovingObject enemyToAttack = GameManager.instance.CheckForCreatureCurrentPosition(pos); if (enemyToAttack != null) { target = enemyToAttack; cameraFollow=false; attacking=true; animator.SetTrigger(&quot;attack&quot;); futurePosition = Vector3.Lerp(transform.position, pos, 0.2f); } else { target=null; cameraFollow=true; futurePosition = pos; } </code></pre> <p>As you can see in the code above, when attacking an enemy, the futurePosition attribute is set at about one fifth (or 20%) of the distance between the hero and the enemy, and &quot;attacking&quot; is set to true. When the player reaches that point in the Update() function, it attacks the enemy and then goes back to its original position. I hope this is clear so far.</p> <p>Here's my problem : I recently added a test animation for the hero when it attacks, but the animation doesn't start when it should at <code>animator.SetTrigger(&quot;attack&quot;);</code>. It only activates after the movements of both the hero and the enemies is over. I know that this is the problem because if I replace the line <code>transform.position = Vector3.MoveTowards(transform.position, futurePosition, inverseMoveTime * Time.deltaTime);</code> with <code>transform.position = futurePosition;</code>, it makes the deplacement immediate and the animation triggers instantly. I want the animation to occur while the object is moving towards futurePosition.</p> <p>Here's what the transition looks like in the inspector (I start from AnyState instead of IdleRight because I just wanted to test things out) :</p> <p><a href="https://i.stack.imgur.com/ePDaL.png" rel="nofollow noreferrer">Screenshot</a></p> <p>As you can see, there's no exit time. There's also no delay in the animation itself, I've checked. Everything else is working as expected.</p> <p>I'm also using Unity version 2019.4.37f1, I'm not sure whether that's relevant.</p> <p>I hope I made my problem clear and that someone has an idea of what to do. I've searched for a solution, but it didn't seem like anyone had the same issue. If anything, it seemed most people had the opposite problem, where the object wouldn't move as long as the animation was active... Thanks in advance for your help.</p>
[ { "answer_id": 74175677, "author": "HichamDz38", "author_id": 3502460, "author_profile": "https://Stackoverflow.com/users/3502460", "pm_score": -1, "selected": false, "text": "class AA:\ndef __init__(self, a, b):\n self.a = a\n self.b = b\n\ndef foo(self):\n self.z = self.a + se...
2022/10/24
[ "https://Stackoverflow.com/questions/74175643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317788/" ]
74,175,648
<p>I am trying to create a new column in a data frame based on dates and date ranges. I am a beginner, and have tried several of the answers here but I cannot get them to work. Here is my original code:</p> <pre><code> df_accident[&quot;bank_holidays_2010&quot;] = df_accident[&quot;date&quot;].map( {'Easter': [d.strftime('%d/%m/%Y') for d in pd.date_range('02/04/2010', periods=4)], 'Mayday': [d.strftime('%d/%m/%Y') for d in pd.date_range('03/05/2010', periods=1)], 'Spring Bank Holiday': [d.strftime('%d/%m/%Y') for d in pd.date_range('31/05/2010', periods=1)], 'Summer Bank Holiday': [d.strftime('%d/%m/%Y') for d in pd.date_range('30/08/2010', periods=1)], 'Christmas and New Year': [d.strftime('%d/%m/%Y') for d in pd.date_range('25/12/2010', periods=9)] } ) </code></pre> <p>and repeated for other years. I get an error:</p> <pre><code>None of [Index(['Easter', 'Mayday', 'Spring Bank Holiday', 'Summer Bank Holiday',\n 'Christmas and New Year'],\n dtype='object')] are in the [columns]&quot; </code></pre> <p>I have tried:</p> <pre><code>hols = {'Easter': [d.strftime('%d/%m/%Y') for d in pd.date_range('02/04/2010', periods=4)], 'Mayday': [d.strftime('%d/%m/%Y') for d in pd.date_range('03/05/2010', periods=1)], 'Spring Bank Holiday': [d.strftime('%d/%m/%Y') for d in pd.date_range('31/05/2010', periods=1)], 'Summer Bank Holiday': [d.strftime('%d/%m/%Y') for d in pd.date_range('30/08/2010', periods=1)], 'Christmas and New Year': [d.strftime('%d/%m/%Y') for d in pd.date_range('25/12/2010', periods=9)] } </code></pre> <p>and:</p> <pre><code>bank_holidays_2010 = {'Easter': ('02/04/2010', '03/04/2010', '05/04/2010', '06/04/2010'), 'Mayday': ('03/05/2010'), 'Spring Bank Holiday': ('31/05/2010'), 'Summer Bank Holiday': ('30/08/2010'), 'Christmas and New Year': ('25/12/2010', '26/12/2010', '27/12/2010', '28/12/2010', '29/12/2010', '30/12/2010', '31/12/2010', '01/01/2011', '02/01/2011') } </code></pre> <p>Returns same error.</p> <p>What I would like to achieve is values for the dates and date ranges:</p> <pre><code>df_accident['bank_holidays_2010'].value_counts() Easter 466921 Mayday 301039 Spring Bank Holiday 132195 Christmas and New Year 92931 </code></pre>
[ { "answer_id": 74175677, "author": "HichamDz38", "author_id": 3502460, "author_profile": "https://Stackoverflow.com/users/3502460", "pm_score": -1, "selected": false, "text": "class AA:\ndef __init__(self, a, b):\n self.a = a\n self.b = b\n\ndef foo(self):\n self.z = self.a + se...
2022/10/24
[ "https://Stackoverflow.com/questions/74175648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19477097/" ]
74,175,660
<p>I've been looking at some of the answers on this forum but nothing seems to work.</p> <p>My main HTML file refers to the style sheet as follows:</p> <pre><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;/styles/main.css&quot;&gt; </code></pre> <p>I have an index.js file with the following code:</p> <pre><code>const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) =&gt; { res.sendFile('index.html', {root: __dirname}); }); app.listen(port, () =&gt; { console.log(`Now listening on port ${port}`); }); </code></pre> <p>Finally, this is my folder structure:</p> <p><a href="https://i.stack.imgur.com/Rz7BY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rz7BY.png" alt="folder structure screenshot" /></a></p> <p>I'd really appreciate some guidance on this</p>
[ { "answer_id": 74175696, "author": "mythosil", "author_id": 3808025, "author_profile": "https://Stackoverflow.com/users/3808025", "pm_score": -1, "selected": false, "text": "express.static" }, { "answer_id": 74176408, "author": "alvivanco", "author_id": 20317807, "aut...
2022/10/24
[ "https://Stackoverflow.com/questions/74175660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317807/" ]
74,175,664
<p>Sorry if the title is a bit confusing, I wasn't sure how to word it in a couple of words.</p> <p>I'm currently dealing with a situation where the user uploads a .csv or excel file, and the data must be mapped properly to prepare for a batch upload. It will make more sense as you read the code below!</p> <p>First step: The user uploads the .csv/excel file, it's transformed into an array of objects. Generally the first array will be the headers.</p> <p>The data will look like the below(including headers). This will be anywhere between 100 items to up to ~100,000 items:</p> <pre><code>const DUMMY_DATA = [ ['First Name', 'Last Name', 'company', 'email', 'phone', 'Address', 'City', 'State', 'Zip Code'], ['Lambert', 'Beckhouse', 'StackOverflow', 'lbeckhouse0@stackoverflow.com', '512-555-1738', '316 Arapahoe Way', 'Austin', 'TX', '78721'], ['Maryanna', 'Vassman', 'CDBABY', 'mvassman1@cdbaby.com', '479-204-8976', '1126 Troy Way', 'Fort Smith', 'AR', '72916'] ] </code></pre> <p>Once this is uploaded, the user will map out each field to the proper schema. This could either be all of the fields or only a select few.</p> <p>For instance the user only wants to exclude the address portion except for zip code. We would get back the 'mapped fields' array, renamed to the proper schema names (i.e. First Name =&gt; firstName):</p> <pre><code>const MAPPED_FIELDS = [firstName, lastName, company, email, phone, &lt;empty&gt;, &lt;empty&gt;, &lt;empty&gt;, zipCode] </code></pre> <p>I've made it so the indexes of the mapped fields will always match the 'headers'. So any unmapped headers will have an value.</p> <p>So in this scenario we know to only upload the data (of DUMMY_DATA) with the indexes [0, 1, 2, 3, 4, 8].</p> <p>We then get to the final part where we want to upload the proper fields for all the data, so we would have the properly mapped schemas from MAPPED_FIELDS matching the mapped values from DUMMY_DATA...</p> <pre><code>const firstObjectToBeUploaded = { firstName: 'Lambert', lastName: 'BeckHouse', company: 'StackOverflow', email: 'lbeckhouse@stackoverflow.com', phone: '512-555-1738', zipCode: '78721' } try { await uploadData(firstObjectToBeUploaded) } catch (err) { console.log(err) } </code></pre> <p>All the data will be sent to an AWS lambda function written in Node.js to handle the upload / logic.</p> <p>I'm struggling a bit on how to implement this efficiently as the data can get quite large.</p>
[ { "answer_id": 74175708, "author": "Nick", "author_id": 9473764, "author_profile": "https://Stackoverflow.com/users/9473764", "pm_score": 3, "selected": true, "text": "map" }, { "answer_id": 74175822, "author": "pilchard", "author_id": 13762301, "author_profile": "htt...
2022/10/24
[ "https://Stackoverflow.com/questions/74175664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8304719/" ]
74,175,681
<p>Github public repo has <a href="https://github.com/marmayogi/TTF2PostscriptCID-Win" rel="nofollow noreferrer">release v1.0</a>.</p> <p>The following <strong>curl</strong> command downloads only 9 bytes output of 42KB.</p> <p><code>curl -O -L -J --ssl-no-revoke https://github.com/marmayogi/TTF2PostscriptCID-Win/releases/v1.0/TTF2PostscriptCID-Win-1.0.zip</code></p> <pre><code>% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9 100 9 0 0 9 0 0:00:01 --:--:-- 0:00:01 9 </code></pre> <p>Based on comments received, the response of <code>curl</code> command only with<code>L</code> flag is added up in the post:</p> <p><code>curl -L https://github.com/marmayogi/TTF2PostscriptCID-Win/releases/v1.0/TTF2PostscriptCID-Win-1.0.zip</code></p> <pre><code>curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate. </code></pre> <p><strong>Added with post based on the comments received.</strong></p> <p>My desktop was expecting <code>--ssl-no-revoke</code> along with <code>curl</code> command. This problem was resolved with flag <code>k</code>. Here is the evidence.</p> <p><code>&quot;C:\Program Files\Neovim\bin\curl.exe&quot; -o TTF2PostscriptCID-Win-1.0.zip -L https://github.com/marmayogi/TTF2PostscriptCID-Win/archive/refs/tags/v1.0.zip</code></p> <pre><code> % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a &quot;bundle&quot; of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. </code></pre> <p>Can anyone throw some light on this issue?</p> <p>Thanks in advance.</p>
[ { "answer_id": 74175733, "author": "leomeinel", "author_id": 20316343, "author_profile": "https://Stackoverflow.com/users/20316343", "pm_score": 3, "selected": true, "text": "curl -sL https://github.com/marmayogi/TTF2PostscriptCID-Win/archive/refs/tags/v1.0.zip >filename.zip \n" }, {...
2022/10/24
[ "https://Stackoverflow.com/questions/74175681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10725972/" ]
74,175,688
<p>I have this setup of a pandas dataframe (or a csv file):</p> <pre class="lang-py prettyprint-override"><code>df = { 'colA': ['aa', 'bb', 'cc', 'dd', 'ee'], 'colB': ['aa', 'bb', 'dd', 'qq', 'ee'], 'colC': ['aa', 'bb', 'cc', 'ee', 'dd'], 'colD': ['aa', 'bb', 'ee', 'cc', 'dd'] } </code></pre> <p>The goal here is to get a list/column with the set of values that appear in all the columns or in other words the entries that are common to all the columns.</p> <p>Required output:</p> <pre class="lang-py prettyprint-override"><code>col aa bb dd ee </code></pre> <p>or a output with the common value's list:</p> <pre class="lang-py prettyprint-override"><code>common_list = ['aa', 'bb', 'dd', 'ee'] </code></pre> <p>I have a silly solution (but it doesn't seem to be correct as I am not getting what I want when implemented to my dataframe)</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv('Bus Names Concat test.csv') #i/p csv file (pandas df converted into csv) df = df.stack().value_counts() core_list = df[df&gt;2].index.tolist() #defining the common list as core list print(len(core_list)) df_core = pd.DataFrame(core_list) print(df_core) </code></pre> <p>Any help/sugggestion/feedback to get the required o/p will be appreciated.</p>
[ { "answer_id": 74175733, "author": "leomeinel", "author_id": 20316343, "author_profile": "https://Stackoverflow.com/users/20316343", "pm_score": 3, "selected": true, "text": "curl -sL https://github.com/marmayogi/TTF2PostscriptCID-Win/archive/refs/tags/v1.0.zip >filename.zip \n" }, {...
2022/10/24
[ "https://Stackoverflow.com/questions/74175688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19259213/" ]
74,175,691
<p>I got two fields: First_name (e.g.John) and Surname (e.g.Doe) How do I concat these for a join to another table that's Name (e.g. John Doe). Trying contact(First_name, Surname) gives me JohnDoe.</p> <p>Thanks!</p>
[ { "answer_id": 74175728, "author": "Jaidon S", "author_id": 10147931, "author_profile": "https://Stackoverflow.com/users/10147931", "pm_score": 2, "selected": false, "text": "concat_ws(' ', First_name, Surname);" }, { "answer_id": 74176197, "author": "Simeon Pilgrim", "au...
2022/10/24
[ "https://Stackoverflow.com/questions/74175691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16643284/" ]
74,175,703
<p>Let's say I have a <code>UITextField</code>. I want to check if its <code>delegate</code> is set, and if so, check to see if a specific optional method is implemented. If it is implemented, then I need to call it, otherwise perform a fallback action. A common way to do this is:</p> <pre class="lang-swift prettyprint-override"><code>let field = // some UITextField instance if let delegate = field.delegate, delegate.responds(to: #selector(UITextFieldDelegate.textField(_:shouldChangeCharactersIn:replacementString:))) { if delegate.textField?(field, shouldChangeCharactersIn: someRange, replacementString: someString) == true { // do something here } } else { // Fallback action } </code></pre> <p>That is all working. But then I had an urge to try a different approach. Instead of using <code>responds(to:)</code> I want to assign the optional delegate method to a variable. I came up with the following which actually works:</p> <p><strong>Note:</strong> The following code requires a deployment target of iOS 15.0 to compile. If you set the target to iOS 16.0 then it doesn't compile. Not sure why.</p> <pre class="lang-swift prettyprint-override"><code>if let delegate = field.delegate, let should = delegate.textField { if should(field, field.selectedRange, title) { // do something here } } else { // Fallback action } </code></pre> <p>While this works I'm really confused why it works.</p> <ol> <li>The <code>let should = delegate.textField</code> part makes no reference to the method's parameters.</li> <li>The <code>UITextFieldDelegate</code> protocol has 4 optional methods that start with <code>textField</code>. These are: <ul> <li><code>func textField(UITextField, shouldChangeCharactersIn: NSRange, replacementString: String) -&gt; Bool</code></li> <li><code>func textField(UITextField, editMenuForCharactersIn: NSRange, suggestedActions: [UIMenuElement]) -&gt; UIMenu?</code></li> <li><code>func textField(UITextField, willDismissEditMenuWith: UIEditMenuInteractionAnimating)</code></li> <li><code>func textField(UITextField, willPresentEditMenuWith: UIEditMenuInteractionAnimating)</code></li> </ul> </li> </ol> <p>So how does this work? How does the compiler know which one I meant? It actually seems to only work with the one that happens to be first.</p> <p>I can't find any way to do this for the other 3 delegate methods. If I really want to call the <code>func textField(UITextField, editMenuForCharactersIn: NSRange, suggestedActions: [UIMenuElement]) -&gt; UIMenu?</code> method I can't see how. The following code will not compile:</p> <pre class="lang-swift prettyprint-override"><code>if let delegate = field.delegate, let editMenu = delegate.textField { let suggested = [UIMenuElement]() if let menu = editMenu(field, field.selectedRange, suggested) { } } </code></pre> <p>This gives the error:</p> <blockquote> <p>Cannot convert value of type '[UIMenuElement]' to expected argument type 'String'</p> </blockquote> <p>on the <code>if let menu = should(field, field.selectedRange, suggested) {</code> line. This clearly indicates it is assuming the <code>func textField(UITextField, shouldChangeCharactersIn: NSRange, replacementString: String) -&gt; Bool</code> method.</p> <p>Is there a syntax (that I'm missing) that allows me to assign the specific protocol method to a variable?</p> <p>I'm going to stick with the tried and true use of <code>responds(to:)</code> for now but I'd love an explanation of what's going on with the attempts to assign the ambiguously named protocol method to a variable and if there is a way to specify the parameters to get the correct assignment.</p> <p>My searching on SO didn't yield any relevant questions/answers.</p> <p>My code is in an iOS project with a deployment target of iOS 15.0 and later using Xcode 14.0.1. The Swift compiler setting is set for Swift 5. It seems the code doesn't compile with a deployment target of iOS 16.0. Strange.</p>
[ { "answer_id": 74175775, "author": "dillon-mce", "author_id": 11601631, "author_profile": "https://Stackoverflow.com/users/11601631", "pm_score": 0, "selected": false, "text": "error: ambiguous use of 'textField'\nif let delegate = textField.delegate, let should = delegate.textField {\n\...
2022/10/24
[ "https://Stackoverflow.com/questions/74175703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20287183/" ]
74,175,731
<p>Not sure which details are relevant so I'll include as many as possible.</p> <p>Had to upgrade flutter today and instead of working when I typed in 'flutter upgrade' into android studios terminal/Iterm2/terminal zsh I was met with the following response.</p> <p>'sysctl -n hw.optional.arm64' returned unexpected output: ''</p> <p>When I search for this issue the only thing i can <a href="https://stackoverflow.com/questions/72708385/what-may-cause-error-sysctl-n-hw-optional-arm64-returned-unexpected-output">find is this post</a> which states that sysctl can't be found. The path does appear to be in my .zshrc but still not working. I can't use which or where sysctl as it just says 'sysctl not found'</p> <p>When I try to upgrade flutter through brew (brew install --cask flutter) it downloads fine but on installing it throws the following error:</p> <blockquote> <p>==&gt; Purging files for version 3.3.5 of Cask flutter Error: It seems there is already a Binary at '/opt/homebrew/bin/dart'.</p> </blockquote> <p>I can't continue working as I need the new flutter version and it seems the web doesn't have much to show for this particular error.</p> <p>I can't flutter --version, flutter doctor or anything of the sort as I just get the same message.</p> <p>I'm using:</p> <ul> <li>MacOS monterey 12.6 macbook air.</li> <li>Android studios</li> <li>Iterm2</li> <li>Ohmyzsh</li> </ul> <p>When I open android studios it shows me the following:</p> <ol> <li><p>&quot;Flutter device daemon #1 exited (exit code 1), stderr: 'sysctl -n hw.optional.arm64' returned unexpected output: '' in a pop up window.</p> </li> <li><p>Pubspec has been edited &gt; get dependencies &gt; Upgrade depenedencies: Both of which have the same error as in the title.</p> </li> <li><p>The current configured flutter SDK is not known to be fully supported. Please update your SDK and restart intelliJ which I think is what I've been trying to do.</p> </li> </ol>
[ { "answer_id": 74175775, "author": "dillon-mce", "author_id": 11601631, "author_profile": "https://Stackoverflow.com/users/11601631", "pm_score": 0, "selected": false, "text": "error: ambiguous use of 'textField'\nif let delegate = textField.delegate, let should = delegate.textField {\n\...
2022/10/24
[ "https://Stackoverflow.com/questions/74175731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8224318/" ]
74,175,745
<p>I am working on a project to let a client authorize their google ads account, and then use those authorized credentials to download data on their behalf. I have a webapp that successfully Authorizes the app to do things on the clients behalf. This generates an access code that I then trade for two credentials, an access token and a refresh token. This refresh token then gets passed to a database, where a separate app attempts to query the googleAds API. It is my understanding that the Google Oauth engine only needs the refresh token.</p> <p>I am trying to authorize by use of load_from_dict() or load_from_env() methods of the GoogleAdsClient class. Both yield the same error: <code>google.auth.exceptions.RefreshError: ('invalid_client: Unauthorized', {'error': 'invalid_client', 'error_description': 'Unauthorized'})</code></p> <p>I have verified the developer_token, client_id, and client_secret are all accurate to what is in the API console. I have also verified the refresh_token is being passed correctly to the credential dict.</p> <p>I am really at a loss on where to go from here. I have read many stack overflow threads with similar titles, and yet I am still stuck at the same place.</p> <p>Here are some relevant links.</p> <p><a href="https://developers.google.com/google-ads/api/docs/client-libs/python/configuration" rel="nofollow noreferrer">Google Ads API configuration</a></p> <p><a href="https://developers.google.com/identity/protocols/oauth2/web-server" rel="nofollow noreferrer">Google Identity and Server side web apps</a></p> <p><a href="https://github.com/googleads/google-ads-python/blob/main/examples/basic_operations/get_campaigns.py" rel="nofollow noreferrer">Google's example of an API call</a></p> <p>Relevant code</p> <pre><code>class GoogleAds: def __init__(self): self.scope = ['https://www.googleapis.com/auth/adwords'] self.client_id = os.getenv('GOOGLE_ADS_CLIENT_ID') self.client_secret = os.getenv('GOOGLE_ADS_CLIENT_SECRET') self.developer_token = os.getenv('GOOGLE_ADS_DEVELOPER_TOKEN') self.refresh_token = os.getenv('GOOGLE_ADS_REFRESH_TOKEN') def authorize(self): credentials = { &quot;developer_token&quot;: self.developer_token, &quot;refresh_token&quot;: self.refresh_token, &quot;client_id&quot;: self.client_id, &quot;client_secret&quot;: self.client_secret, &quot;use_proto_plus&quot;:&quot;True&quot;, &quot;grant_type&quot;: &quot;refresh_token&quot;, } print(credentials) googleads_client = GoogleAdsClient.load_from_dict(credentials) service = googleads_client.get_service(&quot;GoogleAdsService&quot;) request = googleads_client.get_type(&quot;SearchGoogleAdsRequest&quot;) return service, request </code></pre>
[ { "answer_id": 74175775, "author": "dillon-mce", "author_id": 11601631, "author_profile": "https://Stackoverflow.com/users/11601631", "pm_score": 0, "selected": false, "text": "error: ambiguous use of 'textField'\nif let delegate = textField.delegate, let should = delegate.textField {\n\...
2022/10/24
[ "https://Stackoverflow.com/questions/74175745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16555250/" ]
74,175,751
<p>The upsert statement below does not work and get:</p> <pre><code>MongoServerError: E11000 duplicate key error collection: db.emails index: _id_ dup key: { _id: &quot;8hh58975fw&quot; } </code></pre> <p>My goal is to edit an existing document ( or create if exists ) with the same <code>_id</code> The code in api is:</p> <pre><code>await db.collection('emails') .updateOne( { _id: userId, type: &quot;profileCompletion&quot;, time: new Date(), }, { $inc: { &quot;count&quot;: 1}, }, {upsert: true}, ) </code></pre> <p>But I coped it from this which works:</p> <pre><code>await db.collection('analytics') .updateOne( { _id: getDateMonYear(new Date(), &quot;mmddyyyy&quot;), type: &quot;Geo&quot;, }, { $inc: { &quot;count&quot;: 1}, }, {upsert: true}, ) </code></pre>
[ { "answer_id": 74176016, "author": "Kal", "author_id": 3717114, "author_profile": "https://Stackoverflow.com/users/3717114", "pm_score": 0, "selected": false, "text": "time: new Date(),\n" }, { "answer_id": 74176469, "author": "user20042973", "author_id": 20042973, "a...
2022/10/24
[ "https://Stackoverflow.com/questions/74175751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717114/" ]
74,175,767
<p><strong>Example 1</strong></p> <p>I have a code pushing one spreaded array into another:</p> <pre><code>const hobbies = ['Sports', 'Cooking']; const activeHobbies = ['Hiking']; activeHobbies.push(...hobbies); console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking'] hobbies.push('Skiing'); console.log(hobbies); //['Sports', 'Cooking', 'Skiing'] console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking'] </code></pre> <p>Is a spreaded array pushed same as <code>activeHobbies.push(hobbies[0], hobbies[1])</code> by values?</p> <p>Why is it not <code>['Hiking', 'Sports', 'Cooking', 'Skiing']</code> in the last line ?</p> <p><strong>Example 2</strong></p> <pre><code>const hobbies = ['Sports', 'Cooking']; const activeHobbies = ['Hiking']; activeHobbies.push(hobbies); console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']], why not ['Hiking', ['Sports', 'Cooking']] ? hobbies.push('Skiing'); console.log(hobbies); //['Sports', 'Cooking', 'Skiing'] console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']] </code></pre> <p>As I understand, <code>hobbies</code> array will be pushed to <code>activeHobbies</code> by reference without spreading like this <code>activeHobbies.push(hobbies)</code> and the new values will be added to <code>hobbies</code> array inside <code>activeHobbies</code> array, if new values are pushed to <code>hobbies</code> array, because it's pushed by reference. Is it correct?</p> <p>But why the first console outputs <code>['Hiking', ['Sports', 'Cooking', 'Skiing']]</code> and not <code>['Hiking', ['Sports', 'Cooking']]</code> ?</p>
[ { "answer_id": 74175820, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "activeHobbies.push(hobbies[0], hobbies[1])" }, { "answer_id": 74176485, "author": "Geremia", "author_i...
2022/10/24
[ "https://Stackoverflow.com/questions/74175767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11067821/" ]
74,175,788
<p>This is what i'm trying to do right now but I don't know if this is this correct way to do it since I started learning C recently</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main(int argc, char const *argv[]) { char** input = malloc(5 * sizeof(char*)); char buffer[10]; for (int i = 0; i &lt; 5; i++) { fgets(buffer,10,stdin); *(input+i) = buffer; printf(&quot;%s&quot;,*(input)); } for (int i = 0; i &lt; 5; i++) { printf(&quot;%s&quot;,*(input+i)); } printf(&quot;\n&quot;); return 0; } </code></pre> <p>In my head the logic seems fine but I don't know why it doesn't work</p>
[ { "answer_id": 74175820, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "activeHobbies.push(hobbies[0], hobbies[1])" }, { "answer_id": 74176485, "author": "Geremia", "author_i...
2022/10/24
[ "https://Stackoverflow.com/questions/74175788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317906/" ]
74,175,799
<p>I keep getting this error:</p> <pre class="lang-none prettyprint-override"><code> error: no match for ‘operator&gt;&gt;’ (operand types are ‘std::ifstream’ {aka ‘std::basic_ifstream&lt;char&gt;’} and ‘std::vector&lt;symbol&gt;’) 26 | myFile &gt;&gt; temp; | ~~~~~~ ^~ ~~~~ </code></pre> <pre><code>int readAlphabetFromFile(string filename, vector&lt;symbol&gt; alphabet) { ifstream myFile; myFile.open(filename); if (myFile.is_open()) { while (!myFile.eof()) { vector&lt;symbol&gt; temp; myFile &gt;&gt; temp; alphabet.push_back(temp); } return 0; } else { return -1; } } </code></pre>
[ { "answer_id": 74175820, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "activeHobbies.push(hobbies[0], hobbies[1])" }, { "answer_id": 74176485, "author": "Geremia", "author_i...
2022/10/24
[ "https://Stackoverflow.com/questions/74175799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393163/" ]
74,175,812
<p>In my View Model I have created a function that uploads audio file to Firebase Storage.Then I want to close my fragment but only if the file was already uploaded so I have to wait for coroutine to complete job. How can I achieve it? I can use <em>runBlocking</em> and it works but I don't think that's a good idea.</p> <pre><code>fun addRequest(request: Event){ scope.launch { val uri = repository.uploadAudioFile() request.audio = uri repository.addRequest(request) } } </code></pre> <p>Then in my fragment I want to call something like:</p> <pre><code> prosbyViewModel.addRequest(Event(title = title,description = description, date = date)) requireActivity().supportFragmentManager.popBackStack() </code></pre>
[ { "answer_id": 74175820, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "activeHobbies.push(hobbies[0], hobbies[1])" }, { "answer_id": 74176485, "author": "Geremia", "author_i...
2022/10/24
[ "https://Stackoverflow.com/questions/74175812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19193769/" ]
74,175,827
<p>I want the difference between tall and short images to not be as jarring as it is. Unfamiliar with coding jargon so forgive my ineptitude. Attached image describes change I want better<a href="https://i.stack.imgur.com/l360n.png" rel="nofollow noreferrer">graph of what my site currently looks like and what I want it to</a>. Images on my page are three per line, unseparated in the code, as shown below.</p> <pre><code> &lt;img src=&quot;so.jpg&quot;&gt; &lt;img src=&quot;ch.jpg&quot;&gt; &lt;img src=&quot;CC.jpg&quot;&gt; &lt;img src=&quot;blue.jpg&quot;&gt; &lt;img src=&quot;tv.jpg&quot;&gt; &lt;img src=&quot;do.jpg&quot;&gt; &lt;img src=&quot;bwire.jpg&quot;&gt; &lt;img src=&quot;nail.jpg&quot;&gt; &lt;img src=&quot;tom.jpg&quot;&gt; </code></pre>
[ { "answer_id": 74175820, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 2, "selected": false, "text": "activeHobbies.push(hobbies[0], hobbies[1])" }, { "answer_id": 74176485, "author": "Geremia", "author_i...
2022/10/24
[ "https://Stackoverflow.com/questions/74175827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19583487/" ]
74,175,849
<p>I have a list of ints,</p> <pre><code>lst = [1, 2, 3] </code></pre> <p>how do I do a <code>isinstance</code> on this, to return <code>True</code> only for a list of ints?</p> <pre><code>isinstance(lst, list[int]) # does not work </code></pre>
[ { "answer_id": 74175917, "author": "Pedro Freitas Lopes", "author_id": 14404907, "author_profile": "https://Stackoverflow.com/users/14404907", "pm_score": 2, "selected": false, "text": "lst = [1, 2, 3]\n\nresult = all(isinstance(x, int) for x in lst)\n\nprint(result)\n" }, { "ans...
2022/10/24
[ "https://Stackoverflow.com/questions/74175849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10855529/" ]
74,175,947
<p>I have a readonly array of strings and numbers. I want to have a reverse map object similar to how <a href="https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings" rel="nofollow noreferrer">reverse mapping of <code>enum</code>s</a> work. In order to do this, I need to be able to find the index of <code>T</code> within array <code>A</code>.</p> <pre class="lang-ts prettyprint-override"><code>const myArray = [1, '1+', 2, 3, '3+'] as const; type MyArrayIndexes = { [K in typeof myArray[number]]: IndexOf&lt;typeof myArray, K&gt;; }; const myArrayIndexes: MyArrayIndexes = { 1: 0, '1+': 1, 2: 2, 3: 3, '3+': 4, }; </code></pre> <p>I was having trouble figuring out the definition of <code>IndexOf&lt;A extends readonly any[], T extends A[number]&gt;</code>, but thought I'd play with it a bit longer before I asked SO. I figured it out, so I thought I'd share in case anyone else looked to do this.</p> <p>My initial implementation was something like this, though originally it was using <code>typeof myArray</code> directly rather than the template parameter <code>A</code> and included some boneheaded, uninteresting mistakes.</p> <pre class="lang-ts prettyprint-override"><code>type IndexOf&lt;A extends readonly unknown[], T extends A[number]&gt; = Extract&lt; { [K in keyof A &amp; number]: [A[K], K]; }[keyof A &amp; number], [T, number] &gt;[1]; </code></pre> <p>When I tried to instantiate <code>myArrayIndexes</code>, it was expecting every value to be <code>never</code>.</p>
[ { "answer_id": 74175917, "author": "Pedro Freitas Lopes", "author_id": 14404907, "author_profile": "https://Stackoverflow.com/users/14404907", "pm_score": 2, "selected": false, "text": "lst = [1, 2, 3]\n\nresult = all(isinstance(x, int) for x in lst)\n\nprint(result)\n" }, { "ans...
2022/10/24
[ "https://Stackoverflow.com/questions/74175947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120446/" ]
74,175,950
<p>I want to pick 2 numbers randomly in a 2D array[4][2]. My 2D array stock (x, y) and I want to randomly choose between two coordinates.</p> <p>I tried the following algorithm, but it doesn't work:</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #define DEBUG #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;math.h&gt; int nb_aleatoire(int min, int max) { return min + (int)(rand() / (RAND_MAX + 0.001) *(max - min + 1)); } int main(void) { int lab[4][2] = { { 1, 4 }, { 2, 4 }, { 3, 8 } }; int alea; int x; int y; int i, j; /*On initialise le générateur de nombres aléatoires. */ srand((unsigned int) time(NULL)); rand(); for (i = 0; i &lt; 1; i++) { printf(&quot;(%d, %d)\n&quot;, rand(lab[i][i + 1]), rand(lab[i][i + 1])); } system(&quot;pause&quot;); return EXIT_SUCCESS; } </code></pre>
[ { "answer_id": 74175996, "author": "selbie", "author_id": 104458, "author_profile": "https://Stackoverflow.com/users/104458", "pm_score": 0, "selected": false, "text": "int lab[4][2] = {\n { 1, 4 },\n { 2, 4 },\n { 3, 8 },\n};\n" }, { "answer_id": 74176002, "author":...
2022/10/24
[ "https://Stackoverflow.com/questions/74175950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318017/" ]
74,176,012
<p>I have a problem which is changing the date format from '21 Sep 2022 04:37:17' to '2022-09-21 04:37:17'. I'm using the code:</p> <pre><code>import pandas as pd fileIn = 'C:/Users/xxx.xlsx' df = pd.read_excel(fileIn, index_col=0) diaStrava = df['Data da atividade'].str[:2] mesStrava = df['Data da atividade'].str[6:9] anoStrava = df['Data da atividade'].str[13:18] if mesStrava == 'out': c_mesStrava = '10' dataStrava = diaStrava + '-' + c_mesStrava + '-' + anoStrava </code></pre> <p>And I'm getting the error:</p> <p>... Traceback (most recent call last):</p> <p>... if mesStrava == 'out': ... in <strong>nonzero</strong> raise ValueError( ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> <p>can anyone help me? Thanks</p>
[ { "answer_id": 74175996, "author": "selbie", "author_id": 104458, "author_profile": "https://Stackoverflow.com/users/104458", "pm_score": 0, "selected": false, "text": "int lab[4][2] = {\n { 1, 4 },\n { 2, 4 },\n { 3, 8 },\n};\n" }, { "answer_id": 74176002, "author":...
2022/10/24
[ "https://Stackoverflow.com/questions/74176012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7667393/" ]
74,176,036
<p>I have a database for my website that is hosted on Heroku and uses Flask and Python. The model structure looks like:</p> <pre><code>class MyDataModel(db.Model): id = db.Column(db.Integer, primary_key=True) property1 = db.Column(db.String(240), default = &quot;&quot;) property2 = db.Column(db.String(240), default = &quot;&quot;) property3 = db.Column(db.String(240), default = &quot;&quot;) </code></pre> <p>When I try to update this model to something with an additional property (property4) shown below, the website doesn't work. Is there a way to add an additional property to a model so that the model still functions properly?</p> <pre><code>class MyDataModel(db.Model): id = db.Column(db.Integer, primary_key=True) property1 = db.Column(db.String(240), default = &quot;&quot;) property2 = db.Column(db.String(240), default = &quot;&quot;) property3 = db.Column(db.String(240), default = &quot;&quot;) property4 = db.Column(db.String(240), default = &quot;&quot;) </code></pre> <p>The db is set up like:</p> <pre><code>db = SQLAlchemy() app = Flask(__name__) db.init_app(app) </code></pre>
[ { "answer_id": 74332359, "author": "Rahul K P", "author_id": 4407666, "author_profile": "https://Stackoverflow.com/users/4407666", "pm_score": 1, "selected": false, "text": "flask" } ]
2022/10/24
[ "https://Stackoverflow.com/questions/74176036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12422823/" ]
74,176,046
<p>So I have this kind of design:</p> <p><a href="https://i.stack.imgur.com/wn67L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wn67L.png" alt="My Card" /></a></p> <p>How can I achieve this in Flutter?</p>
[ { "answer_id": 74176107, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 3, "selected": false, "text": "Stack" }, { "answer_id": 74176169, "author": "KuKu", "author_id": 11986450, "author_profile": "...
2022/10/24
[ "https://Stackoverflow.com/questions/74176046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15188468/" ]
74,176,061
<pre><code>import React, { useState } from 'react' export const BreedsSelect = props =&gt; { const [selectedBreed, setSelectedBreed] = useState(null) const options = props.breeds return ( &lt;div&gt; &lt;select value={selectedBreed} onChange={e =&gt; setSelectedBreed(e.target.value)} &gt; {options?.map(breed =&gt; { ;&lt;option&gt;{breed}&lt;/option&gt; })} &lt;/select&gt; &lt;/div&gt; ) } </code></pre> <p>In the above code I get an error that options.map is not a function. How can this be resolved? The following code calls the above code.</p> <pre><code>import React, { useEffect, useState } from 'react' // DO NOT DELETE import { BreedsSelect } from './BreedsSelect' export const DogListContainer = () =&gt; { const [breeds, setBreeds] = useState(null) useEffect(() =&gt; { fetch('https://dog.ceo/api/breeds/list/all') .then(res =&gt; res.json()) .then(data =&gt; { setBreeds(data.message) }) }, []) return &lt;BreedsSelect breeds={breeds} /&gt; } </code></pre>
[ { "answer_id": 74176172, "author": "Sporadic", "author_id": 20009501, "author_profile": "https://Stackoverflow.com/users/20009501", "pm_score": 0, "selected": false, "text": "Object.keys(options).map(breed => <option>{breed}</option>)\n" }, { "answer_id": 74176313, "author": ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,176,071
<p>It seems that when I'm using the <code>import</code> statement in the <code>&lt;script setup&gt;</code> all code below it stops working.</p> <p>I installed the <a href="https://heroicons.com" rel="nofollow noreferrer">@heroicons</a> package and use the import statement to use it as a component in my <code>&lt;template&gt;</code>. But everything below the import statements does not work anymore. My code:</p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;HomeIcon class=&quot;w-5 h-5&quot;&gt; &lt;h1&gt;{{myName}}&lt;/h1&gt; &lt;/template&gt; &lt;script setup&gt; import {HomeIcon} from '@heroicons/vue/24/outline' const myName = ref('username') &lt;/script&gt; </code></pre> <p>When running the code above I do <strong>not</strong> see &quot;username&quot; as a heading as specified in my code. I also see a ESlint warning</p> <blockquote> <p>myName is declared but it's value is never read</p> </blockquote> <p>The moment I comment the <code>import</code> statement, the <code>myName</code> ref seems to work again.</p> <p>What I use:</p> <ul> <li>VS Code</li> <li>Nuxtjs 3</li> <li>Tailwind CSS</li> <li>Heroicons package</li> <li>PNPM as package manager</li> </ul>
[ { "answer_id": 74176172, "author": "Sporadic", "author_id": 20009501, "author_profile": "https://Stackoverflow.com/users/20009501", "pm_score": 0, "selected": false, "text": "Object.keys(options).map(breed => <option>{breed}</option>)\n" }, { "answer_id": 74176313, "author": ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20214647/" ]
74,176,080
<p>I am trying create an update route but whenever I try to update the content I can only update title and description &amp; markdown but not sanitized html. How Can I udpate the sanitized html while I edit. Here is my article.js model.</p> <pre class="lang-js prettyprint-override"><code>const mongoose = require('mongoose'); const marked = require('marked'); const slugify = require('slugify'); const createDomPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const dompurify = createDomPurify(new JSDOM().window); const articleSchema = new mongoose.Schema({ title: { type: String, required: true, }, description: { type: String, }, markdown: { type: String, required: true, }, createdAt: { type: Date, default: Date.now, }, slug: { type: String, required: true, unique: true, }, sanitizedHtml: { type: String, required: true, }, }); articleSchema.pre('validate', function (next) { if (this.title) { this.slug = slugify(this.title, { lower: true, strict: true }); } if (this.markdown) { this.sanitizedHtml = dompurify.sanitize(marked.parse(this.markdown)); } next(); }); module.exports = mongoose.model('Article', articleSchema); </code></pre> <p>Here is my put route :</p> <pre class="lang-js prettyprint-override"><code>router.put('/:id', async (req, res) =&gt; { const { id } = req.params; const article = Article.findById(id); const newArticle = { title: req.body.title, description: req.body.description, markdown: req.body.markdown, }; const updatedArticle = await Article.findByIdAndUpdate(id, newArticle); await updatedArticle.save(); res.redirect(`/articles/${article.slug}`); }); </code></pre>
[ { "answer_id": 74176172, "author": "Sporadic", "author_id": 20009501, "author_profile": "https://Stackoverflow.com/users/20009501", "pm_score": 0, "selected": false, "text": "Object.keys(options).map(breed => <option>{breed}</option>)\n" }, { "answer_id": 74176313, "author": ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15894598/" ]
74,176,085
<p>As summary states. Lets say I want o resolve my <em>ReturnFunction</em> in a ternary operator fashion. Well, as far as I know, as long as my function returning several values (<em>ReturnThreeValues</em>) is placed at LAST position after <em>ReturnFunction</em>'s return, the three values it gives should be returned by <em>ReturnFunction</em> if the ternary operator do what I think is the expected here, but for some reason it keeps returning <em>ReturnOneValue</em>'s value even when n == nil (because I'm not including it when calling). It can be seen &amp; tryed here:</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;script src="//github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"&gt;&lt;/script&gt; &lt;script type="application/lua"&gt; function ReturnOneValue(t, n) n = n or 1 return t[n] end function ReturnThreeValues(t) return t[1], t[2], t[3] end function ReturnFunction(t, n) return n ~= nil and ReturnOneValue(t, n) or ReturnThreeValues(t) end local t = {"One", "Two", "Three"} local r1, r2, r3 = ReturnFunction(t) print(r1, r2, r3) &lt;/script&gt;</code></pre> </div> </div> </p> <p>Well, basically I don't get why my print result is being: &quot;One nil nil&quot; and not: &quot;One Two Three&quot; as it should be, if the ternary operator was working as (I think is the) expected... Or is there something I'm not taking into account when it comes to resolve a multi-return function in this <em>ternary</em> way?</p> <p><strong>EDIT:</strong></p> <p>FTR (and just in case is useful for anyone), after doing some more research I got to find <a href="https://stackoverflow.com/a/25362653/2805176"><strong>this other question</strong></a> with a possible workaround and turns out it works, as can be seen here:</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;script src="//github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"&gt;&lt;/script&gt; &lt;script type="application/lua"&gt; function ReturnOneValue(t, n) n = n or 1 return t[n] end function ReturnThreeValues(t) return t[1], t[2], t[3] end function ReturnFunction(t, n) return n == nil and {ReturnThreeValues(t)} or {ReturnOneValue(t, n)} end local t = {"One", "Two", "Three"} local r1, r2, r3 = table.unpack(ReturnFunction(t)) print(r1, r2, r3) &lt;/script&gt;</code></pre> </div> </div> </p> <p>However, I'm not going to considerate it the right solution to the problem due to in the end it's more convoluted than what I was expecting to find, and I don't think the added complexity would worth after all... It's clear the way to go would be more in the line LMD suggests. Even though, after some consideration, I'm going to mark Nicol's answer as the right one, since he explained very well the why of such behavior and what was really happening under-the-hood, and that's what this question was actually more about. Well, thanks to everyone and I hope it makes sense.</p>
[ { "answer_id": 74176172, "author": "Sporadic", "author_id": 20009501, "author_profile": "https://Stackoverflow.com/users/20009501", "pm_score": 0, "selected": false, "text": "Object.keys(options).map(breed => <option>{breed}</option>)\n" }, { "answer_id": 74176313, "author": ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805176/" ]
74,176,087
<p>So I'm currently working on a decimal-to-binary converter and am running into a formatting issue where I can't seem to add a space every four digits. currently, it is adding the &quot;space&quot;(at the moment it's a 5) to the end of the string. any suggestions are welcome.</p> <pre><code>decimal = int(input(&quot;Enter Binary Number: &quot;)) binary = &quot;&quot; while decimal &gt; 0: remainder = decimal % 2 binary += str(remainder) decimal = int(decimal / 2) reverse = binary[::-1] counter = 0 for i in reverse: counter+=1 if counter == 4: reverse+=&quot;5&quot; counter=0 </code></pre> <p>print(&quot;The Binary Number Is: &quot;, reverse)</p>
[ { "answer_id": 74176142, "author": "CryptoFool", "author_id": 7631480, "author_profile": "https://Stackoverflow.com/users/7631480", "pm_score": 0, "selected": false, "text": "decimal = int(input(\"Enter Binary Number: \"))\nbinary = \"\"\n\nwhile decimal > 0:\n remainder = decimal % 2...
2022/10/24
[ "https://Stackoverflow.com/questions/74176087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,176,092
<p>I have a list of dataframes all have a <code>['Date']</code> column set as the index</p> <pre><code>data_frames = [df1, df2, df3, df4, df5] </code></pre> <p>I would like to merge them all on the index I found the below code but it obviously wont work in my case because it only merges 2 dataframes. Is there anyways to do it with a list in one step?</p> <pre><code>final_df = reduce(lambda left,right: pd.merge(left_index=True, right_index=True, how='inner'), data_frames) </code></pre>
[ { "answer_id": 74176108, "author": "Lowin Li", "author_id": 19560513, "author_profile": "https://Stackoverflow.com/users/19560513", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf1 = pd.DataFrame({\"Date\":[1,2]})\ndf2 = pd.DataFrame({\"Date\":[1,2,3]})\ndf3 = pd.Dat...
2022/10/24
[ "https://Stackoverflow.com/questions/74176092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3242388/" ]
74,176,115
<p>Riverpod docs say to use <code>ref.read</code> in callbacks like a button's <code>onPressed</code>, since you must not use <code>ref.watch</code> there.</p> <p>Is it OK to do something like this?</p> <pre><code>build(context, ref) { // Use ref.watch ahead of time, because I refer to p all over // the widget tree. p is a mutable ChangeNotifier final p = ref.watch(myProvider); return ElevatedButton( onPressed: () { // Refer to provider obtained via ref.watch earlier p.mutateSomehow(), }, child: /* huge tree referring to p 20 times */ ); } </code></pre> <p>? I'm doing this all over my code and it seems to work fine, but if this pattern were OK it seems like Riverpod would just recommend it and deprecate <code>ref.read</code>.</p>
[ { "answer_id": 74176166, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 0, "selected": false, "text": "ref.read" }, { "answer_id": 74176610, "author": "john", "author_id": 16146701, "author_profile"...
2022/10/24
[ "https://Stackoverflow.com/questions/74176115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4105/" ]
74,176,134
<p>I need a way to do the following:</p> <ul> <li>I want to be able to loop through each column in a data-frame that is of the <code>dtype == object</code></li> <li>As I am looping through each desired column, I am obtaining the following summary statistics: <ul> <li>The name of the attribute</li> <li>The number of unique values each attribute has</li> <li>The most frequently occurring value of each attribute</li> <li>The number of occurrences of the most frequently occurring value</li> <li>The percentage of the total number of values the most frequently occurring value contributes</li> </ul> </li> </ul> <p>Say I have the following data:</p> <pre><code>import pandas as pd data = {&quot;Sex&quot;:[&quot;M&quot;, &quot;M&quot;, &quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;M&quot;, &quot;F&quot;, &quot;F&quot;, &quot;M&quot;], &quot;Product&quot;: [&quot;X&quot;, &quot;Y&quot;, &quot;Y&quot;, &quot;Z&quot;,&quot;Y&quot;, &quot;Y&quot;, &quot;Y&quot;, &quot;X&quot;, &quot;Z&quot;, &quot;Y&quot;], &quot;Answer&quot;:[&quot;Yes&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;No&quot;, &quot;No&quot;, &quot;Yes&quot;, &quot;Yes&quot;, &quot;No&quot;, &quot;Yes&quot;, &quot;Yes&quot;], &quot;Numeric&quot;:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], &quot;Binary&quot;:[True, True, False, False, False, True, False, True, True, False]} df = pd.DataFrame(data) </code></pre> <p>I need some way to do the following (I know the code isn't correct - hopefully my pseudo-code conveys what I mean)</p> <pre><code>for column in df: if df[column].dtype != object: continue else: #pseudo-code begins attributes = df[column].name #attribute names unique_values = df[column].unique() #number of unique values most_frequent = df[column].mode() #most frequently occurring occurrences = df[column][most_frequent].nunique() #occurrences of the mode proportions = df[column][most_frequent].value_counts(normalize = True) #to get #proportions </code></pre> <p>I then need some way to tabulate all this information into some kind of summary statistics table</p> <pre><code>summaryStats = tabluate([attributes, unique_values, most_frequent, occrrences, proportions]) </code></pre> <p>The resulting output should look something like this</p> <pre><code>| Attribute | Unique Values | Mode | Occurrences | % of Total | |----------- --------------- ------ ------------- ------------| | Sex F, M, F 6 60% | | Product X, Y, Z Y 7 70% | | ... ... ... ... ... | #...and so on and so forth for the other attributes </code></pre> <p>I am essentially creating a summary table for discrete data.</p> <p>Any help at all would be much appreciated :)</p>
[ { "answer_id": 74181773, "author": "Code Different", "author_id": 2538939, "author_profile": "https://Stackoverflow.com/users/2538939", "pm_score": 1, "selected": false, "text": "data = []\n\n# Loop through columns of dtype `object`\nfor col in df.select_dtypes(\"object\"):\n # Do a c...
2022/10/24
[ "https://Stackoverflow.com/questions/74176134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18937753/" ]
74,176,159
<p>I'm trying to implement a kind of toggle effect with a button, when clicked it will flip between 2 images. I can get it to change once using the eventListeners on btn2 and btn3 but when I try to implement the 'toggle' effect in btn1 nothing happens when the button is clicked. Could someone tell me where I am going wrong?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script&gt; document.addEventListener('DOMContentLoaded', function(){ let eng = document.querySelector(&quot;#eimg&quot;); let spn = document.querySelector(&quot;#simg&quot;); let can = document.querySelector(&quot;#cimg&quot;); let btn1 = document.querySelector(&quot;#eswitch&quot;); let btn2 = document.querySelector(&quot;#sswitch&quot;); let btn3 = document.querySelector(&quot;#cswitch&quot;); btn1.addEventListener('click', function(){ if (eng.src == &quot;./England.jpeg&quot;){ eng.src = './England2.jpeg'; }else { eng.src = './England.jpeg'; } }) btn2.addEventListener('click', function(){ spn.src = 'Spain2.jpg'; }) btn3.addEventListener('click', function(){ can.src = 'Canada2.png'; }) }) &lt;/script&gt; &lt;link href=&quot;styles.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;My Webpage&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;header&quot;&gt; &lt;h1 class=&quot;title&quot;&gt;Travel&lt;/h1&gt; &lt;/div&gt; &lt;div&gt; &lt;nav aria-label=&quot;breadcrumb&quot;&gt; &lt;ol class=&quot;breadcrumb&quot;&gt; &lt;li class=&quot;breadcrumb-item&quot;&gt;&lt;a href=&quot;./index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;breadcrumb-item active&quot; aria-current=&quot;page&quot;&gt;Travel&lt;/li&gt; &lt;/ol&gt; &lt;/nav&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem;&quot;&gt; &lt;img id=&quot;eimg&quot; src=&quot;./England.jpeg&quot; class=&quot;card-img-top&quot; alt=&quot;Silhouette of England&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title&quot;&gt;England&lt;/h5&gt; &lt;button id=&quot;eswitch&quot; class=&quot;btn btn-primary&quot;&gt;England&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem;&quot;&gt; &lt;img id=&quot;simg&quot; src=&quot;./Spain.png&quot; class=&quot;card-img-top&quot; alt=&quot;Silhouette of Spain&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title&quot;&gt;Spain&lt;/h5&gt; &lt;button id=&quot;sswitch&quot; class=&quot;btn btn-primary&quot;&gt;Spain&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem;&quot;&gt; &lt;img id=&quot;cimg&quot; src=&quot;./Canada.png&quot; class=&quot;card-img-top&quot; alt=&quot;Silhouette of Canada&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title&quot;&gt;Canada&lt;/h5&gt; &lt;button id=&quot;cswitch&quot; class=&quot;btn btn-primary&quot;&gt;Canada&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74176279, "author": "oalva-rez", "author_id": 17400744, "author_profile": "https://Stackoverflow.com/users/17400744", "pm_score": 3, "selected": true, "text": "(eng.src == \"./England.jpeg\")" }, { "answer_id": 74176329, "author": "Franco Agustín Torres", "...
2022/10/24
[ "https://Stackoverflow.com/questions/74176159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17966700/" ]
74,176,215
<pre><code>#!/bin/sh #Saying the system time out loud time= date +&quot;%T&quot; say The current time now is, $time. Bye. </code></pre> <p>The script is printing out the time, not saying it.</p>
[ { "answer_id": 74176284, "author": "Red Cricket", "author_id": 759991, "author_profile": "https://Stackoverflow.com/users/759991", "pm_score": 0, "selected": false, "text": "bash-3.2$ cat <<EOT\n> The current time is now, `date +\"%T\"`\n> EOT\nThe current time is now, 19:49:16\n" }, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3951352/" ]
74,176,222
<p>This is my input:</p> <pre class="lang-php prettyprint-override"><code>[ [&quot;username&quot; =&gt; &quot;erick&quot;, &quot;location&quot; =&gt; [&quot;singapore&quot;], &quot;province&quot; =&gt; [&quot;jatim&quot;]], [&quot;username&quot; =&gt; &quot;thomas&quot;, &quot;location&quot; =&gt; [&quot;ukraina&quot;], &quot;province&quot; =&gt; [&quot;anonymouse&quot;]] ] </code></pre> <p>How can I flatten the inner arrays to string values?</p> <p>Expected output:</p> <pre class="lang-php prettyprint-override"><code>[ [&quot;username&quot; =&gt; &quot;erick&quot;, &quot;location&quot; =&gt; &quot;singapore&quot;, &quot;province&quot; =&gt; &quot;jatim&quot;], [&quot;username&quot; =&gt; &quot;thomas&quot;, &quot;location&quot; =&gt; &quot;ukraina&quot;, &quot;province&quot; =&gt; &quot;anonymouse&quot;] ]``` </code></pre>
[ { "answer_id": 74176284, "author": "Red Cricket", "author_id": 759991, "author_profile": "https://Stackoverflow.com/users/759991", "pm_score": 0, "selected": false, "text": "bash-3.2$ cat <<EOT\n> The current time is now, `date +\"%T\"`\n> EOT\nThe current time is now, 19:49:16\n" }, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9321247/" ]
74,176,224
<p>My predicate is <code>lll(C,R)</code> Where <code>C</code> is a country and <code>R</code> is a continent.</p> <p>Example of data that is needed for the predicate:</p> <pre><code>% ------------------ % country(N,C,Ar,Pop), a country N with % capital C, area Ar and population Pop % ------------------ country( andorra , 'Andorra la Vella' , 450 , 72766 ) . country( angola , 'Luanda' , 1246700 , 10342899 ) . % ------------------ % continent(N,Pop), N is a continent with population Pop. % ------------------ continent('Europe',9562488). % ------------------ % geo_sea(N,C,P), the sea N is in country C in province P % ------------------ geo_sea( 'Andaman Sea' , india , 'Andaman and Nicobar Is.' ) . % ------------------ % encompasses(C,R,Fr), country C is encompassed % by region R to fraction Fr (percent) %------------------- encompasses( austria , 'Europe' ,100 ) . encompasses( afghanistan , 'Asia' ,100 ) . encompasses( antigua_and_barbuda , 'America' ,100 ) . encompasses( albania , 'Europe' ,100 ) . </code></pre> <p>I want the biggest landlocked country so</p> <pre><code>lll(C,R) :- country(C,_,_,_), continent(R,_), not(geo_sea(_,C,_)), encompasses(C,R,100), setof( Circumf, circumference(Circumf,C), Cs ), max_list(Cs,CirMax), circumference(CirMax,C) . </code></pre> <p>This is what I came up with</p> <p>When i use this <code>lll(C,'Europe')</code> all landlocked countries get outputted instead.</p> <p>I want the country with this biggest circumference to be outputted. Issue right now is that the list only contains 1 element so when max is used on a list with 1 element it gets outputted.</p> <p>Any idea how to accomplish this?</p>
[ { "answer_id": 74177181, "author": "brebs", "author_id": 17628336, "author_profile": "https://Stackoverflow.com/users/17628336", "pm_score": 0, "selected": false, "text": "?- aggregate_all(max(Area), (country(Country, _, Area, _),\n\\+ geo_sea(_, Country, _)), MaxArea),\ncountry(Country,...
2022/10/24
[ "https://Stackoverflow.com/questions/74176224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20292919/" ]
74,176,242
<pre><code>Name,abc Title,teacher Email,abc.edu Phone,000-000-0000 Office,21building About,&quot;abc is teacher&quot; Name,def Title,plumber Email,plumber@plumber.com Phone,111-111-1111 Office,22building About,&quot;The best plumber in the town&quot; Name,ghi Title,producer Phone,333-333-3333 Office,33building About,&quot;The best producer&quot; </code></pre>
[ { "answer_id": 74177181, "author": "brebs", "author_id": 17628336, "author_profile": "https://Stackoverflow.com/users/17628336", "pm_score": 0, "selected": false, "text": "?- aggregate_all(max(Area), (country(Country, _, Area, _),\n\\+ geo_sea(_, Country, _)), MaxArea),\ncountry(Country,...
2022/10/24
[ "https://Stackoverflow.com/questions/74176242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15666347/" ]
74,176,265
<pre><code>paths.shape (525600, 50) T.shape (525600,) </code></pre> <p>how do I divide or multiply paths by T?</p> <p>More specifically I want to do this</p> <pre><code>S = pd.DataFrame(paths) d1 = S.divide(np.sqrt(T), axis=0) </code></pre> <p>but not using pandas</p> <p>want to use numpy only</p>
[ { "answer_id": 74176321, "author": "learner", "author_id": 17658327, "author_profile": "https://Stackoverflow.com/users/17658327", "pm_score": 0, "selected": false, "text": "paths.transpose()*T\npaths.transpose()/np.sqrt(T)\n" }, { "answer_id": 74177237, "author": "hpaulj", ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13840401/" ]
74,176,335
<p>I'm following <a href="https://code.kx.com/q4m3/14_Introduction_to_Kdb%2B/#1424-basic-operations-on-splayed-tables" rel="nofollow noreferrer">14.2.4 Basic Operations on Splayed Tables</a> on kx.com.</p> <p>In an empty directory, running below</p> <pre><code>`:db/t/ set .Q.en[`:db;] ([] s1:`a`b`c; v:10 20 30; s2:`x`y`z) </code></pre> <p>created a splayed table successfully:</p> <pre><code>[22:52:57] [~/tmp] tree . └── db ├── sym └── t ├── s1 ├── s2 └── v </code></pre> <p>Q1) After loading the table using <code>$ q db/t</code> as instructed, the enumerated symbols did not get displayed. What am I missing here?</p> <pre><code>[22:54:24] [~/tmp] q db/t KDB+ 4.0 ... q)select from t s1 v s2 -------- 0 10 3 1 20 4 2 30 5 </code></pre> <p>Q2) Loading using <code>$ q db</code> worked: the symfile was loaded successfully, and symbols appeared correctly. However, is there a way to load only one table? (Here, if I had more tables, all of them would've been loaded)</p> <pre><code>[23:05:18] [~/tmp] Q db KDB+ 4.0 ... q)t s1 v s2 -------- a 10 x b 20 y c 30 z q)sym `a`b`c`x`y`z </code></pre>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927314/" ]
74,176,338
<p>None of my react components render when I use github pages. My CSS seems to work (I can see the background pattern) but none of my react components render. Everything works fine locally, but it does not when I use github pages. Here is a link to my repo: <a href="https://github.com/GibbsV3/MySite" rel="nofollow noreferrer">https://github.com/GibbsV3/MySite</a> I have tried using the Router component but so far I cannot figure it out. Is there something wrong with my index.html file?</p>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318399/" ]
74,176,390
<p>I have a domain <code>mydomain.com</code> and a nginx space to host my website. The URL address <code>mydomain.com</code> is already in use and I don't want to buy another domain, so I created a subdomain <code>myapp.mydomain.com</code>. Then I created a laravel API app <code>myapp</code> for testing purposes and uploaded the code into <code>/mydomain_com/myapp</code> folder via a FTP client.</p> <p>The problem now is I have to configure my <code>.htaccess</code> accordingly so the the app can run correctly.</p> <p>At the current state, the homepage route <code>/</code> is working fine, but everything else is not working.</p> <p><strong>\mydomain_com\myapp.env:</strong></p> <pre><code>... APP_NAME=myapp APP_ENV=local APP_KEY=base64:U4v.... APP_DEBUG=false APP_URL=https://myapp.mydomain.com ... </code></pre> <p><strong>My routes are:</strong> <a href="https://i.stack.imgur.com/HAlmF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HAlmF.png" alt="Laravel API app routes" /></a></p> <p><strong>\mydomain_com\myapp\routes\web.php</strong></p> <pre class="lang-php prettyprint-override"><code>Route::get('/', function () { return view('welcome'); }); Route::get('/aaa', function () { return view('welcome'); }); </code></pre> <p><strong>\mydomain_com\myapp\routes\api.php</strong></p> <pre class="lang-php prettyprint-override"><code>Route::apiResource('os', OsController::class); </code></pre> <p>Now, when I go to <code>https://myapp.mydomain.com</code> I get this:</p> <p><a href="https://i.stack.imgur.com/GQw0l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GQw0l.png" alt="homepage route" /></a></p> <p>However when I try to visit <code>https://myapp.mydomain.com/aaa</code> and <code>https://myapp.mydomain.com/api/os</code>, I get this error ↓</p> <p><a href="https://i.stack.imgur.com/4myts.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4myts.png" alt="/aaa route" /></a></p> <p><strong>Can You pls tell me what's the problem with my <code>\mydomain_com\myapp\.htaccess</code> ↓ ? Why is the homepage only working?</strong></p> <pre><code>RewriteEngine On RewriteBase / # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] RewriteCond %{HTTP_HOST} !^subdomain RewriteCond %{REQUEST_URI} !^public RewriteRule ^(.*)$ public/$1 [L] RewriteCond %{HTTP_HOST} ^subdomain RewriteCond %{REQUEST_URI} !^public RewriteRule ^(.*)$ public/ [L] </code></pre>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16624097/" ]
74,176,392
<p>I have a Firestore collection called <code>users</code> that stores all my user info. When registering a new user, I first register them with Firebase Auth, then create the record in the <code>users</code> collection. Right now I'm storing the <code>UID</code> as a field, which means when I want to query a user's info, I need to do a query with a <code>WHERE</code> clause. However, one alternative to faster querying would be to store the <code>UID</code> as the document ID for the collection. That would make it so that I could query the collection with a specific ID, which intuitively seems faster.</p> <p>Using the <code>UID</code> as the doc ID makes me worried about some stuff:</p> <ol> <li>I'm not sure if I can assume that uniqueness for the <code>UID</code> in Firebase Auth implies uniqueness when using it as the doc ID in a Firestore collection.</li> <li>I watched a tutorial video by Todd that said that querying is faster if you use the auto-generated document ID that Firestore provides. Given this, I wouldn't want to take a risk using something else when the provided doc ID is known to be faster for querying.</li> </ol> <p>What would be the better approach to make querying as efficient as possible, assuming you are querying only based on <code>UID</code>? Or is the difference so negligible that this is a moot point?</p>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838216/" ]
74,176,398
<p>I have an array contain <code>n</code> number of elements can be 6 or 8, like that:</p> <pre><code>$langs = [&quot;PHP&quot;, &quot;JAVA&quot;, &quot;Ruby&quot;, &quot;C&quot;, &quot;C++&quot;, &quot;Perl&quot;]; </code></pre> <p>I would like to add one year evenly next to the elements</p> <p><strong>Desired output in case of 6 elements:</strong></p> <ul> <li>PHP - 2022</li> <li>JAVA - 2022</li> <li>Ruby - 2022</li> <li>C - 2023</li> <li>C++ - 2023</li> <li>Perl - 2023</li> </ul> <p><strong>Desired output in case of 9 elements:</strong></p> <ul> <li>PHP - 2022</li> <li>JAVA - 2022</li> <li>Ruby - 2022</li> <li>C - 2023</li> <li>C++ - 2023</li> <li>Perl - 2023</li> <li>Python - 2024</li> <li>Javascript - 2024</li> <li>Mysql - 2024</li> </ul> <p>My try :</p> <pre><code>$date = Carbon::now(); foreach($langs as $key =&gt; $lang){ if(count($langs) % $key == 0){ echo $lang .' - '. $date-&gt;addYear(); } } </code></pre>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187482/" ]
74,176,422
<p>The FDL has been working fine in production for a few weeks and has suddenly started show this error in the browser as if it does not have a valid SSL certificate.</p> <p>The FDL is generated via the API.</p> <p><strong>Is there a solution to remove this warning for my FDL?</strong></p> <p>I have raised a support request with GCP but have posted a question in here in case there is something I can do.</p> <p><a href="https://i.stack.imgur.com/klN9a.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/klN9a.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10222449/" ]
74,176,431
<p>I'm trying to write simple code in order to see if a string is in a list. This is the code I've gotten.</p> <pre><code>a = [&quot;Hill, Lauren&quot;, &quot;Smith, Jerry&quot;] b = &quot;Smith&quot; if b in a: print(&quot;True&quot;) else: print(&quot;False&quot;) </code></pre> <p>I don't understand why it prints &quot;False&quot;. I thought it would print &quot;True&quot; as &quot;Smith&quot; is in &quot;Smith, Jerry&quot;. Can someone explain why this happens?</p>
[ { "answer_id": 74178669, "author": "rianoc", "author_id": 4256419, "author_profile": "https://Stackoverflow.com/users/4256419", "pm_score": 2, "selected": false, "text": "get" }, { "answer_id": 74191980, "author": "Thomas Smyth - Treliant", "author_id": 5620913, "auth...
2022/10/24
[ "https://Stackoverflow.com/questions/74176431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318424/" ]
74,176,438
<p>How to convert List&lt;?&gt; to List in java?</p> <p>For example I have this class</p> <pre><code>@Data public class Example { private List&lt;?&gt; data; } </code></pre> <p>and I used in this function</p> <pre><code>@PostMapping(&quot;/getResult&quot;) @ResponseBody public Result getResult(@RequestBody String json) { Gson gson = new Gson(); Example xmpl = gson.fromJson(json, Example.class); List&lt;MyObject&gt; source = (List&lt;MyObject&gt;)xmpl.getData(); //==&gt; error // get Result return result; } </code></pre> <p>It will give this error</p> <pre><code> class com.google.gson.internal.LinkedTreeMap cannot be cast to class com.myproject.MyObject </code></pre> <p>EDITED:</p> <p>The real problem is not from converting ? to object, but from converting LinkedTreeMap to the object</p> <p>WORKAROUND :</p> <pre><code> String jsonData = gson.toJson(xmpl.getData()); MyObjectBean[] objs = gson.fromJson(jsonData,MyObjectBean[].class); </code></pre>
[ { "answer_id": 74176643, "author": "esthrim", "author_id": 1841601, "author_profile": "https://Stackoverflow.com/users/1841601", "pm_score": 1, "selected": false, "text": "String jsonData = gson.toJson(xmpl.getData());\n\nMyObjectBean[] objs = gson.fromJson(jsonData,MyObjectBean[].class)...
2022/10/24
[ "https://Stackoverflow.com/questions/74176438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841601/" ]
74,176,450
<p>I have an array of times (these are not constant) <code>[1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00]</code>. The goal is to calculate times that can be bookable. If there is an existing booking from <code>4:00 - 5:00</code> then <code>3:00</code> should be unavailable as it would overlap the existing booking. To calculate this, I have a function that tells us the start and end indexes of the booking, I need to find a way to remove x times from <strong>behind</strong> the start index.</p> <p>To make it more clear, I drew a diagram.</p> <p><a href="https://i.stack.imgur.com/ugLeH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ugLeH.jpg" alt="problem diagram" /></a></p> <p>Doing this calculation will allow to calculate available times no matter how long the existing booking is. I'm trying to figure out how to create a function that does what I described. Below is the code I have to return the available times based on the start/end index provided however I'm stuck on how to approach the calculation I described above.</p> <pre><code> // This filters times that are less than the start index const filteredTimes1 = availableHours.filter((item, index) =&gt; index &lt; ( (startTimeIndex || availableHours.length - 0) )) // This filters times that greater than the end index const filteredTimes2 = availableHours.filter((item, index) =&gt; index &gt; (endTimeIndex || availableHours.length) ) // Then combine the results into an array const validAvailableHours = [...filteredTimes1 , ...filteredTimes2] </code></pre> <p>Any help would be appreciated, thanks.</p>
[ { "answer_id": 74176643, "author": "esthrim", "author_id": 1841601, "author_profile": "https://Stackoverflow.com/users/1841601", "pm_score": 1, "selected": false, "text": "String jsonData = gson.toJson(xmpl.getData());\n\nMyObjectBean[] objs = gson.fromJson(jsonData,MyObjectBean[].class)...
2022/10/24
[ "https://Stackoverflow.com/questions/74176450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203366/" ]
74,176,471
<p>For a uni assignment, a function &quot;lookup&quot; has been defined as:</p> <pre><code>lookup :: Env e -&gt; String -&gt; Maybe e </code></pre> <p>The &quot;Env&quot; keyword has been defined as:</p> <pre><code>import qualified Data.Map as M newtype Env e = Env (M.Map String e) deriving (Functor, Foldable, Traversable, Show, Eq, Monoid, Semigroup) </code></pre> <p>I understand that the double colon &quot;::&quot; means &quot;has type of&quot;. So the lookup function takes two arguments and returns something. I know the second argument is a string, however, I'm struggling to understand the first argument and the output. What is the &quot;Env&quot; type and what does the &quot;e&quot; after it represent. It feels like e is an argument to &quot;Env&quot; but if that is the case, the output wouldn't make sense.</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 74176877, "author": "Ben", "author_id": 450128, "author_profile": "https://Stackoverflow.com/users/450128", "pm_score": 3, "selected": true, "text": "Env" }, { "answer_id": 74178345, "author": "LudvigH", "author_id": 4050510, "author_profile": "https://...
2022/10/24
[ "https://Stackoverflow.com/questions/74176471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19866923/" ]
74,176,488
<p>Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:</p> <p>the total of all the inputs the smallest of the inputs the largest of the inputs the number of even inputs the number of odd inputs the average of all of the inputs</p> <p>You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.</p> <p>So far this is my code but I want to know if there's a way without using the sys module</p> <pre><code>import sys # declare a variable largest which has smallest integer value # -sys.maxsize gives the smallest integer value,you can also use any smallest value largest = -sys.maxsize # declare a variable smallest, that is assigned with maximum integer value smallest = sys.maxsize # declare variables total to store the sum of all numbers total = 0 # option variable is to store the user option Y or N option = 'y' # declare variables to count odd, even and totalCount evenCount = 0 oddCount = 0 totalCount = 0 print(&quot;This program will calculate statistics for your integer data.&quot;) # run the loop when the user enters y or Y while option == 'y' or option == 'Y': # take input of number number = int(input(&quot;Please type a number: &quot;)) # add the number to total total = total + number # increase totalCount totalCount = totalCount + 1 # calculate smallest if number &lt; smallest: smallest = number # calculate largest if number &gt; largest: largest = number # calculate count of even and odd numbers if number % 2 == 0: evenCount = evenCount + 1 else: oddCount = oddCount + 1 option = input(&quot;Do you have another number to enter? &quot;) # calculate average average = total / totalCount # print the output print(&quot;\nThe total of your numbers is:&quot;, total) print(&quot;The smallest of your numbers is:&quot;, smallest) print(&quot;The largest nof yout numbers is:&quot;, largest) print(&quot;The number of even numbers is:&quot;, evenCount) print(&quot;The number of odd numbers is:&quot;, oddCount) print(&quot;The average of your numbers is:&quot;, average) </code></pre>
[ { "answer_id": 74176877, "author": "Ben", "author_id": 450128, "author_profile": "https://Stackoverflow.com/users/450128", "pm_score": 3, "selected": true, "text": "Env" }, { "answer_id": 74178345, "author": "LudvigH", "author_id": 4050510, "author_profile": "https://...
2022/10/24
[ "https://Stackoverflow.com/questions/74176488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318252/" ]
74,176,504
<p>I´m starting with neo4j and would like to know how to get the age in years. I have the node below</p> <pre><code>(p1:Person{id:1,birthdate:&quot;1989-10-03&quot;,name:&quot;Person1&quot;}) </code></pre> <p>tried something like this</p> <pre><code>with p.birthdate as bd, date() as d return d - bd </code></pre>
[ { "answer_id": 74177586, "author": "stellasia", "author_id": 4709400, "author_profile": "https://Stackoverflow.com/users/4709400", "pm_score": 2, "selected": true, "text": "date" }, { "answer_id": 74181168, "author": "jose_bacoy", "author_id": 7371893, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20006672/" ]
74,176,515
<p>I am trying to make an app that will display the weather data after the user enters a city. I am using the openweathermap.org API. In my console under networks it shows that I am making an API call when I enter the city but no data is returning. The missing data that should display is the city name, the temperature and the weather. Please advise on how I can fix this.</p> <p>App.js:</p> <pre><code>import React, { useState } from 'react'; import './App.css'; function App() { const apiKey = 'API Key'; //I entered my API key here const [weatherData, setWeatherData] = useState([{}]); const [city, setCity] = useState(''); const getWeather = (event) =&gt; { if (event.key == 'Enter') { fetch( 'https://api.openweathermap.org/data/2.5/weather?q=s{city}&amp;units=imperil&amp;APPID=${apiKey}' //I copied this api from the tutorial ) .then((response) =&gt; response.json()) .then((data) =&gt; { setWeatherData(data); setCity(''); }); } }; return ( &lt;div className=&quot;container&quot;&gt; &lt;input className=&quot;input&quot; placeholder=&quot;Enter City...&quot; onChange={(e) =&gt; setCity(e.target.value)} value={city} onKeyPress={getWeather} /&gt; {typeof weatherData.main === 'undefined' ? ( &lt;div&gt; &lt;p&gt;Welcome to weather app! Enter the city you want the weather of.&lt;/p&gt; &lt;/div&gt; ) : ( &lt;div className=&quot;weather-data&quot;&gt; &lt;p className=&quot;city&quot;&gt;{weatherData.name}&lt;/p&gt; &lt;p className=&quot;temp&quot;&gt;{Math.round(weatherData.main.temp)}℉&lt;/p&gt; &lt;p className=&quot;weather&quot;&gt;{weatherData.weather[0].main}&lt;/p&gt; &lt;/div&gt; )} {weatherData.cod === '404' ? &lt;p&gt;City not found.&lt;/p&gt; : &lt;&gt;&lt;/&gt;} &lt;/div&gt; ); } export default App; </code></pre> <p>App.css:</p> <pre><code>.container { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 25px; } .input { padding: 15px; width: 80%; margin: auto; border: 1px solid lightgrey; border-radius: 6px; font-size: 16px; } .input:focus{ outline: none; } .weather-data{ margin-top: 100px; display: flex; flex-direction: column; align-items: center; } .city{ font-size: 30px; font-weight: 200; } .temp{ font-size: 90px; padding: 10px; border: 1px solid lightgray; border-radius: 12px; } .weather{ font-size: 30px; font-weight: 200; } </code></pre>
[ { "answer_id": 74177586, "author": "stellasia", "author_id": 4709400, "author_profile": "https://Stackoverflow.com/users/4709400", "pm_score": 2, "selected": true, "text": "date" }, { "answer_id": 74181168, "author": "jose_bacoy", "author_id": 7371893, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18630139/" ]
74,176,540
<p>I am trying to call the class <em>FileRead</em> and methods <em>Display</em> and <em>Contents</em> from another separate class, however it is within the same package. This is my main class. It works within Eclipse. I can type in a text file and it displays it. This class also compiles and runs in command prompt.</p> <pre><code>public class FileRead { static String theFile; Scanner myScanner = new Scanner (System.in); static List&lt;String&gt; fileArray = new ArrayList&lt;String&gt;(); static StringBuffer stringBuff = new StringBuffer(); public FileRead() { System.out.println (&quot;Enter your file: &quot;); theFile = myScanner.nextLine(); try { myScanner = new Scanner(new File(theFile)); FileReader myFileReader = new FileReader(theFile); BufferedReader buffRead = new BufferedReader(myFileReader); while ((theFile = buffRead.readLine()) != null) { fileArray.add(theFile); } buffRead.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String Contents() { for (String str : fileArray) { stringBuff.append(str); stringBuff.append(&quot;\n&quot;); } String str = stringBuff.toString(); return (str); } public void Display() { for (int i = 0; i &lt; fileArray.size(); i++) { System.out.println (&quot;Line # &quot; + (i + 1) + &quot; &quot; + fileArray.get(i)); } } public static void main (String[] args) { //FileRead textFile = new FileRead(); //textFile.Display(); //textFile.Contents(); } } </code></pre> <p>The problem I am having is with this class:</p> <pre><code>public class FileReadShow { public static void main (String[] args) { try { FileRead myTextFile = new FileRead(); myTextFile.Contents(); myTextFile.Display(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>When I try to compile this in the command prompt, I get this:</p> <pre><code>javac filereadshow.java filereadshow.java:112: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow filereadshow.java:112: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow 2 errors </code></pre> <p>I've done some searching around and found the main causes of these errors. I didn't find any typos. I also tried removing one <em>main</em> methods from one of these classes but that hadn't worked either. One thing I'm still unsure of is undeclared variables, which is my first question.</p> <p>1: I am new to constructors, and it looks correct to me, but could the problem be that I have incorrectly called the reference to the object where the <em>FileRead</em> constructor is?</p> <p>2: I have narrowed the errors down to this statement alone <code>FileRead myTextFile = new FileRead();</code> because no matter what I do with it, this is where the errors are. Could someone please help me determine if the problem is with the <em>FileRead</em> script itself, or with the object reference <code>FileRead myTextFile = new FileRead();</code>?</p> <p>Thanks for your time!</p> <p>EDIT: FileRead.class is in the current directory as I am able to compile it. I compiled that before trying FileReadShow.</p> <p>EDIT #2: I switched IDE's and found more information which gave me two compile error descriptions:</p> <pre><code>Exception in thread &quot;main&quot; java.lang.Error: Unresolved compilation problems: -FileRead cannot be resolved to a type -FileRead cannot be resolved to a type </code></pre> <p>So far there doesn't seem to be a very definitive answer. I am currently working through fixes that have worked for other people. Such as restarting eclipse/PC, using the &quot;clean&quot; option in the file drop down menu, creating a new class, etc. So far nothing has worked. I will keep trying. Does anyone have any more suggestions I could try?</p> <p>EDIT #3: Both of my .java files are inside of the package folder that contains everything for Eclipse (.CLASSPATH, .project, src folder, bin folder, etc). Normally when I change directories in command prompt, I go to this package folder and can compile with ease. My exact command prompt input is:</p> <pre><code>C:\Users\D&gt;cd eclipse-workspace\packageone\src\packageone C:\Users\D\eclipse-workspace\PackageOne\src\PackageOne&gt;javac fileread.java //As you can see the first one compiled, so I call the second below C:\Users\D\eclipse-workspace\PackageOne\src\PackageOne&gt;javac filereadshow.java filereadshow.java:90: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow filereadshow.java:90: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow 2 errors </code></pre> <p>The first .java file (FileRead.java) compiled, the second one (.FileReadShow.java) still results in errors. What am I doing wrong? I've compiled dozens of programs this way and haven't run into this...?</p>
[ { "answer_id": 74177586, "author": "stellasia", "author_id": 4709400, "author_profile": "https://Stackoverflow.com/users/4709400", "pm_score": 2, "selected": true, "text": "date" }, { "answer_id": 74181168, "author": "jose_bacoy", "author_id": 7371893, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14695508/" ]
74,176,557
<h2>Introduction</h2> <p>I recently learned how to plot <code>Simple Moving Averages</code> (<em>abbreviated &quot;SMA&quot;</em>) using the <a href="https://github.com/matplotlib/mplfinance" rel="nofollow noreferrer"><code>MatPlotLibFinance</code></a> library on <code>Python3</code>. <code>Simple Moving Averages</code> are trend lines that They help the investor in determining the best times to enter to buy or sell an asset.</p> <h2>Data</h2> <p>The following variables contain the data used in the Script to plot the price action, the first variable was named <code>df_trading_pair</code> and contains the following information:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Start Date</th> <th>Open Price</th> <th>High Price</th> <th>Low Price</th> <th>Close Price</th> <th>Volume</th> <th>End Date</th> <th>Abs((CP-OP)/CP)*100</th> <th>Low SMA 9</th> <th>Close SMA 25</th> <th>High SMA 99</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>2022-10-23 23:42:00</td> <td>29.24</td> <td>29.28</td> <td>29.24</td> <td>29.25</td> <td>2145.0</td> <td>2022-10-23 23:44:59.999</td> <td>0.03</td> <td>29.195555555555554</td> <td>29.236400000000003</td> <td>28.95191919191919</td> </tr> <tr> <td>1</td> <td>2022-10-23 23:45:00</td> <td>29.25</td> <td>29.27</td> <td>29.24</td> <td>29.24</td> <td>2233.0</td> <td>2022-10-23 23:47:59.999</td> <td>0.03</td> <td>29.192222222222224</td> <td>29.239199999999997</td> <td>28.95848484848485</td> </tr> <tr> <td>2</td> <td>2022-10-23 23:48:00</td> <td>29.24</td> <td>29.24</td> <td>29.23</td> <td>29.23</td> <td>1399.0</td> <td>2022-10-23 23:50:59.999</td> <td>0.03</td> <td>29.193333333333335</td> <td>29.2316</td> <td>28.96454545454545</td> </tr> <tr> <td>3</td> <td>2022-10-23 23:51:00</td> <td>29.23</td> <td>29.24</td> <td>29.21</td> <td>29.21</td> <td>2603.0</td> <td>2022-10-23 23:53:59.999</td> <td>0.07</td> <td>29.19888888888889</td> <td>29.2284</td> <td>28.97060606060606</td> </tr> <tr> <td>4</td> <td>2022-10-23 23:54:00</td> <td>29.22</td> <td>29.3</td> <td>29.22</td> <td>29.25</td> <td>5576.0</td> <td>2022-10-23 23:56:59.999</td> <td>0.1</td> <td>29.209999999999997</td> <td>29.228</td> <td>28.977575757575757</td> </tr> <tr> <td>5</td> <td>2022-10-23 23:57:00</td> <td>29.24</td> <td>29.28</td> <td>29.23</td> <td>29.26</td> <td>3848.0</td> <td>2022-10-23 23:59:59.999</td> <td>0.07</td> <td>29.221111111111114</td> <td>29.226799999999997</td> <td>28.983636363636364</td> </tr> <tr> <td>6</td> <td>2022-10-24 00:00:00</td> <td>29.26</td> <td>29.34</td> <td>29.25</td> <td>29.27</td> <td>9973.0</td> <td>2022-10-24 00:02:59.999</td> <td>0.03</td> <td>29.22666666666667</td> <td>29.2288</td> <td>28.990202020202016</td> </tr> <tr> <td>7</td> <td>2022-10-24 00:03:00</td> <td>29.28</td> <td>29.36</td> <td>29.26</td> <td>29.34</td> <td>11754.0</td> <td>2022-10-24 00:05:59.999</td> <td>0.2</td> <td>29.234444444444446</td> <td>29.233600000000003</td> <td>28.996969696969696</td> </tr> <tr> <td>8</td> <td>2022-10-24 00:06:00</td> <td>29.34</td> <td>29.44</td> <td>29.33</td> <td>29.41</td> <td>28414.0</td> <td>2022-10-24 00:08:59.999</td> <td>0.24</td> <td>29.245555555555555</td> <td>29.24</td> <td>29.003939393939394</td> </tr> <tr> <td>9</td> <td>2022-10-24 00:09:00</td> <td>29.42</td> <td>29.48</td> <td>29.4</td> <td>29.43</td> <td>21753.0</td> <td>2022-10-24 00:11:59.999</td> <td>0.03</td> <td>29.263333333333335</td> <td>29.248800000000003</td> <td>29.011414141414143</td> </tr> <tr> <td>10</td> <td>2022-10-24 00:12:00</td> <td>29.43</td> <td>29.43</td> <td>29.28</td> <td>29.28</td> <td>9341.0</td> <td>2022-10-24 00:14:59.999</td> <td>0.51</td> <td>29.26777777777778</td> <td>29.2528</td> <td>29.018787878787876</td> </tr> <tr> <td>11</td> <td>2022-10-24 00:15:00</td> <td>29.29</td> <td>29.3</td> <td>29.25</td> <td>29.26</td> <td>3000.0</td> <td>2022-10-24 00:17:59.999</td> <td>0.1</td> <td>29.27</td> <td>29.2556</td> <td>29.024040404040406</td> </tr> <tr> <td>12</td> <td>2022-10-24 00:18:00</td> <td>29.26</td> <td>29.29</td> <td>29.25</td> <td>29.28</td> <td>3065.0</td> <td>2022-10-24 00:20:59.999</td> <td>0.07</td> <td>29.27444444444445</td> <td>29.2588</td> <td>29.029393939393938</td> </tr> <tr> <td>13</td> <td>2022-10-24 00:21:00</td> <td>29.27</td> <td>29.29</td> <td>29.26</td> <td>29.27</td> <td>754.0</td> <td>2022-10-24 00:23:59.999</td> <td>0.0</td> <td>29.278888888888886</td> <td>29.2612</td> <td>29.034444444444443</td> </tr> <tr> <td>14</td> <td>2022-10-24 00:24:00</td> <td>29.28</td> <td>29.33</td> <td>29.28</td> <td>29.33</td> <td>2657.0</td> <td>2022-10-24 00:26:59.999</td> <td>0.17</td> <td>29.284444444444446</td> <td>29.266</td> <td>29.039292929292927</td> </tr> <tr> <td>15</td> <td>2022-10-24 00:27:00</td> <td>29.33</td> <td>29.39</td> <td>29.32</td> <td>29.33</td> <td>3722.0</td> <td>2022-10-24 00:29:59.999</td> <td>0.0</td> <td>29.29222222222222</td> <td>29.2676</td> <td>29.04484848484848</td> </tr> <tr> <td>16</td> <td>2022-10-24 00:30:00</td> <td>29.34</td> <td>29.41</td> <td>29.34</td> <td>29.4</td> <td>3906.0</td> <td>2022-10-24 00:32:59.999</td> <td>0.2</td> <td>29.30111111111111</td> <td>29.2716</td> <td>29.051010101010103</td> </tr> <tr> <td>17</td> <td>2022-10-24 00:33:00</td> <td>29.39</td> <td>29.39</td> <td>29.34</td> <td>29.34</td> <td>3269.0</td> <td>2022-10-24 00:35:59.999</td> <td>0.17</td> <td>29.302222222222227</td> <td>29.274</td> <td>29.056767676767677</td> </tr> <tr> <td>18</td> <td>2022-10-24 00:36:00</td> <td>29.34</td> <td>29.38</td> <td>29.26</td> <td>29.28</td> <td>5719.0</td> <td>2022-10-24 00:38:59.999</td> <td>0.2</td> <td>29.286666666666665</td> <td>29.276</td> <td>29.061818181818182</td> </tr> <tr> <td>19</td> <td>2022-10-24 00:39:00</td> <td>29.28</td> <td>29.29</td> <td>29.23</td> <td>29.25</td> <td>2118.0</td> <td>2022-10-24 00:41:59.999</td> <td>0.1</td> <td>29.281111111111116</td> <td>29.2788</td> <td>29.066060606060606</td> </tr> <tr> <td>20</td> <td>2022-10-24 00:42:00</td> <td>29.24</td> <td>29.24</td> <td>29.21</td> <td>29.23</td> <td>1875.0</td> <td>2022-10-24 00:44:59.999</td> <td>0.03</td> <td>29.276666666666667</td> <td>29.2832</td> <td>29.069999999999997</td> </tr> <tr> <td>21</td> <td>2022-10-24 00:45:00</td> <td>29.23</td> <td>29.25</td> <td>29.21</td> <td>29.24</td> <td>6155.0</td> <td>2022-10-24 00:47:59.999</td> <td>0.03</td> <td>29.272222222222222</td> <td>29.284000000000002</td> <td>29.074242424242424</td> </tr> <tr> <td>22</td> <td>2022-10-24 00:48:00</td> <td>29.23</td> <td>29.23</td> <td>29.18</td> <td>29.19</td> <td>1913.0</td> <td>2022-10-24 00:50:59.999</td> <td>0.14</td> <td>29.263333333333335</td> <td>29.281999999999996</td> <td>29.077777777777776</td> </tr> <tr> <td>23</td> <td>2022-10-24 00:51:00</td> <td>29.19</td> <td>29.2</td> <td>29.13</td> <td>29.14</td> <td>6363.0</td> <td>2022-10-24 00:53:59.999</td> <td>0.17</td> <td>29.246666666666663</td> <td>29.278</td> <td>29.081111111111113</td> </tr> <tr> <td>24</td> <td>2022-10-24 00:54:00</td> <td>29.14</td> <td>29.17</td> <td>29.12</td> <td>29.17</td> <td>8608.0</td> <td>2022-10-24 00:56:59.999</td> <td>0.1</td> <td>29.224444444444444</td> <td>29.275199999999998</td> <td>29.084444444444447</td> </tr> <tr> <td>25</td> <td>2022-10-24 00:57:00</td> <td>29.17</td> <td>29.21</td> <td>29.17</td> <td>29.19</td> <td>2111.0</td> <td>2022-10-24 00:59:59.999</td> <td>0.07</td> <td>29.20555555555556</td> <td>29.272799999999997</td> <td>29.087979797979795</td> </tr> <tr> <td>26</td> <td>2022-10-24 01:00:00</td> <td>29.2</td> <td>29.2</td> <td>29.16</td> <td>29.19</td> <td>2259.0</td> <td>2022-10-24 01:02:59.999</td> <td>0.03</td> <td>29.185555555555556</td> <td>29.270800000000005</td> <td>29.091313131313132</td> </tr> <tr> <td>27</td> <td>2022-10-24 01:03:00</td> <td>29.18</td> <td>29.21</td> <td>29.18</td> <td>29.21</td> <td>1634.0</td> <td>2022-10-24 01:05:59.999</td> <td>0.1</td> <td>29.176666666666662</td> <td>29.27</td> <td>29.094242424242424</td> </tr> <tr> <td>28</td> <td>2022-10-24 01:06:00</td> <td>29.21</td> <td>29.23</td> <td>29.2</td> <td>29.22</td> <td>3276.0</td> <td>2022-10-24 01:08:59.999</td> <td>0.03</td> <td>29.173333333333332</td> <td>29.2704</td> <td>29.0979797979798</td> </tr> <tr> <td>29</td> <td>2022-10-24 01:09:00</td> <td>29.21</td> <td>29.21</td> <td>29.19</td> <td>29.2</td> <td>837.0</td> <td>2022-10-24 01:11:59.999</td> <td>0.03</td> <td>29.171111111111113</td> <td>29.2684</td> <td>29.101717171717173</td> </tr> </tbody> </table> </div> <p>Also, another variable called <code>df_trading_pair_date_time_index</code> contains the same information as the previous variable with slight modifications, since it can only be used in this way in the script below:</p> <pre><code>def set_DateTimeIndex(df_trading_pair): df_trading_pair = df_trading_pair.set_index('Start Date', inplace=False) # Rename the column names for best practices df_trading_pair.rename(columns = { &quot;Open Price&quot; : 'Open', &quot;High Price&quot; : 'High', &quot;Low Price&quot; : 'Low', &quot;Close Price&quot; :'Close', }, inplace = True) return df_trading_pair # Create another df just to properly plot the data df_trading_pair_date_time_index = set_DateTimeIndex(df_trading_pair) </code></pre> <h2>Script</h2> <p>The following script will essentially plot a Japanese candlestick chart using the information stored in the <code>df_trading_pair</code> and <code>df_trading_pair_date_time_index</code> variables, the main details of such procedure are explained as comments within the script:</p> <pre><code>import pandas as pd import mplfinance as mpf import matplotlib.pyplot as plt import matplotlib.dates as mdates trading_pair = &quot;SOLBUSD&quot; # Plotting # Create my own `marketcolors` style: mc = mpf.make_marketcolors(up='#2fc71e',down='#ed2f1a',inherit=True) # Create my own `MatPlotFinance` style: s = mpf.make_mpf_style(base_mpl_style=['bmh', 'dark_background'],marketcolors=mc, y_on_right=True) # Plot it # First create a dictionary to store the plots to add subplots = {'Low SMA 9': mpf.make_addplot(df_trading_pair['Low SMA 9'], width=1, color='#F0FF42'), 'Close SMA 25': mpf.make_addplot(df_trading_pair['Close SMA 25'], width=1.5, color='#EA047E'), 'High SMA 99': mpf.make_addplot(df_trading_pair['High SMA 99'], width=2, color='#00FFD1')} trading_plot, axlist = mpf.plot(df_trading_pair_date_time_index, figratio=(10, 6), type=&quot;candle&quot;, style=s, tight_layout=True, datetime_format = '%H:%M', ylabel = &quot;Precio ($)&quot;, returnfig=True, show_nontrading=True, addplot=list(subplots.values()) ) # Add Title symbol = trading_pair.replace(&quot;BUSD&quot;,&quot;&quot;)+&quot;/&quot;+&quot;BUSD&quot; axlist[0].set_title(f&quot;{symbol} - 3m&quot;, fontsize=25, style='italic', fontfamily='fantasy') # Find which times should be shown every 6 minutes starting at the last row of the df x_axis_minutes = [] for i in range (1,len(df_trading_pair_date_time_index),2): x_axis_minutes.append(df_trading_pair_date_time_index.index[-i].minute) # Set the main &quot;ticks&quot; to show at the x axis axlist[0].xaxis.set_major_locator(mdates.MinuteLocator(byminute=x_axis_minutes)) # Set the x axis label axlist[0].set_xlabel('Zona Horaria UTC') # Set the SMA legends # First set the amount of legends to add to the legend box axlist[0].legend([None]*(len(subplots)+2)) # Then Store the legend objects in a variable called &quot;handles&quot;, based on this script, your objects to legend will appear from the third element in this list handles = axlist[0].get_legend().legendHandles # Finally set the corresponding names for the plotted SMA trends and place the legend box to the upper left corner of the bigger plot axlist[0].legend(handles=handles[2:],labels=list(subplots.keys()), loc = 'upper left') </code></pre> <p>Finally, this script will produce the following image:</p> <p><a href="https://i.stack.imgur.com/sxi4s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sxi4s.png" alt="output1" /></a></p> <h2>Problem</h2> <p>When comparing the chart printed by my script against the chart displayed by Binance:</p> <p><a href="https://i.stack.imgur.com/Ezn79.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ezn79.png" alt="gráfico de binance" /></a></p> <p>It is evident that the largest moving average (the one of <code>99</code> value) was not plotted as such, or it was, but <em><strong>I think</strong></em> because of the size set (<code>figratio=(10, 6)</code>) for the same plot it ended up not appearing.</p> <h2>The Question</h2> <p>How could I make my script do a kind of <strong>Zoom out</strong> so that when printing the graph it shows the moving average of <code>99</code> without affecting the display of the other elements printed in the graph?.</p>
[ { "answer_id": 74177586, "author": "stellasia", "author_id": 4709400, "author_profile": "https://Stackoverflow.com/users/4709400", "pm_score": 2, "selected": true, "text": "date" }, { "answer_id": 74181168, "author": "jose_bacoy", "author_id": 7371893, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16467154/" ]
74,176,572
<p>This code doesn't compile. But it fails on the last line marked <code>Err</code>, not the line marked <code>Ok</code>. Why can we assign a mutable reference to an immutable reference type but not use it after the assignment?</p> <pre><code>fn main() { let mut x = 10; let mut y = 20; let mut r = &amp;x; r = &amp;mut y; //Ok *r = 30; //Err } </code></pre>
[ { "answer_id": 74176636, "author": "kmdreko", "author_id": 2189130, "author_profile": "https://Stackoverflow.com/users/2189130", "pm_score": 3, "selected": true, "text": "r" }, { "answer_id": 74177492, "author": "Jmb", "author_id": 5397009, "author_profile": "https://...
2022/10/24
[ "https://Stackoverflow.com/questions/74176572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20312298/" ]
74,176,576
<p>Assuming we have a dataframe <code>df</code>:</p> <pre><code> date y_true y_pred1 y_pred2 0 2017-1-31 6.42 -2.35 15.57 1 2017-2-28 -2.35 15.57 6.64 2 2017-3-31 15.57 6.64 7.61 3 2017-4-30 6.64 7.61 10.28 4 2017-5-31 7.61 7.61 6.34 5 2017-6-30 10.28 6.34 4.88 6 2017-7-31 6.34 4.88 7.91 7 2017-8-31 6.34 7.91 6.26 8 2017-9-30 7.91 6.26 11.51 9 2017-10-31 6.26 11.51 10.73 10 2017-11-30 11.51 10.73 10.65 11 2017-12-31 10.73 10.65 32.05 </code></pre> <p>I want to calculate the ratio of the <strong>upward, downward, and equal consistency</strong> of two consecutive months of data in two columns, and use it as an evaluation metric of the time series forecast results. The direction of the current month to previous month ratio: <strong>up</strong> means the current month value minus the previous month value is positive, similarly, <strong>down</strong> and <code>equal</code> means negative and 0, respectively.</p> <p>I calculated the results for the sample data using the following function and code, note that we do not include the yellow rows in the calculation of the final ratio, because the <code>y_true_dir</code> for these rows is either <code>null</code> or <code>0</code>:</p> <p><a href="https://i.stack.imgur.com/4DuDz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4DuDz.png" alt="enter image description here" /></a></p> <pre><code>def cal_arrays_direction(value): if value &gt; 0: return 1 elif value &lt; 0: return -1 elif value == 0: return 0 else: return np.NaN df['y_true_diff'] = df['y_true'].diff(1).map(cal_arrays_direction) df['y_pred1_diff'] = df['y_pred1'].diff(1).map(cal_arrays_direction) df['y_pred2_diff'] = df['y_pred2'].diff(1).map(cal_arrays_direction) df['y_true_y_pred1'] = np.where((df['y_true_diff'] == df['y_pred1_diff']), 1, 0) df['y_true_y_pred2'] = np.where((df['y_true_diff'] == df['y_pred2_diff']), 1, 0) dir_acc_y_true_pred1 = df['y_true_y_pred1'].value_counts()[1] / (df['y_true_diff'].value_counts()[-1] + df['y_true_diff'].value_counts()[1]) print(dir_acc_y_true_pred1) dir_acc_y_true_pred2 = df['y_true_y_pred2'].value_counts()[1] / (df['y_true_diff'].value_counts()[-1] + df['y_true_diff'].value_counts()[1]) print(dir_acc_y_true_pred2) </code></pre> <p>Out:</p> <pre><code>0.2 0.4 </code></pre> <p>But I wonder how could I convert it into a function (similar to <code>MSE</code>, <code>RMSE</code>, etc. in <code>sklearn</code>) to make it's easier to use, thanks!</p> <pre><code>def direction_consistency_acc(y_true, y_pred): ... return dir_acc_ratio </code></pre> <p><strong>Update 1:</strong></p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py&quot;, line 3803, in get_loc return self._engine.get_loc(casted_key) File &quot;pandas\_libs\index.pyx&quot;, line 138, in pandas._libs.index.IndexEngine.get_loc File &quot;pandas\_libs\index.pyx&quot;, line 165, in pandas._libs.index.IndexEngine.get_loc File &quot;pandas\_libs\hashtable_class_helper.pxi&quot;, line 1577, in pandas._libs.hashtable.Float64HashTable.get_item File &quot;pandas\_libs\hashtable_class_helper.pxi&quot;, line 1587, in pandas._libs.hashtable.Float64HashTable.get_item KeyError: 1.0 The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;..\code\stacked model_2022-11-08.py&quot;, line 353, in &lt;module&gt; run_model(df) File &quot;..\code\stacked model_2022-11-08.py&quot;, line 258, in run_model out1 = direction_consistency_acc(preds['y_true'], preds[['y_pred1','y_pred2', File &quot;..\code\stacked model_2022-11-08.py&quot;, line 245, in direction_consistency_acc dir_acc_y_true_pred = preds[f'y_true_{col}'].eq(1).sum() / (s[-1] + s[1]) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py&quot;, line 981, in __getitem__ return self._get_value(key) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py&quot;, line 1089, in _get_value loc = self.index.get_loc(label) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py&quot;, line 3805, in get_loc raise KeyError(key) from err KeyError: 1 Process finished with exit code 1 </code></pre> <p><strong>Update 2:</strong></p> <p>I <code>print(df['y_true_diff'].value_counts())</code> while runing <code>direction_consistency_acc(df['y_true'], df[['y_pred1','y_pred2']])</code>:</p> <pre><code>... 2021-05-31 -1.0 4 1.0 2 Name: y_true_diff, dtype: int64 2021-06-30 -1.0 5 1.0 1 Name: y_true_diff, dtype: int64 2021-07-31 Traceback (most recent call last): File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py&quot;, line 3803, in get_loc -1.0 6 Name: y_true_diff, dtype: int64 return self._engine.get_loc(casted_key) File &quot;pandas\_libs\index.pyx&quot;, line 138, in pandas._libs.index.IndexEngine.get_loc File &quot;pandas\_libs\index.pyx&quot;, line 165, in pandas._libs.index.IndexEngine.get_loc File &quot;pandas\_libs\hashtable_class_helper.pxi&quot;, line 1577, in pandas._libs.hashtable.Float64HashTable.get_item File &quot;pandas\_libs\hashtable_class_helper.pxi&quot;, line 1587, in pandas._libs.hashtable.Float64HashTable.get_item KeyError: 1.0 The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;..\code\stacked model_2022-11-08.py&quot;, line 353, in &lt;module&gt; run_model(df) File &quot;..\code\stacked model_2022-11-08.py&quot;, line 258, in run_model out1 = direction_consistency_acc(preds['y_true'], preds[['y_pred1','y_pred2', File &quot;..\code\stacked model_2022-11-08.py&quot;, line 245, in direction_consistency_acc dir_acc_y_true_pred = preds[f'y_true_{col}'].eq(1).sum() / (s[-1] + s[1]) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py&quot;, line 981, in __getitem__ return self._get_value(key) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py&quot;, line 1089, in _get_value loc = self.index.get_loc(label) File &quot;C:\Users\LSTM\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py&quot;, line 3805, in get_loc raise KeyError(key) from err KeyError: 1 </code></pre>
[ { "answer_id": 74176927, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "numpy.sign" }, { "answer_id": 74176984, "author": "ah bon", "author_id": 8410477, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410477/" ]
74,176,588
<p>Hello Im working on project using Kotlin (for the first time). My problem is i don't know how to get data &quot;fullname&quot; inside &quot;data&quot; list where one of the data inside the list also getting use for the condition, the name is &quot;Role&quot; to my RecyclerView in my Activity.</p> <p>So i need show list &quot;fullname&quot; inside my RecyclerView where the &quot;Role&quot; is &quot;Patient&quot;.</p> <p>Here is the DataFileRecord:</p> <pre><code>data class DataFileRecord( @field:SerializedName(&quot;total&quot;) val total: Int? = null, @field:SerializedName(&quot;data&quot;) val data: List&lt;DataItem&gt;? = null, @field:SerializedName(&quot;offset&quot;) val offset: Int? = null, @field:SerializedName(&quot;limit&quot;) val limit: Int? = null, @field:SerializedName(&quot;status&quot;) val status: Int? = null ) //get fullname data class DataItem( @field:SerializedName(&quot;updateDate&quot;) val updateDate: String? = null, @field:SerializedName(&quot;departement&quot;) val departement: Departement? = null, @field:SerializedName(&quot;isBlock&quot;) val isBlock: String? = null, @field:SerializedName(&quot;role&quot;) val role: Role? = null, @field:SerializedName(&quot;fullname&quot;) val fullname: String? = null, @field:SerializedName(&quot;id&quot;) val id: String? = null, @field:SerializedName(&quot;username&quot;) val username: String? = null ) //get role = patient data class Role( @field:SerializedName(&quot;name&quot;) val name: String? = null, @field:SerializedName(&quot;id&quot;) val id: String? = null ) data class Departement( @field:SerializedName(&quot;name&quot;) val name: String? = null, @field:SerializedName(&quot;id&quot;) val id: String? = null ) </code></pre> <p>Here is my Adapter:</p> <pre><code>class PatientAdapter(val context: List&lt;DataItem&gt;) : RecyclerView.Adapter&lt;PatientAdapter.MyViewHolder&gt;() { var patientList: List&lt;DataItem&gt; = listOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_patient,parent,false) return MyViewHolder(view) } override fun getItemCount(): Int { return patientList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int){ holder.patientName.text = patientList.get(position).fullname } @SuppressLint(&quot;NotifyDataSetChanged&quot;) fun setPatientListItems(patientList: List&lt;DataItem&gt;){ this.patientList=patientList notifyDataSetChanged() } class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val patientName: TextView = itemView.findViewById(R.id.itemPatientName) } } </code></pre> <p>And here is where i stuck with my Call api in my activity:</p> <pre><code>//this 4 lines are inside oncreate patientRecyclerView.setHasFixedSize(true) linearLayoutManager = LinearLayoutManager(this) patientRecyclerView.layoutManager = linearLayoutManager patientRecyclerView.adapter = recyclerAdapter fun getPatient(apiKey: String, apiSecret: String, token: String){ val retrofit = RetrofitClient.getClient() retrofit.addGetPatient(apiKey,apiSecret,token) .enqueue(object : Callback&lt;DataFileRecord&gt;{ override fun onResponse(call: Call&lt;DataFileRecord&gt;, response: Response&lt;DataFileRecord&gt;) { TODO(&quot;Not yet implemented&quot;) val dataPatient = response.body() if (response.isSuccessful){ ---------------- HERE WHERE I STUCK -------------------- } } override fun onFailure(call: Call&lt;DataFileRecord&gt;, t: Throwable) { TODO(&quot;Not yet implemented&quot;) } }) } </code></pre>
[ { "answer_id": 74176927, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "numpy.sign" }, { "answer_id": 74176984, "author": "ah bon", "author_id": 8410477, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009876/" ]
74,176,597
<p>I've been reading about Pandas and trying to write some simple snippets. I've seen many people asking about the <code>ValueError</code> raised by Pandas but can't figure out how to accomplish the following: I have a simple dataframe:</p> <pre><code>Driver_Name Month/Year Km_driven Salaray 0 Ivaylo_Ivanov Jan/21 2168 3208.64 1 Ivaylo_Ivanov Feb/21 2350 3478.00 2 Ivaylo_Ivanov Mar/21 3126 4626.48 3 Ivaylo_Ivanov Apr/21 2415 3574.20 4 Ivaylo_Ivanov May/21 2115 3130.20 5 Mihail Styanov Jan/21 2678 3963.44 6 Mihail Styanov Feb/21 3185 4713.80 7 Mihail Styanov Mar/21 3280 4854.40 8 Mihail Styanov Apr/21 3012 4457.76 9 Mihail Styanov May/21 2980 4410.40 10 Petar_Petkov Jan/21 2013 2979.24 11 Petar_Petkov Feb/21 2089 3091.72 12 Petar_Petkov Mar/21 2163 3201.24 13 Petar_Petkov Apr/21 2098 3105.04 14 Petar_Petkov May/21 2179 3224.92 15 Ivan_Ivanov Jan/21 2876 4256.48 16 Ivan_Ivanov Feb/21 2900 4292.00 17 Ivan_Ivanov Mar/21 2987 4420.76 18 Ivan_Ivanov Apr/21 3016 4463.68 19 Ivan_Ivanov May/21 2019 2988.12 </code></pre> <p>I would like to have a while loop as follows:</p> <pre><code>while df['Driver_Name']=='Ivaylo_Ivanov': do something </code></pre> <p>I know that <code>df['Driver_Name']=='Ivaylo_Ivanov'</code> returns a boolean series, but why can't the <code>while</code> statement iterate over the boolean?</p>
[ { "answer_id": 74176927, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "numpy.sign" }, { "answer_id": 74176984, "author": "ah bon", "author_id": 8410477, "author_profile...
2022/10/24
[ "https://Stackoverflow.com/questions/74176597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10827421/" ]
74,176,606
<p>Sometimes when joining or matching with dates it does not matter if two dates are only a day or two apart. The most recent example occurred to me while using Quicken financial management software. Something got messed up in my Quicken reconciliation. I now have a table of transactions from Quicken and another table of transactions downloaded from my bank. I made one data.table from the two separate tables using <code>rbindlist</code>. I want to find which transactions have no counterpart in the other table. That would be easy if the dates matched as exactly as the number of dollars and cents. But sometimes the dates are off by 2 OR 3 OR 4 OR 5 days but not by 2 months. Using data.table or base R (or if I really must, tidyverse), how do I allow a match if the dates are only a few days off?</p> <h1>example</h1> <pre><code>rep.exmpl &lt;- data.table(date = as.IDate(c(&quot;2022-10-23&quot;, &quot;2022-10-23&quot;, &quot;2022-10-20&quot;, &quot;2022-10-20&quot;, &quot;2022-10-15&quot;, &quot;2022-10-12&quot;, &quot;2022-10-05&quot;, &quot;2022-10-01&quot;, &quot;2022-09-30&quot;, &quot;2022-08-05&quot;)), amount = c(10.00, 10.00, 1.53, 1.53, 78.00, 78.00, 89.56, 65.01, 65.01, 65.01), source = c(&quot;bank&quot;, &quot;quicken&quot;, &quot;bank&quot;, &quot;quicken&quot;,&quot;bank&quot;, &quot;quicken&quot;, &quot;bank&quot;, &quot;bank&quot;, &quot;quicken&quot;, &quot;quicken&quot;)) rep.exmpl </code></pre> <p>rep.exmpl stands for &quot;reproducible example&quot;.</p> <pre><code> date amount source 1: 2022-10-23 10.00 bank 2: 2022-10-23 10.00 quicken 3: 2022-10-20 1.53 bank 4: 2022-10-20 1.53 quicken 5: 2022-10-15 78.00 bank 6: 2022-10-12 78.00 quicken 7: 2022-10-05 89.56 bank 8: 2022-10-01 65.01 bank 9: 2022-09-30 65.01 quicken 10: 2022-08-05 65.01 quicken </code></pre> <p>I used <code>fsetdiff</code> to see what was in one source but not the other.</p> <pre><code>fsetdiff(x = rep.exmpl[source==&quot;bank&quot;, .(date, amount)], y = rep.exmpl[source==&quot;quicken&quot;, .(date, amount)])# in bank only fsetdiff(x = rep.exmpl[source==&quot;quicken&quot;, .(date, amount)], y = rep.exmpl[source==&quot;bank&quot;, .(date, amount)])# in quicken only </code></pre> <p>Row 5 and 6 should be seen as the same since they are only 3 days apart and hence should not be shown to me as a transaction that appeared in only one source. Row 7 should be shown to me since it only appears in bank. Row 10 should be shown to me since it is clearly a different instance to row 8 and 9 without anything matching it in bank. But that is not what happens. Some of it works but much does not.</p> <h2>In bank only</h2> <pre><code> date amount 1: 2022-10-15 78.00 2: 2022-10-05 89.56 3: 2022-10-01 65.01 </code></pre> <p>Row 1 and 3 should not be shown.</p> <h2>In Quicken only</h2> <pre><code> date amount 1: 2022-10-12 78.00 2: 2022-09-30 65.01 3: 2022-08-05 65.01 </code></pre> <p>Row 1 and 2 should not be shown. Only row 3 should be shown.</p> <p>How would you solve this problem elegantly? I thought of trying to create a couple of columns +/- 7 days in the Quicken table and then using rolling joins (<code>roll = TRUE</code>) or perhaps fast overlap joins (<code>foverlaps</code>). One of my problems is that the fuzzy date match could be backwards or forwards.</p>
[ { "answer_id": 74177064, "author": "Waldi", "author_id": 13513328, "author_profile": "https://Stackoverflow.com/users/13513328", "pm_score": 3, "selected": true, "text": "roll=\"nearest\"" }, { "answer_id": 74206699, "author": "Danielle McCool", "author_id": 2402465, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168139/" ]
74,176,634
<p>How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.</p>
[ { "answer_id": 74177064, "author": "Waldi", "author_id": 13513328, "author_profile": "https://Stackoverflow.com/users/13513328", "pm_score": 3, "selected": true, "text": "roll=\"nearest\"" }, { "answer_id": 74206699, "author": "Danielle McCool", "author_id": 2402465, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20318691/" ]
74,176,655
<p>I'm getting <a href="https://i.stack.imgur.com/4oT6e.png" rel="nofollow noreferrer">weird numbers</a> on my C# sorting algorithm times that I <em>think</em> is caused by python recompiling the code every loop. How can I change this function to compile the C# code once and then execute the same compilation with different command line arguments? Is that even possible? In theory the code should follow a curve similar to the rest of the languages being tested.</p> <pre><code>def runCSharp(debug): for size in range(1000, 10001, 1000): if debug: print(&quot;Beginning to sort&quot;, size, &quot; integers&quot;) # Start the clock tic = time.time() # Run the C# script BubbleSort.cs in the CSharp folder args = ['dotnet', 'run', str(size)] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', cwd=&quot;CSharp&quot;) output, err = p.communicate() if debug: print(output) print(err) print(&quot;C# Bubble Sort finished in %0.6f seconds&quot; % (toc - tic)) toc = time.time() csharpTimes.append(toc-tic) return csharpTimes </code></pre> <p>For completeness's sake, this is my C# code, although it sorts fine and something besides my sort implementation is likely the culprit.</p> <pre><code>using System; using System.IO; class BubbleSort { static void Main(string[] args) { int length; StreamReader reader; if (args.Length &gt; 0) { length = Convert.ToInt32(args[0]); reader = new StreamReader(@&quot;..\numbers.txt&quot;); } else { length = 10000; reader = new StreamReader(@&quot;..\..\..\..\numbers.txt&quot;); } Console.WriteLine(&quot;Sorting {0} numbers (C#)&quot;, length); int[] array = new int[length]; for (int i = 0; i &lt; length; i++) { array[i] = Convert.ToInt32(reader.ReadLine()); } bool sorted = false; while (!sorted) { sorted = true; for (int i = 0; i &lt; length - 1; i++) { if (array[i] &gt; array[i + 1]) { int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; sorted = false; } } } // Print the first and last ten numbers from the array to the console for (int i = 0; i &lt; 10; i++) { Console.WriteLine(array[i]); } for (int i = length - 10; i &lt; length; i++) { Console.WriteLine(array[i]); } } } </code></pre>
[ { "answer_id": 74177064, "author": "Waldi", "author_id": 13513328, "author_profile": "https://Stackoverflow.com/users/13513328", "pm_score": 3, "selected": true, "text": "roll=\"nearest\"" }, { "answer_id": 74206699, "author": "Danielle McCool", "author_id": 2402465, ...
2022/10/24
[ "https://Stackoverflow.com/questions/74176655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6811697/" ]
74,176,663
<p>I have a function with five variables that I want to maximize using only an specific set of parameters for each variable.</p> <p>Are there any methods in R that can do this, other than by brutal force? (e.g. Particle Swarm Optimization, Genetic Algorithm, Greedy, etc.). I have read a few packages but they seem to create their own set of parameters from within a given range. I am only interested in optimizing the set of options provided.</p> <p>Here is a simplified version of the problem:</p> <pre><code>#Example of 5 variable function to optimize Fn&lt;-function(x){ a=x[1] b=x[2] c=x[3] d=x[4] e=x[5] SUM=a+b+c+d+e return(SUM) } #Parameters for variables to optimize Vars=list( As=c(seq(1.5,3, by = 0.3)), #float Bs=c(1,2), #Binary Cs=c(seq(1,60, by=10)), #Integer Ds=c(seq(60,-60, length.out=5)), #Negtive Es=c(1,2,3) ) #Full combination FullCombn= expand.grid(Vars) Results=data.frame(I=as.numeric(), Sum=as.numeric()) for (i in 1:nrow(FullCombn)){ ParsI=FullCombn[i,] ResultI=Fn(ParsI) Results=rbind(Results,c(I=i,Sum=ResultI)) } #Best iteration (Largest result) Best=Results[Results[, 2] == max(Results[, 2]),] #Best parameters FullCombn[Best$I,] </code></pre>
[ { "answer_id": 74176999, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 0, "selected": false, "text": "GA" }, { "answer_id": 74177749, "author": "Enrico Schumann", "author_id": 7015675, "author_...
2022/10/24
[ "https://Stackoverflow.com/questions/74176663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9813860/" ]