qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,340,785
<p>Does anyone could tell me how to reorder the matrix:</p> <pre><code>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] </code></pre> <p>To:</p> <pre><code>[[15, 10, 5], [14, 9, 4], [13, 8, 3], [12, 7, 2], [11, 6, 1]] </code></pre>
[ { "answer_id": 74340807, "author": "Ann Zen", "author_id": 13552470, "author_profile": "https://Stackoverflow.com/users/13552470", "pm_score": 0, "selected": false, "text": "zip()" }, { "answer_id": 74340834, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 2, "selected": false, "text": "import numpy as np\n\nmatrix = np.array([[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15]])\n\ntransformed_matrix = matrix[::-1].T[::-1]\n\n\n# array([[15, 10, 5],\n# [14, 9, 4],\n# [13, 8, 3],\n# [12, 7, 2],\n# [11, 6, 1]])\n" }, { "answer_id": 74340844, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 3, "selected": true, "text": "numpy" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10237270/" ]
74,340,788
<p>Blazor's <code>NavLink</code> component detects whether the link refers to the current page, and sets the <code>active</code> class.</p> <p>It is customary to also set the <code>aria-current=&quot;page&quot;</code> attribute, when it is part of a menu.</p> <p>Can the component do that somehow? Or could I wrap it in a custom component that does this?</p> <p>I can't find an extension point that easily allows for this: <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.routing.navlink?view=aspnetcore-6.0" rel="nofollow noreferrer">docs</a>, <a href="https://github.com/dotnet/aspnetcore/blob/ce78832442d91ca307ca8366bafdc9003ea46bc9/src/Components/Web/src/Routing/NavLink.cs" rel="nofollow noreferrer">source</a>.</p>
[ { "answer_id": 74341026, "author": "Kevon", "author_id": 766684, "author_profile": "https://Stackoverflow.com/users/766684", "pm_score": 0, "selected": false, "text": "aria-current=\"@(route == nav route) ? \"page\" : \"\" \")\n" }, { "answer_id": 74341289, "author": "lonix", "author_id": 9971404, "author_profile": "https://Stackoverflow.com/users/9971404", "pm_score": 1, "selected": false, "text": "AriaNavLink.razor" }, { "answer_id": 74341302, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 3, "selected": true, "text": "NavLink" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9971404/" ]
74,340,809
<pre><code>create table Attributes ( id int, AttributeName nvarchar(255), AttributeValue nvarchar(255) ) insert into Attributes values (1, 'BuiltNo', '001') ,(1, 'ManagerName', 'x') ,(1, 'PlantAddress', 'NY') ,(2, 'BuiltNo', '002') ,(2, 'ManagerName', 'y') ,(2, 'PlantAddress', 'NSW') ,(3, 'BuiltNo', '003') ,(3, 'ManagerName', 'z') ,(3, 'PlantAddress', 'QLD') </code></pre> <p><a href="https://i.stack.imgur.com/48tL9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/48tL9.png" alt="enter image description here" /></a></p> <p>I want to update <code>BuiltNo</code>, <code>ManagerName</code> and <code>PlantAddress</code> where <code>id = 1</code> in a single update query. Apparently we can not have 2 <code>where</code> conditions in the same query hence looking for different solution.</p> <pre><code>update Attributes set AttributeValue = '*001' where AttributeName = 'BuiltNo' , set AttributeValue = '*UpdatedValue' where AttributeName = 'ManagerName' where id = 1 </code></pre>
[ { "answer_id": 74340910, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 0, "selected": false, "text": "Declare @I int = 1\nDeclare @J varchar(max) = '{\"BuiltNo\":\"*001\",\"ManagerName\":\"*UpdatedValue\" }'\n\n\nUpdate A\n set AttributeValue =B.Value\n From Attributes A\n Join ( Select * from openjson(@J) ) B\n On A.id=@I and A.AttributeName=B.[key] collate SQL_Latin1_General_CP1_CI_AS\n" }, { "answer_id": 74340946, "author": "AlwaysLearning", "author_id": 390122, "author_profile": "https://Stackoverflow.com/users/390122", "pm_score": 1, "selected": false, "text": "join" }, { "answer_id": 74341733, "author": "WandererAboveTheSea", "author_id": 9680817, "author_profile": "https://Stackoverflow.com/users/9680817", "pm_score": 0, "selected": false, "text": "case when" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1225616/" ]
74,340,845
<p>I'm creating a chrome extension (not for new tab) and want to auto play a muted video every time the user goes to a specific website.</p> <p>I attempted to try it out in <a href="https://codepen.io/i-empty/pen/qBKaMRd" rel="nofollow noreferrer">CodePen</a> and it's still not playing the video.</p> <pre><code>// Video BG let videoContainer = document.createElement(&quot;video&quot;); videoContainer.id = &quot;video&quot;; videoContainer.style.backgroundColor = &quot;rgba(236,55,55,.5)&quot;; videoContainer.style.zIndex = &quot;-1&quot;; videoContainer.style.width = &quot;100%&quot;; videoContainer.style.height = &quot;100vw&quot;; videoContainer.style.marginTop = &quot;50x&quot;; videoContainer.style.position = &quot;fixed&quot;; videoContainer.style.top = &quot;0&quot;; videoContainer.src = &quot;https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&amp;f=1&amp;nofb=1&amp;ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&amp;ipo=images&quot;; //videoContainer.type = &quot;video/mp4&quot;; videoContainer.muted = true; videoContainer.autoplay = true; videoContainer.loop = true; videoContainer.controls = false; document.body.append(videoContainer); </code></pre> <p>I'm pretty new to coding by the way. Thanks to all who can help.</p>
[ { "answer_id": 74340900, "author": "Gonzalo Cugiani", "author_id": 20149906, "author_profile": "https://Stackoverflow.com/users/20149906", "pm_score": 1, "selected": false, "text": "play()" }, { "answer_id": 74350761, "author": "Empty", "author_id": 20435771, "author_profile": "https://Stackoverflow.com/users/20435771", "pm_score": 0, "selected": false, "text": "videoContainer.src = \"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images\";\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20435771/" ]
74,340,857
<p>I am relatively new to javascript and am trying to get the last line of text in a a textarea on a key press. Is this possible? My code is below.</p> <pre class="lang-js prettyprint-override"><code> const textarea = document.getElementById('textarea'); textarea.addEventListener(&quot;keydown&quot;, (event) =&gt; { if (event.code != 13) { return &quot;Enter key was not pressed&quot; } else if(event.code === 13) { //Do what my question is asking } }); </code></pre> <p>I have tried to get the innerHTML property and the value property of the textarea but that returned the full contents of the textarea, not the last line which is what I need.</p> <pre><code>const textarea = document.getElementById('textarea'); //First thing I tried let content = textarea.innerHTML; console.log(content); //Second thing I tried let content2 = textarea.value; console.log(content2); </code></pre>
[ { "answer_id": 74340900, "author": "Gonzalo Cugiani", "author_id": 20149906, "author_profile": "https://Stackoverflow.com/users/20149906", "pm_score": 1, "selected": false, "text": "play()" }, { "answer_id": 74350761, "author": "Empty", "author_id": 20435771, "author_profile": "https://Stackoverflow.com/users/20435771", "pm_score": 0, "selected": false, "text": "videoContainer.src = \"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images\";\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20140332/" ]
74,340,907
<p>I've Asset Codes which I'm converting into BASE64 like this:</p> <pre><code>private string GenerateBarcode(string BarCode) { string generatebarcode = BarCode; GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(generatebarcode, BarcodeWriterEncoding.Code128); barcode.ResizeTo(400, 120); barcode.SetMargins(10); barcode.ChangeBarCodeColor(Color.Black); Image MyBarCodeImage = barcode.Image; var myArray = (byte[])new ImageConverter().ConvertTo(MyBarCodeImage, typeof(byte[])); string temp_inBase64 = Convert.ToBase64String(myArray); return temp_inBase64; } </code></pre> <p>And after this, I'm saving this BASE64 into my database.</p> <p>Now, getting this into my Dataset, showing in tabular form.</p> <p>At the RDLC level, I've tried:</p> <ul> <li>Drop an Image report control from toolbox.</li> <li>Right click on the image and choose image properties</li> <li>Set the image source to database</li> <li>Set the MIME type to a suitable value, for example image/bmp.</li> <li>Set use this field to the image value which you have,</li> </ul> <p>For example <code>=Fields!Code.Value</code>. The parameter type should be Text.</p> <p>But it's not showing anything in the RDLC Report Viewer.</p> <p>I've found many solutions on the internet but none of them seems works to me. Is there something that I missed?</p> <p>I use Visual Studio 2019 Community, .NET Framework 4.7.2, <code>Microsoft.ReportViewer.WebForms</code> 15.0.0.0</p> <p>Thanks.</p>
[ { "answer_id": 74340900, "author": "Gonzalo Cugiani", "author_id": 20149906, "author_profile": "https://Stackoverflow.com/users/20149906", "pm_score": 1, "selected": false, "text": "play()" }, { "answer_id": 74350761, "author": "Empty", "author_id": 20435771, "author_profile": "https://Stackoverflow.com/users/20435771", "pm_score": 0, "selected": false, "text": "videoContainer.src = \"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images\";\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8874788/" ]
74,340,913
<p>I am working on a project with a React front-end and a Laravel back-end. I am trying to set up my authentication system. I am utilizing SPA authentication using Sanctum. I am successfully utilizing the sanctum/csrf-cookie route, where the XSRF-Token cookie is given. When I then try to follow that up with a login, I get a 419 error, CSRF token mismatch. There is no XSRF-Token. What is interesting is that if I do a get request, as in the 'testing' route below, the XSRF cookie is present. However, when I do a post request, as in posting to the login route, the cookie is not present and I get a 419 error.</p> <p>I am running this locally right now. The front-end is running at localhost:3000, with the back-end running at localhost:8888. Here are various relevant segments of code.</p> <p><strong>LoginForm.js</strong></p> <pre><code>let data = { email: e.target[0].value, password: e.target[1].value } axios.get('http://localhost:8888/sanctum/csrf-cookie') .then((res) =&gt; { axios.post('http://localhost:8888/login', data) .then((res) =&gt; { axios.get('http://localhost:8888/user') }) }) </code></pre> <p><strong>Kernel.php</strong></p> <pre><code>protected $middleware = [ \App\Http\Middleware\TrustProxies::class, \Fruitcake\Cors\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; protected $middlewareGroups = [ 'web' =&gt; [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\HandleInertiaRequests::class, ], 'api' =&gt; [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; protected $routeMiddleware = [ 'auth' =&gt; \App\Http\Middleware\Authenticate::class, 'auth.basic' =&gt; \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'cache.headers' =&gt; \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' =&gt; \Illuminate\Auth\Middleware\Authorize::class, 'guest' =&gt; \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' =&gt; \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' =&gt; \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' =&gt; \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' =&gt; \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, ]; </code></pre> <p><strong>.env</strong></p> <pre><code>SESSION_DRIVER=cookie CLIENT_URL=http://localhost:3000 SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=http://localhost:3000 </code></pre> <p><strong>Bootstrap.js</strong></p> <pre><code>axios = require('axios'); axios.defaults.headers.common['Accept'] = 'application/json'; axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; axios.defaults.withCredentials = true; </code></pre> <p><strong>Web.php</strong></p> <pre><code>Route::get('/testing', function () { return &quot;Testing.&quot;; }); Route::post('/login', function(Request $request) { $credentials = $request-&gt;validate([ 'email' =&gt; ['required', 'email'], 'password' =&gt; ['required'], ]); if (Auth::attempt($credentials)) { $request-&gt;session()-&gt;regenerate(); $id = Auth::id(); $user = User::find($id); return $user; } return back()-&gt;withErrors([ 'email' =&gt; 'The provided credentials do not match our records.', ]); }); </code></pre> <p><strong>Sanctum.php</strong></p> <pre><code>'stateful' =&gt; explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( '%s%s', 'localhost,localhost:3000,localhost:8888, Sanctum::currentApplicationUrlWithPort() ))), </code></pre> <p><strong>Cors.php</strong></p> <pre><code>'paths' =&gt; [ 'api/*', 'sanctum/csrf-cookie', 'login', 'logout', 'register', 'user/password', 'forgot-password', 'reset-password', 'user/profile-information', 'email/verification-notification', 'testing', 'user', 'checkAuth' ], 'allowed_methods' =&gt; ['*'], 'allowed_origins' =&gt; [env('CLIENT_URL')], 'allowed_origins_patterns' =&gt; [], 'allowed_headers' =&gt; ['*'], 'exposed_headers' =&gt; [], 'max_age' =&gt; 0, 'supports_credentials' =&gt; true, </code></pre>
[ { "answer_id": 74340900, "author": "Gonzalo Cugiani", "author_id": 20149906, "author_profile": "https://Stackoverflow.com/users/20149906", "pm_score": 1, "selected": false, "text": "play()" }, { "answer_id": 74350761, "author": "Empty", "author_id": 20435771, "author_profile": "https://Stackoverflow.com/users/20435771", "pm_score": 0, "selected": false, "text": "videoContainer.src = \"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F6f%2F8a%2F7d%2F6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images\";\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16895460/" ]
74,340,917
<p>I keep getting a compilation error if I use an array passed as parameter to a method on std::begin or std::end such as this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; class Test { public: static bool exists(int ints[], int size, int k) { if (std::find(std::begin(ints), std::end(ints), k) != std::end(ints)) { return true; } return false; } }; </code></pre> <p>I tried casting it to &amp;int[0] but it will still not compile.</p>
[ { "answer_id": 74340975, "author": "guivi", "author_id": 1856251, "author_profile": "https://Stackoverflow.com/users/1856251", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\nbool exists(int x[], const int size, const int k)\n{\n std::vector<int> v(x, x + size);\n if (std::find( v.begin(), v.end(), k) != v.end()) {\n return true;\n }\n return false;\n}\nint main()\n{\n int const sz = 10;\n int arrayi[sz] = { 1, 2, 3,4 ,5 ,6 ,7 , 8, 9, 0 };\n if (exists(arrayi, sz, 4))\n std::cout << \"exist\" << std::endl;\n else\n std::cout << \"it does not\" << std::endl;\n}\n" }, { "answer_id": 74340980, "author": "eerorika", "author_id": 2079303, "author_profile": "https://Stackoverflow.com/users/2079303", "pm_score": 2, "selected": false, "text": "ints" }, { "answer_id": 74341023, "author": "Marco Maia", "author_id": 4723737, "author_profile": "https://Stackoverflow.com/users/4723737", "pm_score": 0, "selected": false, "text": "std::span" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235055/" ]
74,340,957
<p>I'm trying to get the cassandra schema version into variable from output of nodetool command.</p> <p>Here are some of the output of nodetool commands:</p> <pre><code>Cluster Information: Name: Test Cluster Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch Partitioner: org.apache.cassandra.dht.Murmur3Partitioner Schema versions: 65e78f0e-e81e-30d8-a631-a65dff93bf82: [127.0.0.1] </code></pre> <p>When few nodes are not reachable here's the output.</p> <pre><code>Cluster Information: Name: Production Cluster Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch Partitioner: org.apache.cassandra.dht.Murmur3Partitioner Schema versions: UNREACHABLE: 1176b7ac-8993-395d-85fd-41b89ef49fbb: [10.202.205.203] </code></pre> <p>Can anyone suggest how to get schema version into variable irrespective of reachable or not?</p> <p>Tried to use awk and grep commands but didn't work because of unreachable.</p>
[ { "answer_id": 74341111, "author": "Dr Claw", "author_id": 12962618, "author_profile": "https://Stackoverflow.com/users/12962618", "pm_score": 0, "selected": false, "text": "version=$(awk '/Schema versions:/ {\n getline\n gsub(/:/,\"\")\n if ($1 == \"UNREACHABLE\") {\n print $2\n } else {\n print $1\n }\n}' < <(nodetool_cmd)) # remplace \"nodetool_cmd\" by the correct command\n\n$ echo \"$version\" #when reachable\n65e78f0e-e81e-30d8-a631-a65dff93bf82\n\n$ echo \"$version\" # when unreachable\n1176b7ac-8993-395d-85fd-41b89ef49fbb\n\n# or in single line:\n\nversion=$(awk '/version/ {getline;gsub(/:/,\"\");if ($1 == \"UNREACHABLE\") {print $2} else {print $1}}' < <(nodetool_cmd))\n" }, { "answer_id": 74341128, "author": "David C. Rankin", "author_id": 3422102, "author_profile": "https://Stackoverflow.com/users/3422102", "pm_score": 1, "selected": false, "text": "awk" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12189187/" ]
74,340,962
<p>I have a widget in my settings screen something like this:</p> <pre><code>Widget autoplay() { return ChangeNotifierProvider&lt;AutoplayToggle&gt;( create: (context) =&gt; AutoplayToggle(), child: Consumer&lt;AutoplayToggle&gt;( builder: (context, provider, child) { return Container( color: provider.isPause ? accent : primary, width: 45, child: Switch.adaptive( value: isPause, onChanged: (value) async { setState(() { isPause= value; }); await UserPrefs.setAutoplay(isPause); provider.toggleAutoplay(); }, ), ); }, ), ), } </code></pre> <p>and this is my class:</p> <pre><code>class AutoplayToggle with ChangeNotifier{ bool isPause = false; void toggleAutoplay() { isPause = !isPause; print(isPause); notifyListeners(); } } </code></pre> <p>I printed couple of statements to debug and every time I toggle the switch the function is being called as the values will change from false to true, however, it is not notifying the change. Any idea on whats going wrong?</p>
[ { "answer_id": 74341111, "author": "Dr Claw", "author_id": 12962618, "author_profile": "https://Stackoverflow.com/users/12962618", "pm_score": 0, "selected": false, "text": "version=$(awk '/Schema versions:/ {\n getline\n gsub(/:/,\"\")\n if ($1 == \"UNREACHABLE\") {\n print $2\n } else {\n print $1\n }\n}' < <(nodetool_cmd)) # remplace \"nodetool_cmd\" by the correct command\n\n$ echo \"$version\" #when reachable\n65e78f0e-e81e-30d8-a631-a65dff93bf82\n\n$ echo \"$version\" # when unreachable\n1176b7ac-8993-395d-85fd-41b89ef49fbb\n\n# or in single line:\n\nversion=$(awk '/version/ {getline;gsub(/:/,\"\");if ($1 == \"UNREACHABLE\") {print $2} else {print $1}}' < <(nodetool_cmd))\n" }, { "answer_id": 74341128, "author": "David C. Rankin", "author_id": 3422102, "author_profile": "https://Stackoverflow.com/users/3422102", "pm_score": 1, "selected": false, "text": "awk" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20026121/" ]
74,340,992
<p>Currently developing a REST API, with a suite of endpoint functions which update the &quot;state&quot; of a particular resource.</p> <p>I am using POST to create the initial resource and then updating the state using PUT - Is PUT the correct method to be using?</p> <p>The state updates are being logged in a journal, so to avoid someone updating the state with the same value multiple times, I wish to put some business logic in that avoid two repeat entries of the same state. If someone attempts to call the same function twice, lets say &quot;CancelResource()&quot; - should I return a 200 success on the second call, and just not make an update, or would it be better to send some sort of error response?</p> <p>I was considering returning a 405 &quot;method not allowed&quot; but this feels a little <em>harsh</em>. I also don't know that 200 would be very useful for the client.</p>
[ { "answer_id": 74341134, "author": "Evert", "author_id": 80911, "author_profile": "https://Stackoverflow.com/users/80911", "pm_score": 1, "selected": false, "text": "PUT" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913298/" ]
74,340,996
<p>I am trying to migrate my map here over to using getx state management. How do I convert the setstate() portion? I want to use a stateless widget. I have a separate view and controller.</p> <p>This my MapPage code here. It is still a stateful widget as I could not figure out how to address the setstate portion in my getx LocationController. Basically I need to show the LoadScreen while the GoogleMap loads.</p> <pre><code>class MapsPage2 extends StatelessWidget { final GoogleMapController _googleMapController = Get.put(GoogleMapController()); @override Widget build(BuildContext context) { return Scaffold( body: Obx( () =&gt; locationController.currentLatLng == null ? LoadScreen() : Stack( children: [ Container( child: GoogleMap( initialCameraPosition: CameraPosition( //get user location target: locationController.currentLatLng!, zoom: 16), minMaxZoomPreference: MinMaxZoomPreference(15.5, 19), zoomGesturesEnabled: true, cameraTargetBounds: CameraTargetBounds( LatLngBounds( northeast: LatLng(43.7970928, -79.3067414), southwest: LatLng(43.592580, -79.483674), ), ), ), ), ], ), )); } } </code></pre> <p>How will I need to edit my location controller?</p> <pre><code>class LocationController extends GetxController { static LocationController instance = Get.find(); Position? myLocation; Rx&lt;Geolocator&gt;? geolocator = Geolocator().obs; LatLng? currentLatLng; RxBool isLoading = false.obs; @override void onInit() async { super.onInit(); getpermission(); } getpermission() async { bool serviceEnabled; LocationPermission permission; serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { await Geolocator.openLocationSettings(); return Future.error(&quot;location service is not enabled&quot;); } permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { //do stuff here permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { //stuff return Future.error(&quot;location permissions denied&quot;); } } if (permission == LocationPermission.deniedForever) { return Future.error(&quot;location permissions permanently denied&quot;); } myLocation = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); } //next func here } </code></pre> <p>And this is the error I am currently getting in terminal:</p> <pre><code>The following message was thrown building Obx(has builder, dirty, state: _ObxState#66e23): [Get] the improper use of a GetX has been detected. You should only use GetX or Obx for the specific widget that will be updated. If you are seeing this error, you probably did not insert any observable variables into GetX/Obx or insert them outside the scope that GetX considers suitable for an update (example: GetX =&gt; HeavyWidget =&gt; variableObservable). If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. The relevant error-causing widget was: Obx Obx:file:///Users/juliapak/Documents/my%20programs/coffeesoc/lib/pages/mapview_page.da rt:16:15 </code></pre>
[ { "answer_id": 74341134, "author": "Evert", "author_id": 80911, "author_profile": "https://Stackoverflow.com/users/80911", "pm_score": 1, "selected": false, "text": "PUT" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74340996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156469/" ]
74,341,024
<pre><code># Program to display the Fibonacci sequence up to n-th term nterms = int(input(&quot;How many Fibonacci numbers would you like to generate? &quot;)) # first two terms n1, n2 = 1, 1 count = 0 # check if the number of terms is valid if nterms == 0: print(f'The first 0 Fibonacci numbers are [].') elif nterms == 1: print(f'The first 1 Fibonacci numbers are [1].') elif nterms == 2: print(f'The first 2 Fibonacci numbers are [1, 1].') # if there is only one term, return n1 # generate fibonacci sequence else: print(f&quot;The first {nterms} Fibonacci numbers are &quot;, end = '') while count &lt; nterms: print(*n1, sep=', ') nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 </code></pre> <p>input: <code>10</code></p> <p>expected output: <code>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]</code></p> <p>my output: <code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55,</code></p>
[ { "answer_id": 74341134, "author": "Evert", "author_id": 80911, "author_profile": "https://Stackoverflow.com/users/80911", "pm_score": 1, "selected": false, "text": "PUT" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20429919/" ]
74,341,033
<p>I have an excel file with one row and 11000 columns. It's a 1x11000 matrix. I want to convert it to rows with 17 columns (n x 17 matrices). What should I do? Thanks in advance.</p> <p>As of yet, I haven't found a solution.</p>
[ { "answer_id": 74348871, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Sub SingleRowToRows()\n \n Const SOURCE_WORKSHEET_NAME As String = \"Sheet1\"\n Const SOURCE_FIRST_CELL_ADDRESS As String = \"A1\"\n Const SOURCE_COLUMNS_COUNT As Long = 10\n \n Const DEST_WORKSHEET_NAME As String = \"Sheet1\"\n Const DEST_FIRST_CELL_ADDRESS As String = \"A3\"\n Const DEST_COLUMNS_COUNT As Long = 3\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n Dim sws As Worksheet: Set sws = wb.Worksheets(SOURCE_WORKSHEET_NAME)\n Dim sfCell As Range: Set sfCell = sws.Range(SOURCE_FIRST_CELL_ADDRESS)\n Dim srg As Range: Set srg = sfCell.Resize(, SOURCE_COLUMNS_COUNT)\n Dim sData() As Variant: sData = srg.Value\n \n Dim drCount As Long\n drCount = Int(SOURCE_COLUMNS_COUNT / DEST_COLUMNS_COUNT)\n \n Dim Remainder As Long\n Remainder = SOURCE_COLUMNS_COUNT Mod DEST_COLUMNS_COUNT\n \n If Remainder > 0 Then drCount = drCount + 1\n \n Dim dData() As Variant\n ReDim dData(1 To drCount, 1 To DEST_COLUMNS_COUNT)\n \n Dim dr As Long: dr = 1\n \n Dim sc As Long\n Dim dc As Long\n \n For sc = 1 To SOURCE_COLUMNS_COUNT\n \n If dc < DEST_COLUMNS_COUNT Then\n dc = dc + 1\n Else\n dr = dr + 1\n dc = 1\n End If\n \n dData(dr, dc) = sData(1, sc)\n \n Next sc\n \n Dim dws As Worksheet: Set dws = wb.Worksheets(DEST_WORKSHEET_NAME)\n Dim dfCell As Range: Set dfCell = dws.Range(DEST_FIRST_CELL_ADDRESS)\n Dim drg As Range: Set drg = dfCell.Resize(drCount, DEST_COLUMNS_COUNT)\n \n drg.Value = dData\n \nEnd Sub\n" }, { "answer_id": 74355791, "author": "ASH", "author_id": 5212614, "author_profile": "https://Stackoverflow.com/users/5212614", "pm_score": 0, "selected": false, "text": "Public Sub TransposeData()\n\n Dim xLRow As Long\n Dim xNRow As Long\n Dim i As Long\n Dim xUpdate As Boolean\n Dim xRg As Range\n Dim xOutRg As Range\n Dim xTxt As String\n On Error Resume Next\n xTxt = ActiveWindow.RangeSelection.Address\n Set xRg = Application.InputBox(\"Please select data range(only one column):\", \"Excel\", xTxt, , , , , 8)\n Set xRg = Application.Intersect(xRg, xRg.Worksheet.UsedRange)\n If xRg Is Nothing Then Exit Sub\n\n Set xOutRg = Application.InputBox(\"please select output range(specify one cell):\", \"Excel\", xTxt, , , , , 8)\n If xOutRg Is Nothing Then Exit Sub\n Set xOutRg = xOutRg.Range(1)\n xUpdate = Application.ScreenUpdating\n Application.ScreenUpdating = False\n xLCol = xRg.Columns.Count\n xNRow = 3\n xNCol = 1\n For i = 1 To xLCol Step 17\n xRg.Cells(i).Resize(1, 17).Copy\n xOutRg.Offset(xNRow, xNCol).PasteSpecial Paste:=xlPasteAll, Transpose:=True\n xNCol = xNCol + 1\n Next\n Application.ScreenUpdating = xUpdate\n \nEnd Sub\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20435870/" ]
74,341,077
<p>I want to access my server from an other instance, which is also within the same VPC, but my security group configuration does not allow me to do so.</p> <p>My security inbound rule as follows</p> <pre><code>Port range | Protocol | Source 22 | TCP | 10.0.0.0/8 </code></pre> <ul> <li>telnet private-ip 22 -&gt; works fine</li> <li>telnet public-ip 22 -&gt; does not work - I need to open 0.0.0.0/0 to be able to get it working, which I don't want to</li> </ul> <p>I get it. I don't open the port for public, but since these two are in the same network, aren't they supposed to be communicating? If you guys shed some light into it, I'd appreciate it.</p> <p>Thanks!</p>
[ { "answer_id": 74341087, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "0.0.0.0/0" }, { "answer_id": 74341329, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "10.x" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15500282/" ]
74,341,091
<p>I have the next <code>TabView</code>:</p> <pre><code>TabView(selection: self.$viewModel.selection) { StoriesView() .tabItem { Label(&quot;Stories&quot;, systemImage: &quot;play.square&quot;) // I need a yellow icon here } .tag(&quot;stories&quot;) MessengerView() .tabItem { Label(&quot;Messenger&quot;, systemImage: &quot;message&quot;) // I need a green icon here } .tag(&quot;messenger&quot;) ProfileView() .tabItem { Label(&quot;Profile&quot;, systemImage: &quot;person&quot;) // I need a red icon here } .tag(&quot;profile&quot;) } </code></pre> <p>It works perfectly but I can't get how to set an own colour for every tab icon. I've tried all possible methods already <code>foregroundColor()</code>, <code>accentColor()</code>, <code>tint()</code> and so on... A nothing works. It changes a color of all tab icons or no one icon.</p> <p>How to make it in <code>TabView</code>?</p> <p><strong>P.S.</strong> Maybe it's a noobie's question but I really got challenged.</p>
[ { "answer_id": 74341087, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "0.0.0.0/0" }, { "answer_id": 74341329, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "10.x" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3253896/" ]
74,341,093
<p>I have a VideoPlayer component with crop functionality that's not working well after migration to functional over class component.</p> <p>The VideoPlayer has a isVideoPlaying state (useState). It also contains a function toggleOrChangeIsVideoPlaying:</p> <pre><code>const togglePlayPauseVideo = (toPlay) =&gt; { if (toPlay !== undefined) { if (toPlay) { playVideo() } else { pauseVideo() } } else { if (!isVideoPlaying) { playVideo() } else { pauseVideo() } } } </code></pre> <p>It renders:</p> <pre><code>&lt;div&gt; &lt;Crop onPlayPauseVideo={togglePlayPauseVideo} ...restofTheProps&gt; &lt;Video ...someProps /&gt; &lt;/Crop&gt; &lt;/div&gt; </code></pre> <p>Using useEffect &amp; console.log() I verified that 'togglePlayPauseVideo' function is changing (and causing a bug), probably because VideoPlayer is re-rendered.</p> <p>I've tried wrapping 'togglePlayPauseVideo' with useCallback. The problem is that it must have 'isVideoPlaying' state as a dependency (otherwise there's another bug), but when it does, it changes again more than it should.</p> <p>Any ideas how to break this cycle?</p> <p>BTW 1: 'isVideoPlaying' state is needed to keep track of the actual element state, that changes in playVideo() and pauseVideo() via ref.</p> <p>BTW 2: VideoPlayer worked ok when it was a class component.</p>
[ { "answer_id": 74341087, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "0.0.0.0/0" }, { "answer_id": 74341329, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "10.x" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6137045/" ]
74,341,112
<p>How do i make sure that when ever the user enter a number less than 0 or more than 300 it asks them to try again. I have trouble with the code. My code works on the first score but the rest it keeps accepting values greater than 300 and less than 0. How would i be able to fix this issue without changing a big part of my code?</p> <pre><code>#Kenneth Sodjahin #November 4th 2022 #defining where low,high,total score start from #defining where couter starts Low=0 High=0 Counter=0 Total=0 #while loop to check if the numbers are numbers #if the user wants to quit they press q #if the Scores are greater than 300 or less than 0 #or if the user presses q, it prints them the highest score,lowest score, counter,and their total score while True: #the code will try these try: #asks user to enter their score Score1=int(input(&quot;Enter your 1st score:&quot;)) if (Score1 &gt; 300) or (Score1 &lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 1&quot;) exit() Score2=int(input(&quot;Enter your 2nd score:&quot;)) if ((Score1 or Score2)&gt; 300) or ((Score1 or Score2)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 2&quot;) exit() Score3=int(input(&quot;Enter your 3rd score:&quot;)) if ((Score1 or Score2 or Score3)&gt; 300) or ((Score1 or Score2 or Score3)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 3&quot;) exit() Score4=int(input(&quot;Enter your 4th score from:&quot;)) if ((Score1 or Score2 or Score3 or Score4)&gt; 300) or ((Score1 or Score2 or Score3 or Score4)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 4&quot;) exit() Score5=int(input(&quot;Enter your 5th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4,Score5] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4+Score5 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 5&quot;) exit() Score6=int(input(&quot;Enter your 6th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4,Score5,Score6] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4+Score5+Score6 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 6&quot;) exit() Score7=int(input(&quot;Enter your 7th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4,Score5,Score6,Score7] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4+Score5+Score6+Score7 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 7&quot;) exit() Score8=int(input(&quot;Enter your 8th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4,Score5,Score6,Score7,Score8] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4+Score5+Score6+Score7+Score8 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 8&quot;) exit() Score9=int(input(&quot;Enter your 9th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue Quit=input(&quot;Enter q to quit or press ENTER to continue:&quot;) if Quit=='q': ScoreList=[Score1,Score2,Score3,Score4,Score5,Score6,Score7,Score8,Score9] #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) Total=Total+Score1+Score2+Score3+Score4+Score5+Score6+Score7+Score8+Score9 print(&quot;High Score is:&quot;,High) print(&quot;Low Score is:&quot;,Low) print(&quot;Total Score is:&quot;,Total) print(&quot;Counter is 9&quot;) exit() Score10=int(input(&quot;Enter your 10th score:&quot;)) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) continue #list of all the score variables ScoreList=[Score1,Score2,Score3,Score4,Score5,Score6,Score7,Score8,Score9,Score10] #total of the scores Total=Total+(Score1+Score2+Score3+Score4+Score5+Score6+Score7+Score8+Score9+Score10) #highest score High = max(ScoreList) #lowest score Low = min(ScoreList) if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&lt; 0): print(&quot;Please enter a Number from 0 and 300 included!&quot;) #catches letter in input errors except ValueError: print('''Sorry, I didn't understand that...Please enter a NUMBER. Try again!''') #if ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&gt; 300) or ((Score1 or Score2 or Score3 or Score4 or Score5 or Score6 or Score7 or Score8 or Score9 or Score10)&lt; 0): #print(&quot;Please enter a Number from 0 and 300 included!&quot;) #better try again... Return to the start of the loop continue else: #we're ready to exit the loop. break </code></pre>
[ { "answer_id": 74341087, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "0.0.0.0/0" }, { "answer_id": 74341329, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "10.x" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20353478/" ]
74,341,130
<p>I need a JavaScript function that allows to select only two divs out of several and insert them respectively into others. My code has 15 .item and 4 .item2. I'm developing an app that generates essay templates. The .item are keyword arguments that need to be included in a predicate structure (class .item2, which has 2 .main_place divs - it takes 2 arguments out of 15). I would like to create a function where the button to insert some .item in the .main_place is the .item itself, so that the user can define the order of presentation of arguments in the predicate based on what he selected.</p> <pre><code>&lt;div class=&quot;item&quot; id=&quot;arg1&quot;&gt;first block&lt;/div&gt; &lt;div class=&quot;item&quot; id=&quot;arg2&quot;&gt;second block&lt;/div&gt; &lt;div class=&quot;item&quot; id=&quot;arg3&quot;&gt;third block&lt;/div&gt; &lt;div class=&quot;item2&quot;&gt;put the first block &lt;div class=&quot;main_place&quot;&gt;here&lt;/div&gt; and the second one &lt;div class=&quot;main_place&quot;&gt;here&lt;/div&gt;.&lt;/div&gt; </code></pre> <p>I saw a solution here on stackoverflow (<a href="https://stackoverflow.com/questions/37347690/how-to-replace-div-with-another-div-in-javascript">How to replace div with another div in javascript?</a>), but it doesn't solve my problem. btw if I have to create a button, I would like the item div itself to be one</p> <pre><code>function show(param_div_id) { document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).innerHTML; } </code></pre>
[ { "answer_id": 74341087, "author": "Marcin", "author_id": 248823, "author_profile": "https://Stackoverflow.com/users/248823", "pm_score": 2, "selected": false, "text": "0.0.0.0/0" }, { "answer_id": 74341329, "author": "John Rotenstein", "author_id": 174777, "author_profile": "https://Stackoverflow.com/users/174777", "pm_score": 1, "selected": false, "text": "10.x" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434402/" ]
74,341,139
<p>I have an image that I read in with <code>tifffile.imread</code> and it is turned into a 3D matrix, with the first dimension representing the Y coordinate, the second the X and the third the channel of the image (these images are not RGB and so there can be an arbitrary number of channels).</p> <p>Each of these images has a label mask which is a 2D array that indicates the position of objects in the image. In the label mask, pixels that have a value of 0 do not belong to any object, pixels that have a value of 1 belong to the first object, pixels that have a value of 2 belong to the second object and so on.</p> <p>What I would like to calculate is for each object and for each channel of the image I would like to know the mean, median, std, min and max of the channel. So, for example, I would like to know the mean, mediam std, min and max values of the first channel for pixels in object 10.</p> <p>I have written code to do this but it is very slow (shown below) and I wondered if people had a better way or knew a package(s) that might be helpful i making this faster/doing this more efficiently. (Here the word 'stain' means the same as channel)</p> <pre><code>sample = imread(input_img) label_mask = np.load(input_mask) n_stains = sample.shape[2] n_labels = np.max(label_mask) #Create empty dataframe to store intensity measurements intensity_measurements = pd.DataFrame(columns = ['sample', 'label', 'stain', 'mean', 'median', 'std', 'min', 'max']) for label in range(1, n_labels+1): for stain in range(n_stains): #Extract stain and label stain_label = sample[:,:,stain][label_mask == label] #Calculate intensity measurements mean = np.mean(stain_label) median = np.median(stain_label) std = np.std(stain_label) min = np.min(stain_label) max = np.max(stain_label) #Add intensity measurements to dataframe intensity_measurements = intensity_measurements.append({'sample' : args.input_img, 'label': label, 'stain': stain, 'mean': mean, 'median': median, 'std': std, 'min': min, 'max': max}, ignore_index=True) </code></pre>
[ { "answer_id": 74341746, "author": "Raibek", "author_id": 11040577, "author_profile": "https://Stackoverflow.com/users/11040577", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport numpy.ma as ma\nimport pandas as pd\n\nsample = imread(input_img)\nlabel_mask = np.load(input_mask)\n\nn_labels = np.max(label_mask)\n\n# let's create boolean label masks for each label \n# producing 3D matrix where 1st axis is label\nlabel_mask_unraveled = np.equal.outer(label_mask, np.arange(1, n_labels +1))\n\n# now we can apply these boolean label masks simultaniously\n# to all the sample channels with help of 'einsum' producing 4D matrix, \n# where the 1st axis is channel/stain and the 2nd axis is label\nsample_label_masks_applied = np.einsum(\"ijk,ijl->klij\", sample, label_mask_unraveled)\n\n# in order to exclude the non-selected pixels \n# from meausurement calculations, we mask the pixels first\nnon_selected_pixels_mask = np.moveaxis(~label_mask_unraveled, -1, 0)[np.newaxis, :, :, :]\nnon_selected_pixels_mask = np.repeat(non_selected_pixels_mask, sample.shape[2], axis=0)\n\nsample_label_masks_applied = ma.masked_array(sample_label_masks_applied, non_selected_pixels_mask) \n\n# intensity measurement calculations\n# embedded into pd.DataFrame initialization\nintensity_measurements = pd.DataFrame(\n {\n \"sample\": args.input_img,\n \"label\": sample.shape[2] * list(range(1, n_labels+1)),\n \"stain\": n_labels * list(range(sample.shape[2])),\n \"mean\": ma.mean(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"median\": ma.median(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"std\": ma.std(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"min\": ma.min(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"max\": ma.max(sample_label_masks_applied, axis=(2, 3)).flatten() \n }\n)\n" }, { "answer_id": 74342302, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 1, "selected": false, "text": "import diplib as dip\n\n# sample = imread(input_img)\n# label_mask = np.load(input_mask)\n# Alternative random data so that I can run the code for testing:\nsample = imageio.imread(\"../images/trui_c.tif\")\nlabel_mask = np.random.randint(0, 20, sample.shape[:2], dtype=np.uint32)\n\nsample = dip.Image(sample, tensor_axis=2)\nmsr = dip.MeasurementTool.Measure(label_mask, sample, features=[\"Mean\", \"StandardDeviation\", \"MinVal\", \"MaxVal\"])\nprint(msr)\n" }, { "answer_id": 74546381, "author": "Hugh Warden", "author_id": 13642459, "author_profile": "https://Stackoverflow.com/users/13642459", "pm_score": 1, "selected": true, "text": "import numpy as np\nimport pandas as pd\nfrom skimage.measure import regionprops, regionprops_table\nnp.random.seed(42)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13642459/" ]
74,341,189
<p>I have example python project with multiple files:</p> <p>src/common.py:</p> <pre><code>def toint(x): return int(x) </code></pre> <p>src/foo1.py:</p> <pre><code>import common def add(a,b): return common.toint(a) + common.toint(b) </code></pre> <p>src/foo2.py:</p> <pre><code>import common def sub(a,b): return common.toint(a)-common.toint(b) </code></pre> <p>setup.py:</p> <pre><code>from setuptools import setup setup (name = 'test_py_project', version = '1.0', author='Vladislav Tsendrovskii', description = 'test python modules', package_dir = {'': 'src'} ) </code></pre> <p>Now I want to install this project. I run <code>python3 setup.py install --user</code> and it installs.</p> <p>But it installs not in a way that I want.</p> <p>When I try to use it, I have problems.</p> <p>I can not do <code>import test_py_project.foo1</code></p> <p>But I can do <code>import foo1</code></p> <p>How should I modify my project, to place all stuff inside <code>test_py_project</code> namespace?</p> <p>I have tried to google for solution. But I've failed(</p>
[ { "answer_id": 74341746, "author": "Raibek", "author_id": 11040577, "author_profile": "https://Stackoverflow.com/users/11040577", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport numpy.ma as ma\nimport pandas as pd\n\nsample = imread(input_img)\nlabel_mask = np.load(input_mask)\n\nn_labels = np.max(label_mask)\n\n# let's create boolean label masks for each label \n# producing 3D matrix where 1st axis is label\nlabel_mask_unraveled = np.equal.outer(label_mask, np.arange(1, n_labels +1))\n\n# now we can apply these boolean label masks simultaniously\n# to all the sample channels with help of 'einsum' producing 4D matrix, \n# where the 1st axis is channel/stain and the 2nd axis is label\nsample_label_masks_applied = np.einsum(\"ijk,ijl->klij\", sample, label_mask_unraveled)\n\n# in order to exclude the non-selected pixels \n# from meausurement calculations, we mask the pixels first\nnon_selected_pixels_mask = np.moveaxis(~label_mask_unraveled, -1, 0)[np.newaxis, :, :, :]\nnon_selected_pixels_mask = np.repeat(non_selected_pixels_mask, sample.shape[2], axis=0)\n\nsample_label_masks_applied = ma.masked_array(sample_label_masks_applied, non_selected_pixels_mask) \n\n# intensity measurement calculations\n# embedded into pd.DataFrame initialization\nintensity_measurements = pd.DataFrame(\n {\n \"sample\": args.input_img,\n \"label\": sample.shape[2] * list(range(1, n_labels+1)),\n \"stain\": n_labels * list(range(sample.shape[2])),\n \"mean\": ma.mean(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"median\": ma.median(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"std\": ma.std(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"min\": ma.min(sample_label_masks_applied, axis=(2, 3)).flatten(),\n \"max\": ma.max(sample_label_masks_applied, axis=(2, 3)).flatten() \n }\n)\n" }, { "answer_id": 74342302, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 1, "selected": false, "text": "import diplib as dip\n\n# sample = imread(input_img)\n# label_mask = np.load(input_mask)\n# Alternative random data so that I can run the code for testing:\nsample = imageio.imread(\"../images/trui_c.tif\")\nlabel_mask = np.random.randint(0, 20, sample.shape[:2], dtype=np.uint32)\n\nsample = dip.Image(sample, tensor_axis=2)\nmsr = dip.MeasurementTool.Measure(label_mask, sample, features=[\"Mean\", \"StandardDeviation\", \"MinVal\", \"MaxVal\"])\nprint(msr)\n" }, { "answer_id": 74546381, "author": "Hugh Warden", "author_id": 13642459, "author_profile": "https://Stackoverflow.com/users/13642459", "pm_score": 1, "selected": true, "text": "import numpy as np\nimport pandas as pd\nfrom skimage.measure import regionprops, regionprops_table\nnp.random.seed(42)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11114361/" ]
74,341,190
<p>Sincerelly, I read a lot of times about this commands and I don't understand what the real objectives. I'm reading pedestal documentation and I saw a lot of this command <code>-&gt;</code> and <code>-&gt;&gt;</code> and I read in nubank's github public repository somethings as <code>^:private</code>, <code>s/def</code>, <code>s/defn</code> and <code>:-</code></p>
[ { "answer_id": 74341865, "author": "Juraj Martinka", "author_id": 1184752, "author_profile": "https://Stackoverflow.com/users/1184752", "pm_score": 4, "selected": true, "text": "->" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8033592/" ]
74,341,209
<p>In Python, many statements can cause errors, but I would like to know what are the simplest statements that can cause an Error <strong>except</strong> for <code>NameError</code> and <code>SyntaxError</code> and their subclasses such as <code>IdentationError</code></p> <p>Using the interactive Python shell, I have tried using single characters in statements but they are all <code>NameError</code>s or <code>SyntaxError</code>s, and I tried two characters, it is also the same, so I wonder if there are any possibilities to cause other types of errors by using 3 or fewer characters in Python. if this is impossible, then why so?</p>
[ { "answer_id": 74341217, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 2, "selected": true, "text": "ZeroDivisionError" }, { "answer_id": 74341248, "author": "Code-Apprentice", "author_id": 1440565, "author_profile": "https://Stackoverflow.com/users/1440565", "pm_score": 0, "selected": false, "text": "x, = 5 # TypeError\n" }, { "answer_id": 74341282, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "^C" }, { "answer_id": 74341325, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 1, "selected": false, "text": "TypeError" }, { "answer_id": 74341331, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "TypeError" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15037829/" ]
74,341,211
<p>When I'm working on a website, I check the changes on my browser (Google Chrome), and since usually the browser doesn't register the changes I make into the CSS file, I usually just work into an incognito window to avoid the hassle of deleting the cache manually. The downside is that I have to close it and open it often, and I have to log again in the app I'm working on every single time. This is relatively quickly but it adds up over time when done hundreds of times.</p> <p>There has to be a better way. What do most programers do?</p>
[ { "answer_id": 74341275, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 2, "selected": false, "text": "css" }, { "answer_id": 74343531, "author": "Z2r", "author_id": 10885581, "author_profile": "https://Stackoverflow.com/users/10885581", "pm_score": 0, "selected": false, "text": "ctrl+f5" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19041084/" ]
74,341,214
<p>I need to write a script that finds all of the capitalized words (not words in all caps, just the initial letter) in a text file and presents them in alphabetical order.</p> <p>I tried to use a regex like this:</p> <pre><code>re.findall(r'\b[A-Z][a-z]*\b', line) </code></pre> <p>but my function returns this output:</p> <pre><code>Enter the file name: bzip2.txt ['A', 'All', 'Altered', 'C', 'If', 'Julian', 'July', 'R', 'Redistribution', 'Redistributions', 'Seward', 'The', 'This'] </code></pre> <p>How can I remove all the single-letter words (ex: A, C, and R)?</p>
[ { "answer_id": 74341260, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": false, "text": "+" }, { "answer_id": 74341357, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "sorted()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436093/" ]
74,341,221
<p>I am trying to use Pybind11 in a Cmake project. I'm using Cmake 3.23.0-rc2.</p> <p>To include it, I can do the following:</p> <p><code>find_package(pybind11 REQUIRED)</code></p> <p>However, this does not work on my machine. So, I attempted to give find_package a hint as per the user guide:</p> <pre><code>SET(pybind11_DIR, &quot;C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/Lib/site-packages/pybind11&quot;) </code></pre> <p>That did not work either. The Cmake error suggested it may need to be the specific location of files like <code>pybind11Config.cmake</code>. So, I tried being more specific:</p> <pre><code>SET(pybind11_DIR, &quot;C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/Lib/site-packages/pybind11/share/cmake/pybind11&quot;) </code></pre> <p>That doesn't work either. I get the exact same error in Cmake:</p> <pre><code>CMake Error at lib/(our project name)/CMakeLists.txt:30 (find_package): By not providing &quot;Findpybind11.cmake&quot; in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by &quot;pybind11&quot;, but CMake did not find one. Could not find a package configuration file provided by &quot;pybind11&quot; with any of the following names: pybind11Config.cmake pybind11-config.cmake Add the installation prefix of &quot;pybind11&quot; to CMAKE_PREFIX_PATH or set &quot;pybind11_DIR&quot; to a directory containing one of the above files. If &quot;pybind11&quot; provides a separate development package or SDK, be sure it has been installed. </code></pre> <p>I double checked, Python itself is being found:</p> <pre><code>Python_FOUND:TRUE Python_VERSION:3.7.4 Python_Development_FOUND:TRUE Python_LIBRARIES:C:/Users/tyler.shellberg/AppData/Local/Programs/Python/Python37/libs/python37.lib Python_INCLUDE_DIRS: </code></pre> <p>(Though weirdly, include_dirs is empty)</p> <p>What am I doing wrong?</p>
[ { "answer_id": 74341260, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": false, "text": "+" }, { "answer_id": 74341357, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "sorted()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5403466/" ]
74,341,251
<p>I would like to change and replace some values under some conditions.</p> <p>My csv looks like:</p> <pre><code> Date 0 2022-11-05 1 2022-11-06 2 2022-11-08 3 2022-11-09 </code></pre> <p>I want the date +2 if it is Saturday and +1 if it is Sunday, and replace the value in the original csv.</p> <pre><code>df = pd.read_csv('Book1.csv') date = df[&quot;Date&quot;] for d in date: date_object = datetime.strptime(d, '%Y-%m-%d').date() #print(date_object) weekdayidx=date_object.isoweekday() #print(weekdayidx) if weekdayidx == 6: date_final = date_object.replace(day=date_object.day + 2) elif weekdayidx == 7: date_final = date_object.replace(day=date_object.day + 1) else: date_final = date_object print(date_final) df['Date'] = df['Date'].replace({'d': 'date_final'}) df.to_csv(&quot;Book1.csv&quot;, index=False) print(df) </code></pre> <p>But still the result is the same as the original csv, no update, not sure about the reason.</p> <p>Output:</p> <pre><code>0 2022-11-05 1 2022-11-06 2 2022-11-08 3 2022-11-09 </code></pre> <p>But I want:</p> <pre><code>2022-11-07 2022-11-07 2022-11-08 2022-11-09 </code></pre> <p>Thanks!</p>
[ { "answer_id": 74341260, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": false, "text": "+" }, { "answer_id": 74341357, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "sorted()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20377483/" ]
74,341,259
<p>I am testing a URL in flutter, but keep getting an error:</p> <blockquote> <p>Error: The argument type 'String' can't be assigned to the parameter type 'int'. final loginUri = Uri.parse(Config.apiURL, Config.loginAPI); ^</p> </blockquote> <pre><code>class Config { static const String appName = &quot;appName&quot;; static const String apiURL = http://127.0.0.1:8000/; static const String loginAPI = &quot;api/dj-rest-auth/login/&quot;; } class AuthService { final loginUri = Uri.parse(Config.apiURL, Config.loginAPI); </code></pre> <p>The error is showing for <code>Config.loginAPI</code> How do I fix this error knowing that they are both strings, not int related to them.</p> <p>What is the reason for it and how to fix it?</p>
[ { "answer_id": 74342361, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 0, "selected": false, "text": "class Config {\n static const String appName = \"appName\";\n static const String apiURL = http://127.0.0.1:8000/;\n static const String loginAPI = \"api/dj-rest-auth/login/\";\n}\n \nclass AuthService {\n final loginUri = Uri.parse(Config.apiURL, Config.loginAPI);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14574691/" ]
74,341,308
<p>I was trying to make a <em>single</em> function that takes in a container and implicitly have it convert to a <code>boost::iterator_range</code> as I thought that was it's purpose, but it seems that I'm missing something.</p> <p>Here's an example of what I was thinking:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;boost/range/iterator_range.hpp&gt; #include &lt;vector&gt; template&lt;typename IT&gt; void fn_x(boost::iterator_range&lt;IT&gt;) { } void fn_y() { std::vector&lt;int&gt; a(64); fn_x(boost::make_iterator_range(a.begin(), a.end())); // Works fn_x(a); // Doesn't } </code></pre> <p><a href="https://godbolt.org/z/3T6MM3141" rel="nofollow noreferrer"><kbd>Demo</kbd></a></p> <p>So how would I get <code>fn_x</code> to accept both a container and a range object, in the same function?</p> <p>Sorry, forgot to mention that I'm using c++14.</p>
[ { "answer_id": 74341502, "author": "azhen7", "author_id": 20341797, "author_profile": "https://Stackoverflow.com/users/20341797", "pm_score": 0, "selected": false, "text": "#include <iterator>\n\ntemplate<typename IT>\nvoid fn_x(boost::iterator_range<IT>) {\n}\n\ntemplate<typename Range>\nvoid fn_x(Range r) {\n fn_x(boost::make_iterator_range(std::begin(r), std::end(r));\n}\n" }, { "answer_id": 74341509, "author": "Marco Maia", "author_id": 4723737, "author_profile": "https://Stackoverflow.com/users/4723737", "pm_score": 0, "selected": false, "text": "std::span" }, { "answer_id": 74350257, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 2, "selected": true, "text": "#include <boost/range/iterator_range.hpp>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntemplate <typename Range> auto fn_x(Range&& r) {\n using std::begin;\n using std::end;\n return accumulate(begin(r), end(r), 0.0);\n}\n\nint main() {\n std::vector<int> a{1,2,3};\n\n std::cout << fn_x(boost::make_iterator_range(a.begin(), a.end())) << \"\\n\";\n std::cout << fn_x(a) << \"\\n\";\n}\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366368/" ]
74,341,341
<p>I have an array of objects like below, where I want to calculate the sum of <code>job_security, skill_development</code> and <code>company_culture</code> these fields.</p> <pre><code>reviews = [ { id: 1, job_security: '2.0', skill_development: '3.0', company_culture: '4.0', is_anonymous: false, pros: 'Test 1...', cons: &quot;Test 1...&quot;, created_at: '2022-10-19T19:07:18.000Z', }, { id: 2, job_security: '3.0', skill_development: '1.0', company_culture: '2.0', is_anonymous: false, pros: 'Test 2...', cons: &quot;Test 2...&quot;, created_at: '2022-10-19T19:07:25.000Z', }, { id: 3, job_security: '4.0', skill_development: '1.0', company_culture: '2.0', is_anonymous: false, pros: 'Test 3...', cons: &quot;Test 3...&quot;, created_at: '2022-10-19T19:07:35.000Z', } ] </code></pre> <p>I am expecting an output like this, where total sums of all the fields will return as an object</p> <pre><code>{ job_security: '4.0', skill_development: '6.0', company_culture: '7.0', } </code></pre> <p>This is what I have done :</p> <pre><code>const filteredKeys = [ 'job_security' 'company_culture', 'skill_development', ]; reviews.forEach((review: any) =&gt; { Object.keys(review).reduce( (accu: any, key: string) =&gt; { if (filteredKeys.includes(key)) { const rating = Number(review[key]); accu[key] = accu[key] || rating; accu[key] += rating; } return accu; }, Object.create(null) ); }); </code></pre>
[ { "answer_id": 74341391, "author": "HappyDev", "author_id": 16775611, "author_profile": "https://Stackoverflow.com/users/16775611", "pm_score": 0, "selected": false, "text": "const reviews = [\n {\n id: 1,\n job_security: '2.0',\n skill_development: '3.0',\n company_culture: '4.0',\n is_anonymous: false,\n pros: 'Test 1...',\n cons: \"Test 1...\",\n created_at: '2022-10-19T19:07:18.000Z',\n },\n {\n id: 2,\n job_security: '3.0',\n skill_development: '1.0',\n company_culture: '2.0',\n is_anonymous: false,\n pros: 'Test 2...',\n cons: \"Test 2...\",\n created_at: '2022-10-19T19:07:25.000Z',\n },\n {\n id: 3,\n job_security: '4.0',\n skill_development: '1.0',\n company_culture: '2.0',\n is_anonymous: false,\n pros: 'Test 3...',\n cons: \"Test 3...\",\n created_at: '2022-10-19T19:07:35.000Z',\n }\n]\n\nconst filters = [\n 'job_security',\n 'company_culture',\n 'skill_development',\n];\nconst output = reviews.reduce((acc, next)=> {\n for (let filter of filters){\n if (!(filter in next)) throw new Error(`Cannot find ${filter} in object`)\n if (!(filter in acc)) acc[filter] = 0;\n acc[filter]+= +next[filter];\n }\n return acc;\n}, {})\n" }, { "answer_id": 74341401, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 0, "selected": false, "text": "reduce()" }, { "answer_id": 74341463, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 3, "selected": true, "text": "const reviews = [{id: 1,job_security: '2.0',skill_development: '3.0',company_culture: '4.0',is_anonymous: false,pros: 'Test 1...',cons: \"Test 1...\",created_at: '2022-10-19T19:07:18.000Z',},{id: 2,job_security: '3.0',skill_development: '1.0',company_culture: '2.0',is_anonymous: false,pros: 'Test 2...',cons: \"Test 2...\",created_at: '2022-10-19T19:07:25.000Z',},{id: 3,job_security: '4.0',skill_development: '1.0',company_culture: '2.0',is_anonymous: false,pros: 'Test 3...',cons: \"Test 3...\",created_at: '2022-10-19T19:07:35.000Z',}];\n\nconst sums = reviews.reduce( (s,e,i,{[i+1]:eNext})=>\n {\n Object.keys(s).forEach( k => s[k] += +e[k] );\n if (!eNext) // for the last (no next element), change values to string\n Object.keys(s).forEach( k => s[k] = s[k].toFixed(1) );\n return s\n }\n ,{ job_security: 0, skill_development: 0, company_culture: 0 });\n \n \nconsole.log( sums )" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12202749/" ]
74,341,368
<p>I'm trying to find the index range (start index and end index, spaces are omitted, and with indexing starting at 1 for human readability.) of each word in a string. What I thought was the best approach was doing a list of lists where each nested list contains the word and a list of the start and end index. From a sample string, I get the following list:</p> <pre><code>text = &quot;i have a list of lists that contain a word and there indices my method works except with repeated words like of or a or the or it&quot; </code></pre> <p>yields:</p> <pre><code>boundaries_list=[['i', [1, 1]], ['have', [3, 6]], ['a', [4, 4]], ['list', [10, 13]], ['of', [15, 16]], ['lists', [18, 22]], ['that', [24, 27]], ['contain', [29, 35]], ['a', [4, 4]], ['word', [39, 42]], ['and', [44, 46]], ['there', [48, 52]], ['indices', [54, 60]], ['my', [62, 63]], ['method', [65, 70]], ['works', [72, 76]], ['except', [78, 83]], ['with', [85, 88]], ['repeated', [90, 97]], ['words', [99, 103]], ['like', [105, 108]], ['of', [15, 16]], ['or', [40, 41]], ['a', [4, 4]], ['or', [40, 41]], ['the', [48, 50]], ['or', [40, 41]], ['it', [86, 87]]] </code></pre> <p>This works, but its not very readable. Would sure be nice to compile it into a dictionary. Dictionaries work, except for when you have more than one of the same key. For me, that means that the first occurrence of a repeated word will be the ONLY occurrence of that word to be incorporated into the dictionary, thus excluding the index range of any other occurrences of that repeated word.</p> <p>To get around this I tried using <code>defaultdict</code>,on a list of dictionaries but this only gave me the first word's index range repeated by n amount of word occurrences.</p> <p>For Example:</p> <pre><code>for one_d in boundaries_list: nested_list_to_nested_dict = dict({one_d[0]:one_d[1] }) new_list.append(nested_list_to_nested_dict) res = defaultdict(list) for d in new_list: for k, v in d.items(): res[k].append(v) print(res) &gt;&gt;&gt; defaultdict(&lt;class 'list'&gt;, {'i': [[1, 1]], 'have': [[3, 6]], 'a': [[4, 4], [4, 4], [4, 4]], 'list': [[10, 13]], 'of': [[15, 16], [15, 16]], 'lists': [[18, 22]], 'that': [[24, 27]], 'contain': [[29, 35]], 'word': [[39, 42]], 'and': [[44, 46]], 'there': [[48, 52]], 'indices': [[54, 60]], 'my': [[62, 63]], 'method': [[65, 70]], 'works': [[72, 76]], 'except': [[78, 83]], 'with': [[85, 88]], 'repeated': [[90, 97]], 'words': [[99, 103]], 'like': [[105, 108]], 'or': [[40, 41], [40, 41], [40, 41]], 'the': [[48, 50]], 'it': [[86, 87]]}) </code></pre> <p>Any help is much appreciated.</p>
[ { "answer_id": 74341403, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 2, "selected": true, "text": "re" }, { "answer_id": 74341425, "author": "Nikolay Zakirov", "author_id": 9023490, "author_profile": "https://Stackoverflow.com/users/9023490", "pm_score": 0, "selected": false, "text": "text = \"i have a list of lists that contain a word and there indices my method works except with repeated words like of or a or the or it\"\n\nfrom collections import defaultdict\nnew_dict = defaultdict(list)\noffset = 0\nfor word in text.split(\" \"):\n new_dict[word].append([offset, offset+len(word)])\n offset += len(word) + 1;\n\nnew_dict\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12157205/" ]
74,341,383
<p>I found this method:</p> <pre><code>public override void OnActionExecuting(HttpActionContext actionContext) { var body = Task.Run(async() =&gt; await actionContext.Request.Content.ReadAsStringAsync() .ConfigureAwait(false)).Result; //rest of code omitted for brevity. } </code></pre> <p>I'm trying to work out two things:</p> <p>1.Will this code cause a deadlock?</p> <p>2.Since the method cannot be marked <code>async Task</code>, should it be written like this instead?</p> <pre><code>var body = actionContext.Request.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult(); </code></pre>
[ { "answer_id": 74341487, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 2, "selected": false, "text": "ConfigureAwait(false)" }, { "answer_id": 74342953, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 1, "selected": false, "text": "string body = Task.Run(async() =>\n{\n return await actionContext.Request.Content.ReadAsStringAsync()\n .ConfigureAwait(false);\n}).Result;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2063755/" ]
74,341,390
<pre><code>def get_beverage_type(a_enabled: bool, b_enabled: bool) -&gt; str: &quot;&quot;&quot; Returns the beverage type defined by the switches. &quot;&quot;&quot; if a_enabled == &quot;y&quot; == True and b_enabled == &quot;n&quot; == False: return &quot;Juice, Orange&quot; elif a_enabled == &quot;n&quot; == False and b_enabled == &quot;y&quot; == True: return &quot;Milk, 2%&quot; else: return &quot;Coke, Diet&quot; Switch_A = (input(&quot;Is switch A enabled? (y/n): &quot;)) Switch_B = (input(&quot;Is switch B enabled? (y/n): &quot;)) print(f&quot;Result: {get_beverage_type(Switch_A, Switch_B)}&quot;) </code></pre> <p>Putting the values as Switch_A = y and and Switch_valueB = n , it still returns Result: Coke, Diet</p>
[ { "answer_id": 74341487, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 2, "selected": false, "text": "ConfigureAwait(false)" }, { "answer_id": 74342953, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 1, "selected": false, "text": "string body = Task.Run(async() =>\n{\n return await actionContext.Request.Content.ReadAsStringAsync()\n .ConfigureAwait(false);\n}).Result;\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436221/" ]
74,341,400
<p>Can't select or input in the text area with custom animated background</p> <p>I'm trying to create a login page, where the user enters his User name and password in dedicated text areas. To make a good design I've added custom background animation. However, I couldn't input or click text within the background animation area.</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/css?family=Exo:400,700'); *{ margin: 0px; padding: 0px; } body{ font-family: 'Exo', sans-serif; } .context { width: 100%; position: absolute; top:100px; } .context h1{ text-align: center; color: #fff; font-size: 50px; } .area{ background: #4e54c8; background: -webkit-linear-gradient(to left, #8f94fb, #4e54c8); width: 100%; height:100vh; } .circles{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; } .circles li{ position: absolute; display: block; list-style: none; width: 20px; height: 20px; background: rgba(255, 255, 255, 0.2); animation: animate 25s linear infinite; bottom: -150px; } .circles li:nth-child(1){ left: 25%; width: 80px; height: 80px; animation-delay: 0s; } .circles li:nth-child(2){ left: 10%; width: 20px; height: 20px; animation-delay: 2s; animation-duration: 12s; } .circles li:nth-child(3){ left: 70%; width: 20px; height: 20px; animation-delay: 4s; } .circles li:nth-child(4){ left: 40%; width: 60px; height: 60px; animation-delay: 0s; animation-duration: 18s; } .circles li:nth-child(5){ left: 65%; width: 20px; height: 20px; animation-delay: 0s; } .circles li:nth-child(6){ left: 75%; width: 110px; height: 110px; animation-delay: 3s; } .circles li:nth-child(7){ left: 35%; width: 150px; height: 150px; animation-delay: 7s; } .circles li:nth-child(8){ left: 50%; width: 25px; height: 25px; animation-delay: 15s; animation-duration: 45s; } .circles li:nth-child(9){ left: 20%; width: 15px; height: 15px; animation-delay: 2s; animation-duration: 35s; } .circles li:nth-child(10){ left: 85%; width: 150px; height: 150px; animation-delay: 0s; animation-duration: 11s; } @keyframes animate { 0%{ transform: translateY(0) rotate(0deg); opacity: 1; border-radius: 0; } 100%{ transform: translateY(-1000px) rotate(720deg); opacity: 0; border-radius: 50%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="area" &gt; &lt;div class="context"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;textarea id="userName"&gt; Enter user name&lt;/textarea&gt;&lt;br&gt; &lt;textarea id="password"&gt; Enter password&lt;/textarea&gt; &lt;/div&gt; &lt;ul class="circles"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74341576, "author": "KnightTheLion", "author_id": 20432259, "author_profile": "https://Stackoverflow.com/users/20432259", "pm_score": 1, "selected": false, "text": "<input id=\"userName\" type=\"text\" placeholder=\"Enter user name\">\n<input id=\"password\" type=\"password\" placeholder=\"Enter password\">\n" }, { "answer_id": 74341636, "author": "Watson Chen", "author_id": 6497141, "author_profile": "https://Stackoverflow.com/users/6497141", "pm_score": 0, "selected": false, "text": "context" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16459979/" ]
74,341,447
<p>I have two of my activities (same app) opened in multiwindow / split-screen. Now I want that when a user taps on a button on Screen-1, I want to open an activity in Screen-2.</p> <p>I have read Android's document and I think I am doing it right, but it is not working. It still opens the new activity in Screen-1. Here is my code:</p> <pre><code> val intent = Intent(this, MyActivity::class.java) intent.addFlags( Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT or FLAG_ACTIVITY_NEW_TASK) startActivity(intent) </code></pre> <p>I have set</p> <pre><code>android:resizeableActivity=&quot;true&quot; </code></pre> <p>in the manifest, under the &quot;application&quot; tab, also in the &quot;activity&quot; tag.</p> <p>What wrong am I doing?</p> <p>I also tried this:</p> <pre><code> val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(MyActivity::class.java.name) intent.addFlags( Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT or FLAG_ACTIVITY_NEW_TASK) startActivity(intent) </code></pre> <p>didn't work.</p> <p>Another related question I want to ask is, is FLAG_ACTIVITY_NEW_TASK required? what if I don't want to create a new task?</p>
[ { "answer_id": 74341576, "author": "KnightTheLion", "author_id": 20432259, "author_profile": "https://Stackoverflow.com/users/20432259", "pm_score": 1, "selected": false, "text": "<input id=\"userName\" type=\"text\" placeholder=\"Enter user name\">\n<input id=\"password\" type=\"password\" placeholder=\"Enter password\">\n" }, { "answer_id": 74341636, "author": "Watson Chen", "author_id": 6497141, "author_profile": "https://Stackoverflow.com/users/6497141", "pm_score": 0, "selected": false, "text": "context" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1397821/" ]
74,341,464
<p>Is it possible to produce a million records a second via kafka? How many servers should it take? Currently i am sending 7000 messages a second from a kafka producer and struggling to exceed this</p> <p>I've noticed several sources say kafka can send millions of messages a second</p> <p>I've created a job that uses @Autowired kafkaTemplate and makes a while loop that sends a short text string &quot;asdf&quot; I've set up linger to 1000ms and seeing messages group in sets of 7000. The producer , consumer broker, zookeeper are on the same machine and the broker and zookeeper and a very simple docker image with default configuration</p> <p>I am maxing out around 7000 requests a second</p> <p>application.props</p> <pre><code>spring.kafka.bootstrap-servers=PLAINTEXT://localhost:9092,PLAINTEXT://localhost:9093 host.name=localhost </code></pre> <p>Job to make calls</p> <pre><code>@Async @Scheduled(fixedDelay = 15000) public void scheduleTaskUsingCronExpression() { generateCalls(); } private void generateCalls() { try{ int i = 0; System.out.println(&quot;start&quot;); long startTime = System.currentTimeMillis(); while(i &lt;= 1000000){ String message = &quot;Test Message sadg sad-&quot;; kafkaTemplate.send(TOPIC, message + i); i++; } long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime)); System.out.println(&quot;done&quot;); } catch(Exception e){ e.printStackTrace(); } System.out.println(&quot;RUNNING&quot;); } </code></pre> <p>Kakfa partition config</p> <pre><code>@Bean public KafkaAdmin kafkaAdmin() { //String bootstrapAddress = &quot;localhost:29092&quot;; String bootstrapAddress = &quot;localhost:9092&quot;; Map&lt;String, Object&gt; configs = new HashMap&lt;&gt;(); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); return new KafkaAdmin(configs); } @Bean public NewTopic testTopic() { return new NewTopic(&quot;test-topic&quot;, 6, (short) 1); } </code></pre> <p>Kafka consumer consuming messge</p> <pre><code>@KafkaListener(topics = &quot;test-topic&quot;, groupId = &quot;one&quot;, concurrency = &quot;6&quot; ) public void listenGroupFoo(String message) { if(message.indexOf(&quot;-0&quot;) != -1){ startTime = new Date().getTime(); System.out.println(&quot;Starting Message in group foo: &quot; + message); } else if(message.indexOf(&quot;-100000&quot;) != -1){ endTime = new Date().getTime(); System.out.println(&quot;Received Message in group foo: &quot; + message); System.out.println(endTime - startTime); } } </code></pre> <p>For hardware I have a 10900k with 64gb ram 5ghz clock speed 970 Evo single nvme disk 10 core 20 thread</p> <p>All requests are from the same machine to the same machine</p> <p>Is there a better way to organize / optimize the code to make a massive number of requests? Theories:</p> <ol> <li>Multiple Threads?</li> <li>Changing configurations of servers such as tomcat configs (receiving or sending side)?</li> <li>Not use the kafkaTemplate that is autowired or creating multiple?</li> <li>Modify Hardware to have multiple disks?</li> <li>Not use a job for the producer?</li> <li>Anything else anyone can think of to help?</li> </ol>
[ { "answer_id": 74341576, "author": "KnightTheLion", "author_id": 20432259, "author_profile": "https://Stackoverflow.com/users/20432259", "pm_score": 1, "selected": false, "text": "<input id=\"userName\" type=\"text\" placeholder=\"Enter user name\">\n<input id=\"password\" type=\"password\" placeholder=\"Enter password\">\n" }, { "answer_id": 74341636, "author": "Watson Chen", "author_id": 6497141, "author_profile": "https://Stackoverflow.com/users/6497141", "pm_score": 0, "selected": false, "text": "context" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12253240/" ]
74,341,471
<p>This question is come from <a href="https://stackoverflow.com/questions/74334249/how-to-sum-an-array-for-each-id-and-create-new-array-in-react">how-to-sum-an-array-for-each-id-and-create-new-array-in-react</a>,OP needs to sum data by id</p> <pre><code>const data = [{&quot;id&quot;: &quot;One&quot;, &quot;number&quot;: 100}, {&quot;id&quot;: &quot;One&quot;, &quot;number&quot;: 150}, {&quot;id&quot;: &quot;One&quot;, &quot;number&quot;: 200}, {&quot;id&quot;: &quot;Two&quot;, &quot;number&quot;: 50}, {&quot;id&quot;: &quot;Two&quot;, &quot;number&quot;: 100}, {&quot;id&quot;: &quot;Three&quot;, &quot;number&quot;: 10}, {&quot;id&quot;: &quot;Three&quot;, &quot;number&quot;: 90}] </code></pre> <p>In order to do it,I just use a traditional way(check with <code>if</code>) to do it with <code>reduce()</code></p> <pre><code>let result2 = data.reduce((a, v) =&gt; { let obj = a.find(i =&gt; i.id == v.id); if (obj) { obj.number += v.number; } else { a.push(v); } return a; }, []) console.log(result2); </code></pre> <p>And I found another answer is more elegant(one-liner):</p> <pre><code>let result3 = data.reduce((acc, {id, number}) =&gt; ({...acc, [id]: {id, number: acc[id] ? acc[id].number + number: number}}), {}); console.log(Object.values(result3)); </code></pre> <p>The question is that when I ran the two methods seperately,I can got the expected result(<a href="https://jsfiddle.net/Lxa9h60o/" rel="nofollow noreferrer">jsfiddle1</a> and <a href="https://jsfiddle.net/kuzy6p9j/" rel="nofollow noreferrer">jsfiddle2</a>)</p> <p><a href="https://i.stack.imgur.com/UIcg2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UIcg2.png" alt="enter image description here" /></a></p> <p>However,if I ran them together,the seconds result(from <code>result3</code>) is not as expected(<a href="https://jsfiddle.net/gs0edu6b/" rel="nofollow noreferrer">jsfiddle 3</a>) <a href="https://i.stack.imgur.com/dvkZu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dvkZu.png" alt="enter image description here" /></a></p> <p>I do not know why this happen,can anyone help me to analysis this?</p> <p>Also,I want to know if there are a more elegant one-liner solution to do it.</p> <p>Thanks in advance!</p>
[ { "answer_id": 74341651, "author": "Norguard", "author_id": 1001831, "author_profile": "https://Stackoverflow.com/users/1001831", "pm_score": 3, "selected": true, "text": "data" }, { "answer_id": 74341686, "author": "N_A_P", "author_id": 10693800, "author_profile": "https://Stackoverflow.com/users/10693800", "pm_score": 0, "selected": false, "text": "Map" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176419/" ]
74,341,479
<p>I have an app where users can login / sign out and the functionality stopped working recently when I added a new SceneDelegate view and moved over the code from the AppDelegate. I'm not sure why it is not working but I suspect it has to do with using the shared delegate in my signOut function.</p> <p>Something strange is happening, when I tap the sign out button nothing happens. However, when I close the app and open it again, I will be signed out.</p> <p>Here is the code on my home screen for the sign out button:</p> <pre><code>@IBAction func signOutButtonTapped(_ sender: Any) { KeychainWrapper.standard.removeObject(forKey: &quot;accessToken&quot;) KeychainWrapper.standard.removeObject(forKey: &quot;userID&quot;) // send user to splash page let signInPage = self.storyboard?.instantiateViewController(withIdentifier: &quot;splashController&quot;) as! splashViewController let appDelegate = UIApplication.shared.delegate appDelegate?.window??.rootViewController = signInPage } </code></pre> <p>This is the code from my SceneDelegate.swift file:</p> <pre><code>class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let _ = (scene as? UIWindowScene) else { return } let accessToken: String? = KeychainWrapper.standard.string(forKey: &quot;accessToken&quot;) // If access token exists, skip login page if accessToken != nil { if let windowScene = scene as? UIWindowScene { self.window = UIWindow(windowScene: windowScene) let mainStoryboard:UIStoryboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil) let vc = mainStoryboard.instantiateViewController(withIdentifier: &quot;homeTabController&quot;) as! TabBarController self.window!.rootViewController = vc } } } } </code></pre>
[ { "answer_id": 74341651, "author": "Norguard", "author_id": 1001831, "author_profile": "https://Stackoverflow.com/users/1001831", "pm_score": 3, "selected": true, "text": "data" }, { "answer_id": 74341686, "author": "N_A_P", "author_id": 10693800, "author_profile": "https://Stackoverflow.com/users/10693800", "pm_score": 0, "selected": false, "text": "Map" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20126173/" ]
74,341,489
<p>I see this term a lot, 'symbol', and after searching on google I still can't find a definition that makes sense to me.</p> <p>For example in the manual of <code>ar</code> command on Linux, it's said :</p> <blockquote> <p>ar creates an index to the symbols defined in relocatable object modules in the archive when you specify the modifier s.</p> </blockquote> <p>Are function declarations / variable declarations / defines / structure declarations etc, symbols ? Or is a symbol a term for .o files ?</p> <p>In this context, what is a symbol exactly ? Act like I'm a complete beginner who knows nothing when you form your answer please !</p>
[ { "answer_id": 74341651, "author": "Norguard", "author_id": 1001831, "author_profile": "https://Stackoverflow.com/users/1001831", "pm_score": 3, "selected": true, "text": "data" }, { "answer_id": 74341686, "author": "N_A_P", "author_id": 10693800, "author_profile": "https://Stackoverflow.com/users/10693800", "pm_score": 0, "selected": false, "text": "Map" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20250022/" ]
74,341,522
<p>I have installed RabbitMQ 3.11.2 and Erlang version 25.1.1 on Windows 10 machine.</p> <p>I am very new to RabbitMQ, and I am unable to launch RabbitMQ management portal. I enabled the RabbitMQ management plugin as well.</p> <p>Searched the internet with all sorts of suggestions on Stack Overflow, Google Groups, and other forums and all of them failed.</p> <p>In the log files I find a lot of errors like below.</p> <pre><code>2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; **Failed to start TCP listener [::]:5672**, error: {{shutdown, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {failed_to_start_child, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {ranch_embedded_sup, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {acceptor, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {0,0,0,0,0,0,0,0}, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; 5672}}, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {shutdown, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {failed_to_start_child, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {ranch_listener_sup, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {acceptor, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {0,0,0,0,0,0,0,0}, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; 5672}}, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {shutdown, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.697.0&gt; {failed_to_start_child, 2022-11-07 11:50:09.594000+10:00 [error] &lt;0.704.0&gt; **Failed to start Ranch listener {acceptor,{0,0,0,0,0,0,0,0},5672**} in ranch_tcp:listen(#{connection_type =&gt; supervisor,handshake_timeout =&gt; 5000,max_connections =&gt; infinity,num_acceptors =&gt; 10,num_conns_sups =&gt; 1,socket_opts =&gt; [{cacerts,'...'},{key,'...'},{cert,'...'},{ip,{0,0,0,0,0,0,0,0}},{port,5672},inet6,{backlog,128},{nodelay,true},{linger,{true,0}},{exit_on_close,false}]}) for reason eacces (permission denied) =erl_crash_dump:0.5 Mon Nov 7 12:50:21 2022 Slogan: init terminating in do_boot **({error,{could_not_start_listener,::,5672,**{{shutdown,{_}},{child,undefined,rabbit_tcp_listener_sup_:::5672,{ </code></pre> <p>I have diabled McAfee firewall, I have added port 5672 to McAfee firewall, reinstalled the RabbitMQ and Erlang apps at least 10 times, opened the port 5672 in windows firewall security, tried on docker images as well but my 3 days efforts failed to start it.</p> <p>I have attached RabbitMQ and Erlang log files in here, please provide your valuable suggestions.</p>
[ { "answer_id": 74341651, "author": "Norguard", "author_id": 1001831, "author_profile": "https://Stackoverflow.com/users/1001831", "pm_score": 3, "selected": true, "text": "data" }, { "answer_id": 74341686, "author": "N_A_P", "author_id": 10693800, "author_profile": "https://Stackoverflow.com/users/10693800", "pm_score": 0, "selected": false, "text": "Map" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436325/" ]
74,341,529
<p>HTML:</p> <pre><code>&lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-back bi bi-bicycle&quot;&gt; </code></pre> <p>CSS:</p> <pre><code>.card-back { transform: rotateY(270deg) translateZ(10px); } .flipped { transform: rotateY(180deg) translateZ(0); } </code></pre> <p>Above are my existing code structure; am trying to add the ‘flipped’ class into the ‘card-back’ class ON CLICK in order to flip my card - desired output: <code>&lt;div class=&quot;card-back flipped bi bi-bicycle&quot;&gt;</code></p> <p>Wrote the following function but it didn’t work:</p> <pre><code>const flipCard = () =&gt; { $(“.card-back”).on(“click”, (event) =&gt; { $(event.currentTarget).classList.add(“flipped”); }); }; flipCard(); </code></pre> <p>Any help/advice would be appreciated!</p>
[ { "answer_id": 74341591, "author": "Jesper Martinez", "author_id": 12494707, "author_profile": "https://Stackoverflow.com/users/12494707", "pm_score": 1, "selected": false, "text": "$(document).on(\"click\", \"div.card-back\" , function() {\n $(this).addClass(\"flipped\");\n});\n" }, { "answer_id": 74341628, "author": "mehdi354", "author_id": 9987655, "author_profile": "https://Stackoverflow.com/users/9987655", "pm_score": 0, "selected": false, "text": "const flipCard = () => {\n console.log(\"click\")\n $('.card').on('click', (event) => {\n $('.card-back').toggleClass('flipped');\n console.log(\"click\")\n });\n};\nflipCard();\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436368/" ]
74,341,555
<p>I am using Bootstrap 5 and have a <code>&lt;div&gt;</code> that is wrapped in an <code>&lt;a&gt;</code>. It contains a title, a thumbnail image, and some description text. In other words, the entire block of content is a link.</p> <p>I have been able to override most of Bootstrap's CSS, but when it comes to this link text it's really persistent.</p> <p>If I specify <code>display: inline-block</code> the underlines disappear. But I want that for <code>inline</code> text here as well. <code>text-decoration: none</code> is not taking effect.</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;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Underline&lt;/title&gt; &lt;!-- Bootstrap core CSS --&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body class="py-0"&gt; &lt;main&gt; &lt;div class="row mb-3 report-with-img-cont"&gt; &lt;div class="col-md-8 col-lg-9 report-previews themed-grid-col"&gt; &lt;a href="/"&gt; &lt;div&gt; &lt;div&gt; &lt;h5&gt; &lt;span&gt;This is a Title&lt;/span&gt; &lt;/h5&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-12 col-lg-4 themed-grid-col"&gt;&lt;img src="https://via.placeholder.com/160x90"&gt;&lt;/div&gt; &lt;div class="col-md-12 col-lg-8 themed-grid-col"&gt;&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74342377, "author": "Saad1430", "author_id": 19199222, "author_profile": "https://Stackoverflow.com/users/19199222", "pm_score": 0, "selected": false, "text": "text-decoration:none;" }, { "answer_id": 74342715, "author": "Ponsiva", "author_id": 9936892, "author_profile": "https://Stackoverflow.com/users/9936892", "pm_score": 3, "selected": true, "text": "text-decoration-none" }, { "answer_id": 74342898, "author": "Amit Kumar", "author_id": 20379294, "author_profile": "https://Stackoverflow.com/users/20379294", "pm_score": 0, "selected": false, "text": "text-decoration-none" }, { "answer_id": 74343086, "author": "Sharif Mia", "author_id": 8060704, "author_profile": "https://Stackoverflow.com/users/8060704", "pm_score": 1, "selected": false, "text": "<a href=\"#\" class=\"text-decoration-none\">Non-underlined link</a>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2454914/" ]
74,341,562
<p>I have a searchable dropdown box, from the package dropdown_search 5.0.3, where the choices in the dropdown box are titles mapped from a list I have created. When an option in the dropdown box is selected, I want to print the title and the corresponding 'amount' value of the option (from the list). However, I am having difficulty extracting the value of the dropdown box. I tried copying the code from some related questions that have been asked on here, but I'm getting the error 'The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(List&lt; String &gt;)?'. Where do I go from here?</p> <p>Here is my current code:</p> <pre><code>void main() =&gt; runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData(), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() =&gt; _MyHomePageState(); } typedef ValueChanged&lt;T&gt; = void Function(T value); class _MyHomePageState extends State&lt;MyHomePage&gt; { final _popupBuilderKey = GlobalKey&lt;DropdownSearchState&lt;String&gt;&gt;(); String dropdownSelected = ''; final List&lt;Food&gt; foodListData = [ Food( title: 'Food 1', id: 1, amount: 3, date: DateTime.now(), ), Food( title: &quot;Food 2&quot;, id: 2, amount: 1, date: DateTime.now(), ), Food( title: 'Food 3', id: 3, amount: 3, date: DateTime.now(), ), Food( title: 'Food 4', id: 4, amount: 1, date: DateTime.now(), ), ]; @override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; AppBar( title: const Text( 'My App', ), ); final pageBody = SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: &lt;Widget&gt;[ Column(children: &lt;Widget&gt;[ Text( 'My Foods', ), GestureDetector( child: ElevatedButton( child: Text(&quot;Add Food&quot;), onPressed: null, ), ), DropdownSearch&lt;String&gt;.multiSelection( key: _popupBuilderKey, items: foodListData.map((item) { return (item.title).toString(); }).toList(), popupProps: PopupPropsMultiSelection.menu( showSelectedItems: true, showSearchBox: true, ), onChanged: (String selectedValue) { dropdownSelected = selectedValue; } ) ]) ], )), ); return Scaffold( body: pageBody, floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: Platform.isIOS ? Container() : FloatingActionButton( child: Icon(Icons.add), onPressed: null, ), ); } } </code></pre>
[ { "answer_id": 74342377, "author": "Saad1430", "author_id": 19199222, "author_profile": "https://Stackoverflow.com/users/19199222", "pm_score": 0, "selected": false, "text": "text-decoration:none;" }, { "answer_id": 74342715, "author": "Ponsiva", "author_id": 9936892, "author_profile": "https://Stackoverflow.com/users/9936892", "pm_score": 3, "selected": true, "text": "text-decoration-none" }, { "answer_id": 74342898, "author": "Amit Kumar", "author_id": 20379294, "author_profile": "https://Stackoverflow.com/users/20379294", "pm_score": 0, "selected": false, "text": "text-decoration-none" }, { "answer_id": 74343086, "author": "Sharif Mia", "author_id": 8060704, "author_profile": "https://Stackoverflow.com/users/8060704", "pm_score": 1, "selected": false, "text": "<a href=\"#\" class=\"text-decoration-none\">Non-underlined link</a>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367123/" ]
74,341,567
<p><a href="https://i.stack.imgur.com/UXlMk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UXlMk.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/C74vQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C74vQ.png" alt="enter image description here" /></a></p> <p>at line 161,I want to insert my text in parameter t,but it won't change when i debug it.although the parameter tmp had alredy changed.</p> <p><a href="https://i.stack.imgur.com/U1qVp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U1qVp.png" alt="enter image description here" /></a></p> <p>I want to change this Text in UI,when my parameter t changes.</p>
[ { "answer_id": 74341920, "author": "Visual Studio", "author_id": 10470363, "author_profile": "https://Stackoverflow.com/users/10470363", "pm_score": 1, "selected": false, "text": "string" }, { "answer_id": 74342728, "author": "Milan Egon Votrubec", "author_id": 8051819, "author_profile": "https://Stackoverflow.com/users/8051819", "pm_score": 1, "selected": true, "text": "var tmp = System.Text.Encoding.UTF8.GetString ( e.Message );\nt.text = $\"{tmp}\\n{t.text}\"; // Note that a newline is represented as \\n\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436344/" ]
74,341,595
<p>I'm currently trying to automate a game called Lyrics Training (<a href="https://www.lyricstraining.com/" rel="nofollow noreferrer">https://www.lyricstraining.com/</a>) and I am able to get the words that are from the button through some other code but I am currently struggling with clicking the &quot;button&quot; because it is for some reason classified as a in the HTML code. I was wondering whether there was a way or a function that would allow me to click it so I could finish the automation? Thanks!</p> <p>So far I have this code that would work if the button was an actual button:</p> <pre><code>let firstChoice = document.getElementsByClassName(&quot;slot s1&quot;)[0]; let secondChoice = document.getElementsByClassName(&quot;slot s2&quot;)[0]; let thirdChoice = document.getElementsByClassName(&quot;slot s3&quot;)[0]; let fourthChoice = document.getElementsByClassName(&quot;slot s4&quot;)[0]; // the click function isn't working for(let i = 0; i &lt; click_order.length; i++){ let word = click_order[i]; if(firstChoice.innerHTML === word){ firstChoice.click(); }else if(secondChoice.innerHTML === word){ secondChoice.click(); }else if(thirdChoice.innerHTML === word){ thirdChoice.click(); }else if(fourthChoice.innerHTML === word){ fourthChoice.click(); } } </code></pre> <p>This is how the &quot;buttons&quot; look like in the HTML code of the website:</p> <p><a href="https://i.stack.imgur.com/F0cdm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F0cdm.png" alt="DIV Buttons" /></a></p> <p>Any help would be appreciated! Thanks!</p>
[ { "answer_id": 74383083, "author": "Static Spaghetti 13", "author_id": 20455439, "author_profile": "https://Stackoverflow.com/users/20455439", "pm_score": 1, "selected": false, "text": "div.addEventListener(\"click\", somefunction);\n//or\nbtn.addEventListener(\"click\", somefunction);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15034171/" ]
74,341,604
<h3>Motivation:</h3> <p>Hybrid syntax</p> <pre class="lang-xml prettyprint-override"><code>&lt;Label FontSize=&quot;50&quot;&gt;Hello&lt;/Label&gt; </code></pre> <p>can be converted into pure attribute syntax,</p> <pre class="lang-xml prettyprint-override"><code>&lt;Label Text=&quot;Hello&quot; FontSize=&quot;50&quot;/&gt; </code></pre> <p>or pure element syntax</p> <pre class="lang-xml prettyprint-override"><code>&lt;Label&gt; &lt;Label.Text&gt;Hello&lt;/Label.Text&gt; &lt;Label.FontSize&gt;50&lt;/Label.FontSize&gt; &lt;/Label&gt; </code></pre> <h3>Question:</h3> <p>Can we also convert <code>&lt;x:Double x:Key=&quot;fontsize&quot;&gt;50&lt;/x:Double&gt;</code> into pure attribute syntax and pure element syntax?</p> <p>In my attempt, I cannot find the name of attribute associated with <code>50</code>.</p>
[ { "answer_id": 74383083, "author": "Static Spaghetti 13", "author_id": 20455439, "author_profile": "https://Stackoverflow.com/users/20455439", "pm_score": 1, "selected": false, "text": "div.addEventListener(\"click\", somefunction);\n//or\nbtn.addEventListener(\"click\", somefunction);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835073/" ]
74,341,607
<p>With a dataframe</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([['a', 3], ['a', 5], ['a', 2], ['a', 6], ['a', 7], ['a', 1], ['a', 9], ['b', 7], ['b', 8], ['b', 11], ['b', 9], ['b', 10], ['b', 6]], columns = ['k', 'v']) </code></pre> <p>I want to compute the row difference on column <code>v</code> for each group of column <code>k</code> with a period of <code>3</code>. While for the first few rows in each group that have less than 3 values, we use an <em><strong>incrementing period</strong></em> starting at 1 till the preset value 3. The desired result would be as follows:</p> <p><a href="https://i.stack.imgur.com/zOPT6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zOPT6.png" alt="enter image description here" /></a></p> <p>What's a good &quot;pandasonic&quot; way to do this?</p>
[ { "answer_id": 74341756, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "groupby" }, { "answer_id": 74341766, "author": "David Smith", "author_id": 13663981, "author_profile": "https://Stackoverflow.com/users/13663981", "pm_score": 2, "selected": true, "text": ".groupby()" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1021602/" ]
74,341,610
<p>I have the following list</p> <pre><code>import numpy as np Y = [np.array([[1, 4, 7], [2, 5, 8]]), np.array([[10, 14, 18], [11, 15, 19], [12, 16, 20], [13, 17, 21]]), np.array([[22, 26, 31], [24, 28, 33], [26, 30, 35]])] </code></pre> <p>I want to loop through and print the columns inside of all the arrays in Y.</p> <p>I don't know how to access the columns of Y. Running <code>Y[:,0]</code> for example, does not give me</p> <pre><code>[[1] [2]] </code></pre> <p>Instead, it gives me the following error</p> <pre><code>TypeError: list indices must be integers or slices, not tuple </code></pre> <p>I want to print all columns of all the arrays in Y, not just the first column of the first array.</p>
[ { "answer_id": 74342191, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import pandas as pd\ndf = pd.concat(map(pd.DataFrame, Y), keys=range(len(Y)))\n\ndf.loc[(0,), 0]\n" }, { "answer_id": 74350651, "author": "S C", "author_id": 19323948, "author_profile": "https://Stackoverflow.com/users/19323948", "pm_score": 2, "selected": true, "text": "for i in range(3):\n l = Y[i]\n for j in range(len(np.transpose(l))):\n print(l[:,j])\n" }, { "answer_id": 74406782, "author": "isCzech", "author_id": 20188124, "author_profile": "https://Stackoverflow.com/users/20188124", "pm_score": 1, "selected": false, "text": "for array in Y:\n for row in array.T:\n print(row)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20383481/" ]
74,341,617
<p>Cognos 11.1.7 Need help with syntax on a macro prompt so the default can be to select all members</p> <p>Here is a simple example that works</p> <pre><code>set([Generic].[Groups].[Location].[Location] -&gt; ?Location?) </code></pre> <p>If I wanted to hard code a value I could use this as a slicer</p> <pre><code>[Generic].[Groups].[Location].[Location]-&gt;[all].[1] </code></pre> <p>What is the syntax for creating a macro prompt with a default of all members? i.e. instead of ?Location?<br /> Something like this:</p> <pre><code>#Prompt('Location', 'token', '[all]')# </code></pre> <p>or maybe like</p> <pre><code>#Prompt('Location', 'memberuniquename', '[all]')# </code></pre> <p>Open to using different techniques (filter, set, etc)</p>
[ { "answer_id": 74342191, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import pandas as pd\ndf = pd.concat(map(pd.DataFrame, Y), keys=range(len(Y)))\n\ndf.loc[(0,), 0]\n" }, { "answer_id": 74350651, "author": "S C", "author_id": 19323948, "author_profile": "https://Stackoverflow.com/users/19323948", "pm_score": 2, "selected": true, "text": "for i in range(3):\n l = Y[i]\n for j in range(len(np.transpose(l))):\n print(l[:,j])\n" }, { "answer_id": 74406782, "author": "isCzech", "author_id": 20188124, "author_profile": "https://Stackoverflow.com/users/20188124", "pm_score": 1, "selected": false, "text": "for array in Y:\n for row in array.T:\n print(row)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10630629/" ]
74,341,618
<p>I'm using Oracle and SQL Developer. I have downloaded HR schema and need to do some queries with it. Now I'm working with table <code>Employees</code>. As an user I need to see the list of employees with lowest salary in each department. I need to provide different solutions by means of plain SQL and one of analytic functions. About analytic functions, I have used <code>RANK()</code>:</p> <pre><code>SELECT * FROM (SELECT employee_id, first_name, department_id, salary, RANK() OVER (PARTITION BY department_id ORDER BY salary) result FROM employees) WHERE result = 1 AND department_id IS NOT NULL; </code></pre> <p>The result seems correct:</p> <p><a href="https://i.stack.imgur.com/1JhKf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1JhKf.png" alt="Result" /></a></p> <p>but when I try to use plain SQL I actually get all employees with their salaries.</p> <p>Here is my attempt with <code>GROUP BY</code>:</p> <pre><code>SELECT department_id, MIN(salary) AS &quot;Lowest salary&quot; FROM employees GROUP BY department_id; </code></pre> <p>This code seems good, but I need to also get columns <code>first_name</code> and <code>employee_id</code>.</p> <p>I tried to do something like this:</p> <pre><code>SELECT employee_id, first_name, department_id, MIN(salary) result FROM employees GROUP BY employee_id, first_name, department_id; </code></pre> <p>and this:</p> <pre><code>SELECT employee_id, first_name, salary, departments.department_id FROM employees LEFT OUTER JOIN departments ON (employees.department_id = departments.department_id) WHERE employees.salary = (SELECT MIN(salary) FROM departments WHERE department_id = employees.department_id) </code></pre> <p>These seem wrong. How can I change or modify my queries to get the same result as when I'm using <code>RANK()</code> by means of plain SQL (two solutions at least)?</p>
[ { "answer_id": 74342191, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "import pandas as pd\ndf = pd.concat(map(pd.DataFrame, Y), keys=range(len(Y)))\n\ndf.loc[(0,), 0]\n" }, { "answer_id": 74350651, "author": "S C", "author_id": 19323948, "author_profile": "https://Stackoverflow.com/users/19323948", "pm_score": 2, "selected": true, "text": "for i in range(3):\n l = Y[i]\n for j in range(len(np.transpose(l))):\n print(l[:,j])\n" }, { "answer_id": 74406782, "author": "isCzech", "author_id": 20188124, "author_profile": "https://Stackoverflow.com/users/20188124", "pm_score": 1, "selected": false, "text": "for array in Y:\n for row in array.T:\n print(row)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18744508/" ]
74,341,621
<p>I have two df,</p> <p>dataset2:</p> <pre><code> 0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 0 s1 5 4 4 5 4 4 4 4 4 ... 4 4 3 3 4 3 4 4 3 3 1 s2 3 4 3 4 4 5 3 5 3 ... 5 3 3 2 3 3 3 5 5 1 2 s3 4 4 5 5 4 4 4 4 4 ... 5 4 4 1 3 2 3 3 4 3 3 s4 5 5 5 1 5 5 5 5 1 ... 4 5 5 1 5 4 5 4 5 5 4 s5 5 5 5 5 5 5 4 5 2 ... 4 4 5 1 2 2 5 5 5 3 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 74 s75 4 4 4 4 5 5 5 5 5 ... 5 5 4 2 5 4 4 5 5 4 75 s76 5 3 4 5 5 5 4 5 4 ... 5 4 4 4 4 3 3 4 5 4 76 s77 5 3 3 5 2 3 3 3 3 ... 3 3 5 5 3 3 5 3 5 3 77 s78 4 5 4 2 2 4 4 4 5 ... 5 5 3 3 4 2 4 5 5 2 78 s79 5 4 5 5 5 5 4 5 5 ... 5 5 4 2 5 3 4 5 5 4 </code></pre> <p>df_combinec:</p> <pre><code> 0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 0 s80 5 5 5 6 4 3 4 3 2 ... 4 2 5 8 3 2 4 4 5 4 1 s81 5 4 4 5 3 4 5 4 3 ... 5 5 5 6 5 3 3 3 5 4 2 s82 4 4 4 6 5 4 4 5 6 ... 5 4 4 1 4 2 4 5 4 3 3 s83 5 4 4 5 5 5 2 4 4 ... 5 5 5 7 4 2 4 5 5 4 4 s84 3 2 5 4 5 5 4 5 5 ... 4 5 5 4 4 3 4 5 4 3 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 116 s196 4 4 4 5 5 4 5 5 4 ... 5 4 4 3 3 4 4 3 5 5 117 s197 5 5 4 5 5 5 4 5 4 ... 5 5 4 2 5 3 5 5 5 3 118 s198 5 5 4 6 4 4 5 4 2 ... 5 5 4 0 5 1 4 4 5 4 119 s199 5 3 3 4 4 5 5 5 5 ... 5 4 5 2 4 3 5 5 5 5 120 s200 5 4 4 4 3 5 2 5 3 ... 4 4 5 4 2 1 4 5 5 4 </code></pre> <p>I try below code to combine these df, but it comes out many Nan.</p> <pre><code>dataset2.reset_index(drop=True) df_combinec.reset_index(drop=True) comb_data = pd.concat([dataset2,df_combinec], ignore_index=True) </code></pre> <p>df_combinec after reindex:</p> <p><a href="https://i.stack.imgur.com/xL0BD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xL0BD.png" alt="enter image description here" /></a></p> <p>comb_data: <a href="https://i.stack.imgur.com/aHRYJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHRYJ.png" alt="enter image description here" /></a></p> <p>How to solve it?</p>
[ { "answer_id": 74341852, "author": "d_frEak", "author_id": 12883179, "author_profile": "https://Stackoverflow.com/users/12883179", "pm_score": 0, "selected": false, "text": "df_combinec.columns=dataset2.columns" }, { "answer_id": 74341919, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "dataset2.columns" }, { "answer_id": 74342113, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([[1, 2]], columns=['A', 'B'])\ndf2 = pd.DataFrame([[3, 4]], columns=pd.MultiIndex.from_arrays([['A', 'B']]))\n\npd.concat([df, df2])\n\n# A B (A,) (B,)\n# 0 1.0 2.0 NaN NaN\n# 0 NaN NaN 3.0 4.0\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18737194/" ]
74,341,632
<p>I have a module that redirects console outputs to the Tkinter window, which I found here on StackOverflow. It works perfectly, however, I realized I also need to save the console output to a file. But everything I tried either doesn't work, breaks the module, or nothing happens.</p> <p>EDIT: I need to modify the following module so it also SAVES THE CONSOLE OUTPUT to the .txt document. BUT preserving it's current functionality</p> <p>Here is the code for the module:</p> <pre><code># Code derived from Bryan Olson's source posted in this related Usenet discussion: # https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/TpFeWxEE9nsJ # https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/eEHYAl4dH9YJ # # See the comments and doc string below. # # Here's a module to show stderr output from console-less Python # apps, and stay out of the way otherwise. I plan to make a ASPN # recipe of it, but I thought I'd run it by this group first. # # To use it, import the module. That's it. Upon import it will # assign sys.stderr. # # In the normal case, your code is perfect so nothing ever gets # written to stderr, and the module won't do much of anything. # Upon the first write to stderr, if any, the module will launch a # new process, and that process will show the stderr output in a # window. The window will live until dismissed; I hate, hate, hate # those vanishing-consoles-with-critical-information. # # The code shows some arguably-cool tricks. To fit everthing in # one file, the module runs the Python interpreter on itself; it # uses the &quot;if __name__ == '__main__'&quot; idiom to behave radically # differently upon import versus direct execution. It uses tkinter # for the window, but that's in a new process; it does not import # tkinter into your application. # # To try it out, save it to a file -- I call it &quot;errorwindow.py&quot; - # - and import it into some subsequently-incorrect code. For # example: # # import errorwindow # # a = 3 + 1 + nonesuchdefined # # should cause a window to appear, showing the traceback of a # Python NameError. # # -- # --Bryan # ---------------------------------------------------------------- # # martineau - Modified to use subprocess.Popen instead of the os.popen # which has been deprecated since Py 2.6. Changed so it # redirects both stdout and stderr. Added numerous # comments, and also inserted double quotes around paths # in case they have embedded space characters in them, as # they did on my Windows system. # # Recently updated it to work in both Python 2 and Python 3. &quot;&quot;&quot; Import this module into graphical Python apps to provide a sys.stderr. No functions to call, just import it. It uses only facilities in the Python standard distribution. If nothing is ever written to stderr, then the module just sits there and stays out of your face. Upon write to stderr, it launches a new process, piping it error stream. The new process throws up a window showing the error messages. &quot;&quot;&quot; import subprocess import sys try: import thread except ModuleNotFoundError: # Python 3 import _thread as thread import os EXC_INFO_FILENAME = 'exc_info.txt' if __name__ == '__main__': # When spawned as separate process. # create window in which to display output # then copy stdin to the window until EOF # will happen when output is sent to each OutputPipe created try: from Tkinter import BOTH, END, Frame, Text, TOP, YES import tkFont import Queue except ModuleNotFoundError: # Python 3 from tkinter import BOTH, END, Frame, Text, TOP, YES import tkinter.font as tkFont import queue as Queue Q_EMPTY = Queue.Empty # An exception class. queue = Queue.Queue(1000) # FIFO def read_stdin(app, bufsize=4096): fd = sys.stdin.fileno() # File descriptor for os.read() calls. read = os.read put = queue.put while True: put(read(fd, bufsize)) class Application(Frame): def __init__(self, master=None, font_size=8, text_color='#0000AA', rows=25, cols=100): Frame.__init__(self, master) # Create title based on the arguments passed to the spawned script: # argv[0]: name of this script (ignored) # argv[1]: name of script that imported this module # argv[2]: name of redirected stream (optional) if len(sys.argv) &lt; 2: title = &quot;Output stream from unknown source&quot; elif len(sys.argv) &lt; 3: title = &quot;Output stream from %s&quot; % (sys.argv[1],) else: # Assume it's a least 3. title = &quot;Output stream '%s' from %s&quot; % (sys.argv[2], sys.argv[1]) self.master.title(title) self.pack(fill=BOTH, expand=YES) font = tkFont.Font(family='Courier', size=font_size) width = font.measure(' ' * (cols+1)) height = font.metrics('linespace') * (rows+1) self.configure(width=width, height=height) self.pack_propagate(0) # Force frame to be configured size. self.logwidget = Text(self, font=font) self.logwidget.pack(side=TOP, fill=BOTH, expand=YES) # Disallow key entry, but allow text copying with &lt;Control-c&gt; self.logwidget.bind('&lt;Key&gt;', lambda x: 'break') self.logwidget.bind('&lt;Control-c&gt;', lambda x: None) self.logwidget.configure(foreground=text_color) self.logwidget.insert(END, '==== Start of Output Stream ====\n\n') self.logwidget.see(END) self.after(200, self.start_thread) # Start queue polling thread. def start_thread(self): thread.start_new_thread(read_stdin, (self,)) self.after(200, self.check_q) def check_q(self): log = self.logwidget log_insert = log.insert log_see = log.see queue_get_nowait = queue.get_nowait go = True while go: try: data = queue_get_nowait().decode() # Must decode for Python 3. if not data: data = '[EOF]' go = False log_insert(END, data) log_see(END) except Q_EMPTY: self.after(200, self.check_q) go = False app = Application() app.mainloop() else: # when module is first imported import traceback class OutputPipe(object): def __init__(self, name=''): self.lock = thread.allocate_lock() self.name = name def flush(self): # no-op. pass def __getattr__(self, attr): if attr == 'pipe': # Attribute doesn't exist, so create it. # Launch this module as a separate process to display any output # it receives. # Note: It's important to put double quotes around everything in # case any have embedded space characters. command = '&quot;%s&quot; &quot;%s&quot; &quot;%s&quot; &quot;%s&quot;' % (sys.executable, # executable __file__, # argv[0] os.path.basename(sys.argv[0]), # argv[1] self.name) # argv[2] # # Typical command and arg values on receiving end: # C:\Python3\python[w].exe # executable # C:\vols\Files\PythonLib\Stack Overflow\errorwindow3k.py # argv[0] # errorwindow3k_test.py # argv[1] # stderr # argv[2] # Execute this script directly as __main__ with a stdin PIPE for sending # output to it. try: # Had to also make stdout and stderr PIPEs too, to work with pythonw.exe self.pipe = subprocess.Popen(command, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdin except Exception: # Output exception info to a file since this module isn't working. exc_type, exc_value, exc_traceback = sys.exc_info() msg = ('%r exception in %s\n' % (exc_type.__name__, os.path.basename(__file__))) with open(EXC_INFO_FILENAME, 'wt') as info: info.write('fatal error occurred spawning output process') info.write('exeception info:' + msg) traceback.print_exc(file=info) sys.exit('fatal error occurred') return super(OutputPipe, self).__getattribute__(attr) def write(self, data): with self.lock: data = data.encode() # Must encode for Python 3. self.pipe.write(data) # First reference to pipe attr will cause an # OutputPipe process for the stream to be created. # Clean-up any left-over debugging file. try: os.remove(EXC_INFO_FILENAME) # Delete previous file, if any. except Exception: pass # Redirect standard output streams in the process that imported this module. sys.stderr = OutputPipe('stderr') sys.stdout = OutputPipe('stdout') </code></pre> <p>I tried inserting this code after, before, and in between the module, but it didn't work or broke the module: <code>import sys path = 'output.txt' sys.stdout = open(path, 'w')</code></p> <p>I also tried to do something like this, but it didn't work either.</p> <pre><code>f = open(&quot;output.txt&quot;, &quot;w&quot;) f.write(sys.stdout) # or &quot;f.write(OutputPipe('stdout')&quot; or &quot; 'f.write(data)' between - 'def write(self, data):' &quot; f.close() </code></pre>
[ { "answer_id": 74341852, "author": "d_frEak", "author_id": 12883179, "author_profile": "https://Stackoverflow.com/users/12883179", "pm_score": 0, "selected": false, "text": "df_combinec.columns=dataset2.columns" }, { "answer_id": 74341919, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "dataset2.columns" }, { "answer_id": 74342113, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([[1, 2]], columns=['A', 'B'])\ndf2 = pd.DataFrame([[3, 4]], columns=pd.MultiIndex.from_arrays([['A', 'B']]))\n\npd.concat([df, df2])\n\n# A B (A,) (B,)\n# 0 1.0 2.0 NaN NaN\n# 0 NaN NaN 3.0 4.0\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11944578/" ]
74,341,649
<p>Looking to convert this powershell code into python:</p> <pre><code>$secretArgs = @{ fileName = &quot;test.pem&quot; fileAttachment = [IO.File]::ReadAllBytes(&quot;C:\brian\13568-test.txt&quot;) } | ConvertTo-Json </code></pre> <p>*Update: I am trying this code to get a similar result:</p> <pre><code>import json test_file = open(&quot;test.txt&quot;, &quot;rb&quot;) test_file_name = &quot;test.txt&quot; body = {&quot;filename&quot;:test_file_name,&quot;fileattachment&quot;:test_file} print(body) data = json.dumps(body) print(data) </code></pre> <p>The goal to find a pythonic method for this powershell snippet:</p> <pre><code> $endpoint =&quot;$destinationapi/secrets/$fileSecretId/fields/$fileFieldToUpdate&quot; echo $endpoint $secretArgs = @{ fileName = &quot;test.pem&quot; fileAttachment = [IO.File]::ReadAllBytes(&quot;C:\brian\13568-test.txt&quot;) } | ConvertTo-Json $response = $null $response = Invoke-RestMethod -Method Put -Uri $endpoint -Headers $destinationheaders -Body $secretArgs -ContentType &quot;application/json&quot; </code></pre>
[ { "answer_id": 74341852, "author": "d_frEak", "author_id": 12883179, "author_profile": "https://Stackoverflow.com/users/12883179", "pm_score": 0, "selected": false, "text": "df_combinec.columns=dataset2.columns" }, { "answer_id": 74341919, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "dataset2.columns" }, { "answer_id": 74342113, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([[1, 2]], columns=['A', 'B'])\ndf2 = pd.DataFrame([[3, 4]], columns=pd.MultiIndex.from_arrays([['A', 'B']]))\n\npd.concat([df, df2])\n\n# A B (A,) (B,)\n# 0 1.0 2.0 NaN NaN\n# 0 NaN NaN 3.0 4.0\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2308467/" ]
74,341,703
<blockquote> <p>Hello guys can anyone help me here, I've tried using display flex. However, the 6th box is overlapping I want my 6-10 Box stay on the 2nd row and if I add the 11th box it should start on the 3rd row can anyone help me with how can I accomplish it? Currently, it's working however my style is overlapping.</p> </blockquote> <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>.question-list-w { display: flex; flex-direction: column; gap: 10px; flex-wrap: wrap; height: 500px; } .question-list-w .horizontal-card { flex: 0 0 85px; } .horizontal-card { display: flex; border: 1px solid #ddd; border-radius: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="question-list-w"&gt; &lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;div class="horizontal-card"&gt; &lt;div class="horizontal-card-icon"&gt;&lt;/div&gt; &lt;div class="horizontal-card-text"&gt;survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont&lt;/div&gt; &lt;div class="horizontal-card-btn"&gt; &lt;button class="horizontal-card-btn btn-show-question" type="button" question-number="1"&gt;Show&lt;/button&gt; &lt;button class="horizontal-card-btn btn-start-question" question-number="1"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74341852, "author": "d_frEak", "author_id": 12883179, "author_profile": "https://Stackoverflow.com/users/12883179", "pm_score": 0, "selected": false, "text": "df_combinec.columns=dataset2.columns" }, { "answer_id": 74341919, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "dataset2.columns" }, { "answer_id": 74342113, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([[1, 2]], columns=['A', 'B'])\ndf2 = pd.DataFrame([[3, 4]], columns=pd.MultiIndex.from_arrays([['A', 'B']]))\n\npd.concat([df, df2])\n\n# A B (A,) (B,)\n# 0 1.0 2.0 NaN NaN\n# 0 NaN NaN 3.0 4.0\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16170674/" ]
74,341,704
<p>I'm trying to create an Excel spreadsheet and populate it with data from Word, but I can't get VBA to follow through. It launches Excel, but then it errors out.</p> <p>If I try early binding, such as with this code from the Microsoft Documentation, I get a Run-time error '13': Type mismatch on the <code>Set xlApp</code> line.</p> <pre><code>Sub test() Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Set xlApp = CreateObject(&quot;Excel.Application&quot;) Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets(1) End Sub </code></pre> <p>If I try late binding, I get a Run-time error '438': Object doesn't support this property or method on the <code>Set xlBook</code> line</p> <pre><code>Sub test() Dim xlApp As Object Dim xlBook As Object Dim xlSheet As Object Set xlApp = CreateObject(&quot;Excel.Application&quot;) Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets(1) End Sub </code></pre> <p>Many people throughout StackOverflow use variations of this successfully. I can't figure out why it doesn't work for me. One user on StackOverflow reported that the problem only persisted on their Mac. If it is a platform problem, is there a way to fix it so it will work on my Mac?</p>
[ { "answer_id": 74346731, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": -1, "selected": false, "text": "CreateObject" }, { "answer_id": 74374002, "author": "Darv", "author_id": 20436291, "author_profile": "https://Stackoverflow.com/users/20436291", "pm_score": 1, "selected": false, "text": "Sub test()\nDim xlApp As Object\nDim xlBook As Object\nDim xlSheet As Object\nSet xlApp = CreateObject(\"Excel.Application\")\nSet xlApp = xlApp.Parent\nSet xlBook = xlApp.Workbooks.Add\nSet xlSheet = xlBook.Worksheets(1)\nEnd Sub\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436291/" ]
74,341,751
<p>I am trying to get nested field's values from json which is returned by function <code>apex_web_service.make_rest_request</code>.</p> <pre><code>DECLARE v_address_json clob; v_address_response clob; l_object_address json_object_t; BEGIN SELECT json_object ('Addresses' value json_object( 'AddName' value ('HQ') , 'AddLine1' value tab1.ADDRESS_LINE1 , . . . . into v_address_json FROM tab1 t1, tab2 t2 WHERE ..... .....; v_address_response := apex_web_service.make_rest_request ( p_url =&gt; 'https://...../addresses', p_http_method =&gt; 'POST', p_body =&gt; v_address_json ); DBMS_OUTPUT.PUT_LINE('v_address_response : '||v_address_response); </code></pre> <p>At this point I am getting below in <code>v_address_response</code>.</p> <pre><code>{ &quot;Metadata&quot; : { &quot;application&quot; : &quot;&quot;, &quot;applicationRefId&quot; : &quot;&quot; }, &quot;APIResponse&quot; : { &quot;Status&quot; : &quot;SUCCESS&quot;, &quot;Error&quot; : { &quot;Code&quot; : &quot;&quot;, &quot;Message&quot; : &quot;&quot;, &quot;Detail&quot; : &quot;&quot; } }, &quot;ven&quot; : { &quot;Id&quot; : 12345, &quot;Addresses&quot; : [ { &quot;vAddId&quot; : 1122334455, &quot;vAddName&quot; : &quot;HQ&quot;, &quot;AddLine1&quot; : &quot;1/A2, ABC, XYZ ROAD, IN&quot;, &quot;City&quot; : &quot;JKL&quot;, &quot;State&quot; : &quot;AB&quot;, &quot;PCode&quot; : &quot;102030&quot;, &quot;Country&quot; : &quot;IN&quot;, &quot;TaxReg&quot; : [ { &quot;RegId&quot; : 998877, &quot;EffectiveFrom&quot; : &quot;2029-11-13&quot; } ], &quot;TaxRep&quot; : [ { &quot;TaxRepId&quot; : 665544, &quot;EffectiveFrom&quot; : &quot;2022-01-01&quot; } ] } ] } } </code></pre> <p>further I am trying to get field's value as below.</p> <pre><code> l_object_address := json_object_t.parse(v_address_response); if l_object_address.get_Object('APIResponse').get_string('Status') = 'SUCCESS' then DBMS_OUTPUT.PUT_LINE(' New Address ID : '||l_object_address.get_Object('Addresses').get_string('vAddId')); --output xx else DBMS_OUTPUT.PUT_LINE('Error in creating address'); end if; exception when others then null; end; </code></pre> <p>in the above section I am able to get value for <strong>APIResponse--&gt; Status i.e 'SUCCESS'</strong> but <strong>unable to get value of vAddId, RegId and other nested fields</strong>. At comment, output xx, nothing is getting printed.</p>
[ { "answer_id": 74346731, "author": "Eugene Astafiev", "author_id": 1603351, "author_profile": "https://Stackoverflow.com/users/1603351", "pm_score": -1, "selected": false, "text": "CreateObject" }, { "answer_id": 74374002, "author": "Darv", "author_id": 20436291, "author_profile": "https://Stackoverflow.com/users/20436291", "pm_score": 1, "selected": false, "text": "Sub test()\nDim xlApp As Object\nDim xlBook As Object\nDim xlSheet As Object\nSet xlApp = CreateObject(\"Excel.Application\")\nSet xlApp = xlApp.Parent\nSet xlBook = xlApp.Workbooks.Add\nSet xlSheet = xlBook.Worksheets(1)\nEnd Sub\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531157/" ]
74,341,767
<p>I'm using the following versions:</p> <ul> <li>&quot;@apollo/gateway&quot;: &quot;^2.1.3&quot;</li> <li>&quot;@apollo/server&quot;: &quot;^4.0.0&quot;</li> <li>&quot;graphql&quot;: &quot;^16.6.0&quot;</li> </ul> <p>I can't get a handle on the <code>req</code> object to extract the headers and forward them. The <code>buildService</code> code works to add headers to requests to downstream services, but the <code>context</code> on ApolloServer is consistently empty. I tried sync and async, request instead of req. I even tried grabbing them directly from <code>context.req.headers</code>, but that's null.</p> <p>Anyone have any idea on how to accomplish this?</p> <pre class="lang-js prettyprint-override"><code>const gateway = new ApolloGateway({ supergraphSdl: new IntrospectAndCompose({ subgraphs: [ { name: &quot;persons&quot;, url: process.env.PERSON_SERVER_URL }, ], }), buildService({ url }) { return new RemoteGraphQLDataSource({ url, willSendRequest: ({ request, context }) =&gt; { console.log(JSON.stringify(context)); // TRYING TO INJECT AUTH HEADERS HERE } }); } }); const app = express(); const httpServer = http.createServer(app); const server = new ApolloServer({ gateway, context: ({ req }) =&gt; { console.log(JSON.stringify(req)); // req IS NULL }, plugins: [ ApolloServerPluginLandingPageDisabled(), ApolloServerPluginDrainHttpServer({ httpServer }) ] }); await server.start(); const graphqlRoute = &quot;/graphql&quot;; app.use( graphqlRoute, bodyParser.json(), expressMiddleware(server), ); await new Promise((resolve) =&gt; httpServer.listen(process.env.PORT, &quot;0.0.0.0&quot;, resolve)); console.log(` Server ready at ${JSON.stringify(httpServer.address())}`); </code></pre> <p>For what it's worth, I asked <a href="https://community.apollographql.com/t/federation-forward-headers-to-subgraphs/4917" rel="nofollow noreferrer">here</a>, as well. This feels like it should be a simple flag (especially for federation) to forward the Authorization header.</p>
[ { "answer_id": 74353302, "author": "Dudo", "author_id": 1639575, "author_profile": "https://Stackoverflow.com/users/1639575", "pm_score": 0, "selected": false, "text": "app.use(\n graphqlRoute,\n cors(),\n bodyParser.json(),\n expressMiddleware(server, {\n context: async ({ req }) => ({\n token: req.headers.authorization\n }),\n }),\n);\n" }, { "answer_id": 74452115, "author": "Marcelo Salazar", "author_id": 222369, "author_profile": "https://Stackoverflow.com/users/222369", "pm_score": 1, "selected": false, "text": "const gateway = new ApolloGateway({\n supergraphSdl: new IntrospectAndCompose({\n subgraphs: [\n { name: \"persons\", url: process.env.PERSON_SERVER_URL },\n ],\n }),\n buildService({ url }) {\n return new RemoteGraphQLDataSource({\n url,\n willSendRequest: ({ request, context }) => {\n console.log(JSON.stringify(context));\n for (const [headerKey, headerValue] of Object.entries(context.headers)) {\n request.http?.headers.set(headerKey, headerValue);\n }\n }\n });\n }\n});\n\nconst app = express();\nconst httpServer = http.createServer(app);\n\nconst server = new ApolloServer({\n gateway,\n plugins: [\n ApolloServerPluginLandingPageDisabled(),\n ApolloServerPluginDrainHttpServer({ httpServer })\n ]\n});\nawait server.start();\n\nconst graphqlRoute = \"/graphql\";\n\nasync function context({ req }) {\n return {\n headers: req.headers,\n };\n}\n\napp.use(\n graphqlRoute,\n bodyParser.json(),\n expressMiddleware(server, {context: context}),\n);\n\nawait new Promise((resolve) => httpServer.listen(process.env.PORT, \"0.0.0.0\", resolve));\nconsole.log(` Server ready at ${JSON.stringify(httpServer.address())}`);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1639575/" ]
74,341,769
<p><code>docker ps</code></p> <p>Displays all the running containers<br><br> I want to display the total number of running containers<br><br> The command,<br></p> <p><code>docker ps | wc -l</code></p> <p>displays the line count but also counts headers as lines.</p> <p>How do I exclude headers? Also, is there another way to print the total number of running containers?</p>
[ { "answer_id": 74341862, "author": "atline", "author_id": 6394722, "author_profile": "https://Stackoverflow.com/users/6394722", "pm_score": 3, "selected": true, "text": "docker info" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18340568/" ]
74,341,796
<p>I am new to Kubernetes, I am creating POD on run time to push data and after pushing and collecting data I am deleting POD.</p> <p>For the processing of files I have connected SSD. and assigned its path as <strong>hostPath: /my-drive/example</strong> while creating POD. Now when i run my POD i can see the files in defined path.</p> <p>But, Now I just wanted to delete files created by POD in a hostPath directory while deleting POD. is it possible?</p> <p>My POD file looks like.</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: pod-example labels: app: pod-example spec: containers: - name: pod-example image: &quot;myimage.com/abcd:latest&quot; imagePullPolicy: Always workingDir: /pod-example env: volumeMounts: - name: &quot;my-drive&quot; mountPath: &quot;/my-drive&quot; volumes: - name: &quot;my-drive&quot; persistentVolumeReclaimPolicy: Recycle hostPath: path: /my-drive/example restartPolicy: Never imagePullSecrets: - name: regcred affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: &quot;kubernetes.io/hostname&quot; operator: In values: - my-node topologyKey: &quot;kubernetes.io/hostname&quot; </code></pre>
[ { "answer_id": 74341897, "author": "Sahan Gunathilaka", "author_id": 10031128, "author_profile": "https://Stackoverflow.com/users/10031128", "pm_score": 1, "selected": false, "text": "lifecycle" }, { "answer_id": 74341972, "author": "P Ekambaram", "author_id": 3270785, "author_profile": "https://Stackoverflow.com/users/3270785", "pm_score": 0, "selected": false, "text": "persistentVolumeReclaimPolicy: Delete\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15830657/" ]
74,341,833
<p>I am coming back from <code>NumPy</code> to <code>MATLAB</code> and don't quite have the hang of the broadcasting here. Can someone explain to me why the first one fails and the second (more explicit works)? After my understanding, <code>x0</code> and <code>x1</code> are both <code>1x2</code> arrays and it should be possible to extend them to <code>5x2</code>.</p> <pre><code>n_a = 5; n_b = 2; x0 = [1, 2]; x1 = [11, 22]; % c = unifrnd(x0, x1, [n_a, n_b]) % Error using unifrnd % Size information is inconsistent. % c = unifrnd(x0, x1, [n_a, 1]) % also fails c = unifrnd(ones(n_a, n_b) .* x0, ones(n_a, n_b) .* x1, [n_a, n_b]) % works </code></pre>
[ { "answer_id": 74341897, "author": "Sahan Gunathilaka", "author_id": 10031128, "author_profile": "https://Stackoverflow.com/users/10031128", "pm_score": 1, "selected": false, "text": "lifecycle" }, { "answer_id": 74341972, "author": "P Ekambaram", "author_id": 3270785, "author_profile": "https://Stackoverflow.com/users/3270785", "pm_score": 0, "selected": false, "text": "persistentVolumeReclaimPolicy: Delete\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7570817/" ]
74,341,848
<p>I have a JSON file that has movie data in it. I want to create a dictionary that has the movie title as the key and a count of how many actors are in that movie as the value. An example from the JSON file is below:</p> <pre><code> { &quot;title&quot;: &quot;Marie Antoinette&quot;, &quot;year&quot;: &quot;2006&quot;, &quot;genre&quot;: &quot;Drama&quot;, &quot;summary&quot;: &quot;Based on Antonia Fraser's book about the ill-fated Archduchess of Austria and later Queen of France, 'Marie Antoinette' tells the story of the most misunderstood and abused woman in history, from her birth in Imperial Austria to her later life in France.&quot;, &quot;country&quot;: &quot;USA&quot;, &quot;director&quot;: { &quot;last_name&quot;: &quot;Coppola&quot;, &quot;first_name&quot;: &quot;Sofia&quot;, &quot;birth_date&quot;: &quot;1971&quot; }, &quot;actors&quot;: [ { &quot;first_name&quot;: &quot;Kirsten&quot;, &quot;last_name&quot;: &quot;Dunst&quot;, &quot;birth_date&quot;: &quot;1982&quot;, &quot;role&quot;: &quot;Marie Antoinette&quot; }, { &quot;first_name&quot;: &quot;Jason&quot;, &quot;last_name&quot;: &quot;Schwartzman&quot;, &quot;birth_date&quot;: &quot;1980&quot;, &quot;role&quot;: &quot;Louis XVI&quot; } ] } </code></pre> <p>I have the following but it's counting all of the actors from all of the movies instead of each movie and the number of actors per movie. I'm not sure how to do this correctly as I'm newer to Python so help would be great.</p> <pre><code>import json def actor_count(json_data): with open(&quot;movies_db.json&quot;, 'r') as file: data = json.load(file) for t in data: title = [t['title'] for t in data] for element in data: for actor in element['actors']: rolee = [actor['role'] for movie in data for actor in movie['actors']] len_role = [len(role)] newD = dict(zip(title, len_role)) print(newD) json_data = open('movies_db.json') actor_count(json_data) </code></pre>
[ { "answer_id": 74343564, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def actor_count(json_data):\n newD = dict()\n with open(\"movies_db.json\", 'r') as file:\n data = json.load(file)\n for t in data:\n if t == 'title':\n title_ = json_data[t]\n newD[ title_ ] = 0\n if t == 'actors':\n newD[ title_ ] = len(json_data[t])\n print(newD)\n" }, { "answer_id": 74352983, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": true, "text": "data" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10289804/" ]
74,341,855
<p>I'm trying to think of a way to make functions that determine the winner of an election by most votes, as well as a function that determines a winner-takes-all rule.</p> <p>My code is as follows:</p> <pre><code>_base_dict = {} def add_state(name: str, votes: dict[str, int]) -&gt; None: global _base_dict for name, votes in _base_dict.items(): _base_dict[name] += votes def winner(college: dict[str, int]) -&gt; str: global _base_dict rv = None bigger_percentage = 0 for state, total_votes in college.items(): majority = total_votes // 2 for name, votes in _base_dict.items(): if votes[state] &gt; majority: percentage = votes[state] / float(total_votes) if percentage &gt; bigger_percentage: bigger_percentage = percentage rv = name elif percentage == bigger_percentage: rv = None if rv is None: return &quot;No Winner&quot; return rv def clear() -&gt; None: global _base_dict _base_dict.clear() _base_dict.update(_base_dict) </code></pre> <p>and on a test file, I am running the functions through this:</p> <pre><code>import elections college = {'Virginia': 13, 'Ohio': 18, 'Minnesota': 10, 'Alabama': 9, 'Maine': 4 } print(elections.winner({})) elections.add_state('Virginia', { 'Turing': 15, 'Lovelace': 20, 'Dijkstra': 10 }) elections.add_state('Ohio', { 'Turing': 1, 'Dijkstra': 15 }) elections.add_state('Alabama', { 'Turing': 10, 'Lovelace': 20, 'Dijkstra': 8 }) print(elections.winner(college)) elections.add_state('Minnesota', { 'Lovelace': 10, 'Dijkstra': 30, }) elections.add_state('Florida', { 'Turing': 10, 'Lovelace': 30, 'Dijkstra': 15 }) print(elections.winner(college)) elections.clear() elections.add_state('Maine', { 'Turing': 2, 'Dijkstra': 1, 'Lovelace': 5 }) print(elections.winner(college)) </code></pre> <p>My desired output is:</p> <pre><code>No Winner Lovelace Dijkstra Lovelace </code></pre> <p>but I keep getting:</p> <pre><code>No Winner No Winner No Winner No Winner </code></pre> <p>I do not know what I am doing wrong. Any help is appreciated. Edit: I prefer to use logic to solve this issue, though imports are also appreciated.</p>
[ { "answer_id": 74343564, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def actor_count(json_data):\n newD = dict()\n with open(\"movies_db.json\", 'r') as file:\n data = json.load(file)\n for t in data:\n if t == 'title':\n title_ = json_data[t]\n newD[ title_ ] = 0\n if t == 'actors':\n newD[ title_ ] = len(json_data[t])\n print(newD)\n" }, { "answer_id": 74352983, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": true, "text": "data" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20322128/" ]
74,341,861
<p>Now I'm using WSL 2 and Docker Desktop on Windows 10.</p> <p>I created an YAML script to create an ingress for my microservices like below.</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-srv annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: posts.com http: paths: - path: /posts pathType: Prefix backend: service: name: posts-clusterip-srv port: number: 4000 </code></pre> <p>And I installed ingress-nginx by following this <a href="https://kubernetes.github.io/ingress-nginx/deploy/" rel="nofollow noreferrer">installation guide</a></p> <p>I ran this command in the guide.</p> <p><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.4.0/deploy/static/provider/cloud/deploy.yaml</code></p> <p>But when I ran <code>kubectl get pods --namespace=ingress-nginx</code>, <code>ingress-nginx-controller</code> shows <code>ImageInspectError</code> <a href="https://i.stack.imgur.com/uthyL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uthyL.png" alt="ImageInspectError" /></a></p> <p>And when I ran the command <code>kubectl apply -f ingress-srv.yaml</code>, it showed an error message. <a href="https://i.stack.imgur.com/5li4R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5li4R.png" alt="Ingress error message" /></a></p> <p>Can anyone please let me know what the issue is?</p> <p>I removed the namespace <code>ingress-nginx</code> using this command <code>kubectl delete all --all -n ingress-nginx</code> and ran the deploy script again.</p> <p><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.4.0/deploy/static/provider/cloud/deploy.yaml</code></p> <p>But the issue still happened.</p>
[ { "answer_id": 74350507, "author": "Daniel Morales", "author_id": 18616389, "author_profile": "https://Stackoverflow.com/users/18616389", "pm_score": 0, "selected": false, "text": "docker system prune" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18616389/" ]
74,341,887
<p>I am trying to get a hold over understanding Applicative functors currently. And my understanding is falling short somewhere but I cannot pinpoint where. Source from where I am trying to build an understanding <a href="https://www.cis.upenn.edu/%7Ecis1940/spring13/lectures.html" rel="nofollow noreferrer">CIS 194 UPenn</a> - <a href="https://www.cis.upenn.edu/%7Ecis1940/spring13/hw/10-applicative.pdf" rel="nofollow noreferrer">Homework 10</a></p> <p>I am working with a custom data type and its Applicative instance which are as follows :</p> <pre><code>-- A parser for a value of type a is a function which takes a String -- represnting the input to be parsed, and succeeds or fails; if it -- succeeds, it returns the parsed value along with the remainder of -- the input. newtype Parser a = Parser { runParser :: String -&gt; Maybe (a, String) } instance Functor Parser where fmap :: (a -&gt; b) -&gt; Parser a -&gt; Parser b fmap fn parserA = Parser (fmap (first fn) . parseAFunc) where parseAFunc = runParser parserA appliedFunc p1 p2 str = case runParser p1 str of Nothing -&gt; Nothing Just (f, str2) -&gt; case runParser p2 str2 of Nothing -&gt; Nothing Just (x, str3) -&gt; Just (f x, str3) instance Applicative Parser where pure a = Parser (\s -&gt; Just (a, s)) p1 &lt;*&gt; p2 = Parser (appliedFunc p1 p2) -- For example, 'satisfy' takes a predicate on Char, and constructs a -- parser which succeeds only if it sees a Char that satisfies the -- predicate (which it then returns). If it encounters a Char that -- does not satisfy the predicate (or an empty input), it fails. satisfy :: (Char -&gt; Bool) -&gt; Parser Char satisfy p = Parser f where f [] = Nothing -- fail on the empty input f (x:xs) -- check if x satisfies the predicate -- if so, return x along with the remainder -- of the input (that is, xs) | p x = Just (x, xs) | otherwise = Nothing -- otherwise, fail -- Using satisfy, we can define the parser 'char c' which expects to -- see exactly the character c, and fails otherwise. char :: Char -&gt; Parser Char char c = satisfy (== c) -- Below is a parser for positive Ints which parses -- the prefix of contiguous digits in a given String -- as an Int posUse :: Parser Int posUse = Parser f where f xs | null ns = Nothing | otherwise = Just (read ns, rest) where (ns, rest) = span isDigit xs -- Below function takes a function and a pair and returns a pair -- with the function applied to the first element of pair first :: (a -&gt; b) -&gt; (a, c) -&gt; (b, c) first fn (x, y) = (fn x, y) </code></pre> <p>Using all the above setup, I am trying to construct some more complicated Parsers using simple Parsers defined above. So fmap has type <code>fmap :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b</code>. And as per my understanding currently, Applicative allows us to extend <code>fmap</code> to functions that take n-ary functions and n Functor parameters and return the resultant functor.</p> <p><code>fmap</code> can be defined in terms of <code>pure</code> and <code>&lt;*&gt;</code> as :</p> <pre><code>fmap1 :: Applicative f =&gt; (a -&gt; b) -&gt; f a -&gt; f b fmap1 f x = pure f &lt;*&gt; x </code></pre> <p>I understand why the above will work given that the implementations of <code>pure</code> and <code>&lt;*&gt;</code> are appropriate since the types nicely line up.</p> <p>Extending this to <code>fmap2</code> aka <code>liftA2</code> :</p> <pre><code>fmap2 :: Applicative f =&gt; (a -&gt; b -&gt; c) -&gt; f a -&gt; f b -&gt; f c fmap2 f x y = pure f &lt;*&gt; x &lt;*&gt; y </code></pre> <p>My understanding of why the above works is as follows : <code>pure g</code> will have type <code>f (a -&gt; b -&gt; c)</code> And so therefore <code>pure g &lt;*&gt; x</code> will have type <code>f (b -&gt; c)</code> since functions are curried. Then this type combined with the type type of y (<code>f b</code>) using <code>&lt;*&gt;</code> will finally give us the type of the result which is <code>f c</code> which is what we needed the type <code>fmap2</code> to be.</p> <p>This understanding did not break down when I tried to construct a Parser out of 2 simple Parsers as follows :</p> <pre><code>-- This Parser expects to see the characters ’a’ and ’b’ and returns them -- as a pair. abParser = liftA2 (\c1 c2 -&gt; (c2 c1)) (char 'a') (char 'b') </code></pre> <p>The above works as expected.</p> <p>But when I try to make the parser <code>intPair</code> which reads two integer values separated by a space and returns the integer values in a list using <code>liftA3</code> my understanding of lift is not working since I expect the following to work but the linter complains :</p> <pre><code>intPair :: Parser [Int] intPair = liftA3 (\x y z -&gt; [z x]) posUse (char ' ') posUse </code></pre> <p>The above does not compile as the last argument needs to have the type <code>Parser (Int -&gt; a)</code> (according to type inference) but I have passed <code>posUse</code> which has the type <code>Parser Int</code>.</p> <p>TL;DR : Sorry for the long description. If anyone does not want to go through it all (expecially the custom data type and its Applicative and Functor instance) -- please let me know if my understanding of why <code>fmap2</code> aka <code>liftA2</code> works is correct and how does that understanding extend to <code>liftA3</code> ? The definition of <code>liftA3</code> seems to be something different than just an extension of the definition of <code>liftA2</code> using <code>&lt;*&gt;</code> and <code>pure</code>.</p> <p>Edit 1 : As stated above, the below line was being complained about by the linter</p> <pre><code>intPair :: Parser [Int] intPair = liftA3 (\x y z -&gt; [z x]) posUse (char ' ') posUse </code></pre> <p>The linter expected the type for the last argument to be <code>Parser (Int -&gt; a)</code>. But after I defined an explicit function instead of passing a lambda, it worked as I expected to work.</p> <pre><code>fnn :: Int -&gt; Char -&gt; Int -&gt; [Int] fnn arg1 arg2 arg3 = [arg1, arg3] intPair = liftA3 fnn posUse (char ' ') posUse </code></pre> <p>It works as I expected.</p>
[ { "answer_id": 74344578, "author": "amalloy", "author_id": 625403, "author_profile": "https://Stackoverflow.com/users/625403", "pm_score": 2, "selected": false, "text": "liftA2" }, { "answer_id": 74356072, "author": "Daniel Wagner", "author_id": 791604, "author_profile": "https://Stackoverflow.com/users/791604", "pm_score": 2, "selected": true, "text": "fnn arg1 arg2 arg3 = [arg1, arg3] -- your working code\nfnn = \\x y z -> [z x] -- your broken code\nfnn = \\x y z -> [z, x] -- type-correct code\nfnn = \\x y z -> [x, z] -- more correct translation of your working code\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9268887/" ]
74,341,905
<p>For this project I am working on, I have a list of strings of equal length (so the length may vary), and I only want the strings whose substrings can be found in a string that I have specified.</p> <p>Will elaborate further, but the following is the expected result.</p> <pre><code># list of strings [&quot;aa&quot;, &quot;ct&quot;, &quot;ab&quot;, &quot;ac&quot;, &quot;bd&quot;, &quot;ra&quot;, &quot;db&quot;, &quot;pq&quot;, &quot;cb&quot;] # a subset of this list is not included in a new list because they do not contain a/b/c/d # -&gt; this list of strings [&quot;aa&quot;, &quot;ab&quot;, &quot;ac&quot;, &quot;bd&quot;, &quot;db&quot;, &quot;cb&quot;] # in other words, &quot;ct&quot;, &quot;ra&quot;, &quot;pq&quot; are excluded </code></pre> <p>However, when I print the new list of valid strings as shown below, every string except for &quot;pq&quot; is included. It seems to yield a similar result as using the any() function, which would be great if only it does what I want it to.</p> <pre><code>list_of_strings = [&quot;aa&quot;, &quot;ct&quot;, &quot;ab&quot;, &quot;ac&quot;, &quot;bd&quot;, &quot;ra&quot;, &quot;db&quot;, &quot;pq&quot;, &quot;cb&quot;] def isValidString(seq): for substring in seq: if substring in &quot;abcd&quot;: return True valid_strings = [] for sequence in list_of_strings: if isValidString(sequence): valid_strings.append(sequence) print(valid_strings) # Output : ['aa', 'ct', 'ab', 'ac', 'bd', 'ra', 'db', 'cb'] </code></pre>
[ { "answer_id": 74341966, "author": "Lokeshwar G", "author_id": 12588118, "author_profile": "https://Stackoverflow.com/users/12588118", "pm_score": 0, "selected": false, "text": "['aa', 'ab', 'ac', 'bd', 'db', 'cb']\n" }, { "answer_id": 74341974, "author": "Prashant Pansuriya", "author_id": 13423027, "author_profile": "https://Stackoverflow.com/users/13423027", "pm_score": 0, "selected": false, "text": "using yield keyword.\n\ndef string_match(list_of_strings):\n for data in list_of_strings:\n for char_data in data:\n if char_data in \"abcd\":\n yield data\n break\nfor data in string_match(list_of_strings):\n print(data)\n" }, { "answer_id": 74342042, "author": "Kings_M", "author_id": 12904301, "author_profile": "https://Stackoverflow.com/users/12904301", "pm_score": 1, "selected": false, "text": "list_of_strings = [\"aa\", \"ct\", \"ab\", \"ac\", \"bd\", \"ra\", \"db\", \"pq\", \"cb\"]\n\ndef isValidString(seq):\n for substring in seq:\n if substring not in \"abcd\":\n return False\n return True\n \n\nvalid_strings = []\n\nfor sequence in list_of_strings:\n if isValidString(sequence):\n valid_strings.append(sequence)\n print(\"\\n\")\n\nprint(valid_strings)\n" }, { "answer_id": 74342045, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "list_of_strings = [\"aa\", \"ct\", \"ab\", \"ac\", \"bd\", \"ra\", \"db\", \"pq\", \"cb\"]\n\ndef isValidString(seq):\n nb_matches = 0\n \n for substring in seq:\n if substring in \"abcd\":\n nb_matches += 1\n if nb_matches == len(seq):\n return True\n\nvalid_strings = []\n\nfor sequence in list_of_strings:\n if isValidString(sequence):\n valid_strings.append(sequence)\n\nprint(valid_strings)\n" }, { "answer_id": 74342074, "author": "Hu gePanic", "author_id": 12189751, "author_profile": "https://Stackoverflow.com/users/12189751", "pm_score": 0, "selected": false, "text": "data = [\"aa\", \"ct\", \"ab\", \"ac\", \"bd\", \"ra\", \"db\", \"pq\", \"cb\"]\nsearchstring = [\"aa\", \"ab\", \"ac\", \"bd\", \"db\", \"cb\"]\n\nnewdata = [s for s in data if s in searchstring]\nprint(newdata)\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15748497/" ]
74,341,942
<p>I'm setting up ui for my Lazy column and I'm getting data from api</p> <pre><code>@Preview @Composable fun MatchesRow(data: Data ) { Card( modifier = Modifier .height(180.dp), backgroundColor = MaterialTheme.colors.background ) { }} </code></pre> <p>i get erros because my parameters are empty , how can i Preview ??</p>
[ { "answer_id": 74342186, "author": "Vahid Garousi", "author_id": 5909910, "author_profile": "https://Stackoverflow.com/users/5909910", "pm_score": 1, "selected": false, "text": "@Composable\nfun MatchesRow(data: Data ) {\n Card(\n modifier = Modifier\n .height(180.dp),\n backgroundColor = MaterialTheme.colors.background\n ) {\n}}\n\n\n@Preview\n@Composable\nfun MatchesRowPreview() {\nval data = .....\n MatchesRow(\n data = data\n )\n}\n" }, { "answer_id": 74342433, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 0, "selected": false, "text": "@PreviewParameter" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19868078/" ]
74,341,964
<p>I'm trying to generate a list of random numbers. I thought this would be a good time to use list comprehension to shorten the code. The only problem is that now I have this unused &quot;i&quot; variable. Is there a way to write it without needing that variable, or should I not worry about it too much?</p> <pre><code>int_list = [random.randrange(0, 50) for i in range(10)] </code></pre>
[ { "answer_id": 74341983, "author": "CutePoison", "author_id": 6224975, "author_profile": "https://Stackoverflow.com/users/6224975", "pm_score": 2, "selected": false, "text": "_" }, { "answer_id": 74342117, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "[random.randrange(0, 50) for i in range(10)]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20206433/" ]
74,341,976
<p>The following config (filterChain) works fine in SpringBoot-2.7.5, but after I tried to test it in SpringBoot-3.0.0-RC1, it is not working and shows the following message, anything I need to change if want to migrate to Spring-Boot-3.0.0. Thanks.</p> <blockquote> <p>{ &quot;timestamp&quot;: 1667794247614, &quot;status&quot;: 401, &quot;error&quot;: &quot;Unauthorized&quot;, &quot;message&quot;: &quot;An Authentication object was not found in the SecurityContext&quot;, &quot;path&quot;: &quot;/api/admin/1&quot; }</p> </blockquote> <pre><code> @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationProvider).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(&quot;/**&quot;).permitAll() // private endpoints .anyRequest().authenticated(); http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } </code></pre> <p>The following is the jwtTokenFilter:</p> <pre><code>@Component public class **JwtTokenFilter** extends OncePerRequestFilter { @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private JPAUserDetailService jpaUserDetailService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { // Get authorization header and validate final String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (isEmpty(header) || !header.startsWith(&quot;Bearer &quot;)) { chain.doFilter(request, response); return; } // Get jwt token and validate final String token = header.split(&quot; &quot;)[1].trim(); if (!jwtTokenUtil.validate(token)) { chain.doFilter(request, response); return; } // Get user identity and set it on the spring security context UserDetails userDetails = jpaUserDetailService.loadUserByUsername(jwtTokenUtil.getUsername(token)); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, (userDetails == null ? null : userDetails.getAuthorities())); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request, response); } } </code></pre>
[ { "answer_id": 74341983, "author": "CutePoison", "author_id": 6224975, "author_profile": "https://Stackoverflow.com/users/6224975", "pm_score": 2, "selected": false, "text": "_" }, { "answer_id": 74342117, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "[random.randrange(0, 50) for i in range(10)]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74341976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3156889/" ]
74,342,021
<p>I have application developed using Apache Cordova, within that application I am using &quot; inappbrowser &quot;. Now the requirement is to open Camera from the inappbrowser, I'm not able to figure out how to achieve this.</p> <p>For developing this application I am using JQuery, bootstrap.js.</p> <p>Now i'm using navigator.mediaDevices.getUserMedia in Inappbrowser. but i get this error</p> <p><code>NotAllowedError: Permissin denied</code></p> <p>But i want to open camera and gallery instead of this.</p>
[ { "answer_id": 74341983, "author": "CutePoison", "author_id": 6224975, "author_profile": "https://Stackoverflow.com/users/6224975", "pm_score": 2, "selected": false, "text": "_" }, { "answer_id": 74342117, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "[random.randrange(0, 50) for i in range(10)]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20157381/" ]
74,342,024
<p>Kindly look at this this here you can see here is mentioned (8 left) i want to replace (left with places left) means in simple i want to show 8 places left…</p> <p><a href="https://digitalrise.website/product/kayak-lisbon/?date=2022-11-07" rel="nofollow noreferrer">https://digitalrise.website/product/kayak-lisbon/?date=2022-11-07</a></p> <p>Here is link below</p>
[ { "answer_id": 74341983, "author": "CutePoison", "author_id": 6224975, "author_profile": "https://Stackoverflow.com/users/6224975", "pm_score": 2, "selected": false, "text": "_" }, { "answer_id": 74342117, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "[random.randrange(0, 50) for i in range(10)]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18643660/" ]
74,342,025
<p>The output of the db.name.aggregate() function gives output:</p> <pre class="lang-json prettyprint-override"><code>[{}, {&quot;abc&quot;: &quot;zyx&quot;}, {}, &quot;opk&quot;: &quot;tyr&quot;] </code></pre> <p>Actual output desired :</p> <pre class="lang-json prettyprint-override"><code>[{&quot;abc&quot;: &quot;zyx&quot;}, &quot;opk&quot;: &quot;tyr&quot;] </code></pre>
[ { "answer_id": 74341983, "author": "CutePoison", "author_id": 6224975, "author_profile": "https://Stackoverflow.com/users/6224975", "pm_score": 2, "selected": false, "text": "_" }, { "answer_id": 74342117, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "[random.randrange(0, 50) for i in range(10)]\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6775283/" ]
74,342,038
<p>I have problem when I use bloc.</p> <pre><code>/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/provider-6.0.4/lib/src/provider.dart:343:7: Error: 'sthrow' isn't a type. sthrow ProviderNotFoundException(T, context.widget.runtimeType); ^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/provider-6.0.4/lib/src/provider.dart:343:14: Error: Expected ';' after this. sthrow ProviderNotFoundException(T, context.widget.runtimeType); ^^^^^^^^^^^^^^^^^^^^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/provider-6.0.4/lib/src/provider.dart:343:41: Error: Expected ')' before this. sthrow ProviderNotFoundException(T, context.widget.runtimeType); ^ 2 FAILURE: Build failed with an exception. * Where: Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159 * What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'. &gt; Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1 * Try: &gt; Run with --stacktrace option to get the stack trace. &gt; Run with --info or --debug option to get more log output. &gt; Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 8s Exception: Gradle task assembleDebug failed with exit code 1 </code></pre> <p><strong>RouteGenerator.dart</strong>:</p> <pre><code>static Route&lt;dynamic&gt;? onRouteGenerator(RouteSettings settings) { switch (settings.name) { case &quot;/&quot;: return MaterialPageRoute( builder: (context) =&gt; BlocProvider( create: (_) =&gt; di.locator&lt;SplashBloc&gt;(), child: const SplashScreen(), ), ); case &quot;/iws&quot;: return MaterialPageRoute( builder: (context) =&gt; BlocProvider( create: (_) =&gt; di.locator&lt;UsersBloc&gt;(), child: const InputWellStatus(), ), ); case &quot;/login&quot;: return MaterialPageRoute( builder: (context) =&gt; BlocProvider( create: (_) =&gt; di.locator&lt;LoginBloc&gt;(), child: Login(), ), ); case &quot;/iwpt&quot;: return MaterialPageRoute( builder: (context) =&gt; const InputWellProdTest(), ); case &quot;/iss&quot;: return MaterialPageRoute( builder: (context) =&gt; const InputSonologStatus(), ); default: return null; } } </code></pre> <p>I beg you to help me solve this problem.</p>
[ { "answer_id": 74342060, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" }, { "answer_id": 74342333, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436809/" ]
74,342,065
<p>The keyboard is cutting off part of the input field</p> <p>I am using a TextFormField</p> <p><a href="https://i.stack.imgur.com/KHWuP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KHWuP.png" alt="keyboard cutting off part of input field" /></a></p> <p>is there anyway to push the screen up?</p>
[ { "answer_id": 74342060, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" }, { "answer_id": 74342333, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17281101/" ]
74,342,102
<p>I have a dataframe like below</p> <pre><code>df = pd.DataFrame({'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2], 'time_1' :['2017-04-03 12:35:00','2017-04-03 12:50:00','2018-04-05 12:59:00','2018-05-04 13:14:00','2017-05-05 13:37:00','2018-07-06 13:39:00','2018-07-08 11:30:00','2017-04-08 16:00:00','2019-04-09 22:00:00','2019-04-11 04:00:00','2018-04-13 04:30:00','2017-04-14 08:00:00'], 'val' :[5,5,5,5,1,6,5,5,8,3,4,6], 'Prod_id':['A','B','C','A','E','Q','G','F','G','H','J','A']}) df['time_1'] = pd.to_datetime(df['time_1']) </code></pre> <p>I would like to do the below</p> <p>a) groupby <code>subject_id</code> and <code>time_1</code> using <code>freq=</code>3M`</p> <p>b) return only the aggregated values of <code>Prod_id</code> column (and drop index)</p> <p>So, I tried the below</p> <pre><code>df.groupby(['subject_id',pd.Grouper(key='time_1', freq='3M')])['Prod_id'].nunique() </code></pre> <p>Though the above works but it returned the group by columns as well in the output.</p> <p>So, I tried the below using <code>as_index=False</code></p> <pre><code>df.groupby(['subject_id',pd.Grouper(key='time_1', freq='3M'),as_index=False])['Prod_id'].nunique() </code></pre> <p>But still it didn't give the exepected output</p> <p>I expect my output to be like as shown below</p> <pre><code>uniq_prod_cnt 2 1 1 3 2 1 2 </code></pre>
[ { "answer_id": 74342060, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" }, { "answer_id": 74342333, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829044/" ]
74,342,105
<p>I have a dataframe</p> <pre><code>df =pd. DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'two', 'three', 'three', 'four', 'five'], 'C' : [2,3,4,9,12,12,17,13]}) </code></pre> <p>I would like to add a new column New, equal to C value/ C value where B= 'one' per group(group by A), the output would like:</p> <pre class="lang-none prettyprint-override"><code>A B C New foo one 2 1 bar one 3 1 foo two 4 2 bar two 9 3 foo three 12 6 bar three 12 4 foo four 17 8.5 foo five 13 6.5 </code></pre> <p>My code is</p> <pre><code>grouped = df.groupby(['A']).head(7) grouped['new']= grouped['C']/df[grouped['B']=='one']['C'] </code></pre> <p>output is not I expected:</p> <pre class="lang-none prettyprint-override"><code>A B C new foo one 2 1 bar one 3 1 foo two 4 NaN bar two 9 NaN foo three 12 NaN bar three 12 NaN foo four 17 NaN foo five 13 NaN </code></pre>
[ { "answer_id": 74342060, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" }, { "answer_id": 74342333, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20113479/" ]
74,342,130
<p>I am getting the below error, please check the image.</p> <p><a href="https://i.stack.imgur.com/XjuGT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjuGT.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74342060, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" }, { "answer_id": 74342333, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "sthrow ProviderNotFoundException(T, context.widget.runtimeType);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10922432/" ]
74,342,135
<p>can anyone help me how to convert this into loops :) hi newbie here in javaScript:) the output of this is a input form, i want all the value that typed into the form to be appear instantly by using keyup event thanks in advance :)</p> <pre><code>let textarea = document.querySelectorAll('span') let bns = document.querySelector('#bns'); let id = document.querySelector('#id'); let img = document.querySelector('#img'); let lg = document.querySelector('#lg'); textarea.forEach(function (item, index) { item.classList.add('t'+ `${index}`) //console.log(item) }) let input = addEventListener('keyup', function(){ let strbns = bns.value; let strid = id.value; let strimg = img.value; let strblg = lg.value; document.querySelector('.t0').innerText = strbns document.querySelector('.t1').innerText = strid document.querySelector('.t2').innerText = strimg document.querySelector('.t3').innerText = strblg }); </code></pre> <p>output <a href="https://i.stack.imgur.com/rmpGV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rmpGV.jpg" alt="enter image description here" /></a></p> <p>i create variables to each input field and used the keyup event to print the out put to individual span. yes it works but its so repetitive and i thinks it is much better if it's convert it into for loops but i dont know how</p>
[ { "answer_id": 74342157, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 0, "selected": false, "text": "const elements = [bns, id, img, lg];\nconst selectors = [\".t0\", \".t1\", \".t2\", \".t3\"].map((s) => document.querySelector(s));\n\naddEventListener('keyup', function() {\n elements.forEach((el, index) => {\n selectors[index].innerText = el.value;\n });\n});\n" }, { "answer_id": 74342815, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": false, "text": "const formData = {\n bns: document.querySelector('#bns'),\n id: document.querySelector('#id'),\n img: document.querySelector('#img'),\n lg: document.querySelector('#lg')\n};\n\ndocument.addEventListener('keyup', function() {\n Object.keys(formData).forEach((key, index) => {\n document.querySelector(`.t${index}`).innerText = formData[key].value\n })\n});" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436713/" ]
74,342,144
<p>I am very new to coding. I am having issue solving this following: taking a data block ex:</p> <pre><code>1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42 </code></pre> <p>and covert into something like</p> <pre><code>1963,&quot;john, doe&quot;,&quot;Williwanka,tp&quot;,jane,4200,1300,19.63,-42 </code></pre> <p>I know I can use <code>split()</code> and <code>join()</code> however having trouble sorting through the string separated by comma &quot;,&quot; and add double quote.</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>let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42"; var myArray = text.split(";"); var newText = ""; for (var i = 0; i &lt;= myArray.length; i++) { if (myArray.indexOf(i) == ",") { let newText = '"' + fruits.join('","') + '"'; } else { newText += text.index(i); } } return newText</code></pre> </div> </div> </p>
[ { "answer_id": 74342175, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "const text = \"1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42\";\n\nconst parts = text.split(\";\");\n\nconst result = parts.map((p) => p.includes(\",\") ? `\"${p}\"` : p).join(\",\");\n\nconsole.log(result);" }, { "answer_id": 74342423, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 0, "selected": false, "text": "/([^;]+)(?:;|$)/" }, { "answer_id": 74348524, "author": "blurfus", "author_id": 600486, "author_profile": "https://Stackoverflow.com/users/600486", "pm_score": 0, "selected": false, "text": "let text = \"00077;Jessica;Williamsburg,ky;40769;42;42;42;42\";\nvar partsArray = text.split(\";\");\nvar newText = \"\";\n\n\nfor (var i = 0; i < partsArray.length; i++) {\n let onePart = partsArray[i];\n\n if (onePart.includes(\",\")) {\n newText += `\"${onePart}\"`;\n } else {\n newText += onePart;\n }\n newText += \",\";\n}\n\nconsole.log(newText);" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436703/" ]
74,342,180
<p>I am reading json file from adls then write it back to ADLS by changing extension to .csv but some random filename is creating in ADLS (writing script in azure synapse)</p> <p>One _success file and part-000-***.csv like this some random file name is generating</p> <p>I want my file name is to be save ex: sfmc.json it should be write in adls as sfmc.csv</p>
[ { "answer_id": 74342175, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "const text = \"1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42\";\n\nconst parts = text.split(\";\");\n\nconst result = parts.map((p) => p.includes(\",\") ? `\"${p}\"` : p).join(\",\");\n\nconsole.log(result);" }, { "answer_id": 74342423, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 0, "selected": false, "text": "/([^;]+)(?:;|$)/" }, { "answer_id": 74348524, "author": "blurfus", "author_id": 600486, "author_profile": "https://Stackoverflow.com/users/600486", "pm_score": 0, "selected": false, "text": "let text = \"00077;Jessica;Williamsburg,ky;40769;42;42;42;42\";\nvar partsArray = text.split(\";\");\nvar newText = \"\";\n\n\nfor (var i = 0; i < partsArray.length; i++) {\n let onePart = partsArray[i];\n\n if (onePart.includes(\",\")) {\n newText += `\"${onePart}\"`;\n } else {\n newText += onePart;\n }\n newText += \",\";\n}\n\nconsole.log(newText);" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376563/" ]
74,342,196
<p>I am new to Gatling and Scala , I am trying to run the Gatling test example specified in the beginning parts of this video: <a href="https://www.youtube.com/watch?v=To7LJiK87Us" rel="nofollow noreferrer">https://www.youtube.com/watch?v=To7LJiK87Us</a>, but using Gradle wrapper. I created a gradle project in IntelliJ idea and the build.gradle file is below</p> <pre><code>buildscript { repositories { maven { url '&lt;url&gt;' credentials { &lt;&gt;&lt;&gt; } } } dependencies { classpath &quot;gradle.plugin.io.gatling.gradle:gatling-gradle-plugin:3.8.4&quot; } } apply plugin: &quot;io.gatling.gradle&quot; apply plugin: 'scala' repositories { maven { url '&lt;&gt;' credentials { &lt;&gt;&lt;&gt; } } mavenCentral() } dependencies { implementation 'org.scala-lang:scala-library:2.12.4' gatling 'org.scala-lang:scala-library:2.12.4' gatling 'au.com.bytecode:opencsv:2.4' gatling group: 'org.scalaj', name: 'scalaj-http_2.12', version: '2.3.0' gatling group: 'org.json4s', name: 'json4s-native_2.12', version: '3.5.3' } compileGatlingScala { scalaCompileOptions.additionalParameters = [&quot;-feature&quot;] } gatling { simulations = { // Enable ALL perf testing, regardless of current pass/fail state include &quot;**/simulation/*Simulation*.scala&quot; } } sourceSets.gatling.resources.srcDir('conf') gatling { logLevel = 'WARN' // logback root level logHttp = 'ALL' } </code></pre> <p>Note: I have a few extra dependencies here like 'opencsv' that I will be needing later for the actual performance testing.</p> <p>And my LoadSimulation script is as below</p> <pre><code>class LoadSimulation extends Simulation { val scn = scenario(&quot;JSON&quot;) .exec( http(&quot;GET&quot;) .get(&quot;http://jsonplaceholder.typicode.com/comments&quot;) ) setUp( scn.inject(atOnceUsers(1)) ) } </code></pre> <p>When I try to run the performance test using gradlew, it says &quot;build successful', but I don't see a result in the reports folder under /build</p> <pre><code>&gt;gradlew gatlingRun-LoadSimulation BUILD SUCCESSFUL in 1s 3 actionable tasks: 1 executed, 2 up-to-date </code></pre> <p>Could anyone please tell me what I am doing wrong? Is this not how I should be running it?</p> <p><strong>EDIT</strong> Updated to below dependencies as per answers below, still the same result, nothing in the /build/reports/gatling folder.</p> <pre><code>dependencies { implementation 'org.scala-lang:scala-library:2.13' gatling 'org.scala-lang:scala-library:2.13' gatling 'au.com.bytecode:opencsv:2.4' gatling group: 'org.scalaj', name: 'scalaj-http_2.13', version: '2.4.2' gatling group: 'org.json4s', name: 'json4s-native_2.13', version: '3.6.7' } </code></pre>
[ { "answer_id": 74342175, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "const text = \"1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42\";\n\nconst parts = text.split(\";\");\n\nconst result = parts.map((p) => p.includes(\",\") ? `\"${p}\"` : p).join(\",\");\n\nconsole.log(result);" }, { "answer_id": 74342423, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 0, "selected": false, "text": "/([^;]+)(?:;|$)/" }, { "answer_id": 74348524, "author": "blurfus", "author_id": 600486, "author_profile": "https://Stackoverflow.com/users/600486", "pm_score": 0, "selected": false, "text": "let text = \"00077;Jessica;Williamsburg,ky;40769;42;42;42;42\";\nvar partsArray = text.split(\";\");\nvar newText = \"\";\n\n\nfor (var i = 0; i < partsArray.length; i++) {\n let onePart = partsArray[i];\n\n if (onePart.includes(\",\")) {\n newText += `\"${onePart}\"`;\n } else {\n newText += onePart;\n }\n newText += \",\";\n}\n\nconsole.log(newText);" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8513968/" ]
74,342,249
<p>I have encountered several problems relating to the arrow function and, after a simple google search or two, I fixed them.</p> <p>Then I encountered this:</p> <pre><code>this.projectiles = this.projectiles.filter(projectile =&gt;projectile.markedForDeletion); </code></pre> <p>I got an error saying that &quot;'arrow function syntax (=&gt;)' is only available in ES6 which is not supported by this environment.&quot; I did several google searches and still don't know how to fix it.</p> <p>I tried to repace the arrow with this:</p> <pre><code>this.projectiles = this.projectiles.filter(function(projectile) {}); </code></pre> <p>But I need to input the</p> <pre><code>!projectile.markedForDeletion </code></pre> <p>into the code, but I don't know where or how.</p> <p>Can someone please help?</p>
[ { "answer_id": 74342175, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "const text = \"1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42\";\n\nconst parts = text.split(\";\");\n\nconst result = parts.map((p) => p.includes(\",\") ? `\"${p}\"` : p).join(\",\");\n\nconsole.log(result);" }, { "answer_id": 74342423, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 0, "selected": false, "text": "/([^;]+)(?:;|$)/" }, { "answer_id": 74348524, "author": "blurfus", "author_id": 600486, "author_profile": "https://Stackoverflow.com/users/600486", "pm_score": 0, "selected": false, "text": "let text = \"00077;Jessica;Williamsburg,ky;40769;42;42;42;42\";\nvar partsArray = text.split(\";\");\nvar newText = \"\";\n\n\nfor (var i = 0; i < partsArray.length; i++) {\n let onePart = partsArray[i];\n\n if (onePart.includes(\",\")) {\n newText += `\"${onePart}\"`;\n } else {\n newText += onePart;\n }\n newText += \",\";\n}\n\nconsole.log(newText);" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436848/" ]
74,342,252
<p>what is a significance of &quot;Users and groups&quot; under EA?</p> <ol> <li><p>adding a person will give same access to person as that EA?</p> </li> <li><p>adding a SP will do what? added SP will not have same access as EA?</p> </li> </ol> <p><a href="https://i.stack.imgur.com/sMVrg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sMVrg.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74342175, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 1, "selected": false, "text": "const text = \"1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42\";\n\nconst parts = text.split(\";\");\n\nconst result = parts.map((p) => p.includes(\",\") ? `\"${p}\"` : p).join(\",\");\n\nconsole.log(result);" }, { "answer_id": 74342423, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 0, "selected": false, "text": "/([^;]+)(?:;|$)/" }, { "answer_id": 74348524, "author": "blurfus", "author_id": 600486, "author_profile": "https://Stackoverflow.com/users/600486", "pm_score": 0, "selected": false, "text": "let text = \"00077;Jessica;Williamsburg,ky;40769;42;42;42;42\";\nvar partsArray = text.split(\";\");\nvar newText = \"\";\n\n\nfor (var i = 0; i < partsArray.length; i++) {\n let onePart = partsArray[i];\n\n if (onePart.includes(\",\")) {\n newText += `\"${onePart}\"`;\n } else {\n newText += onePart;\n }\n newText += \",\";\n}\n\nconsole.log(newText);" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10238261/" ]
74,342,264
<p>I have this table which has 2 columns to form the composite key. I am using EF Core. So this is my model</p> <pre><code>public class MyModel { [Key] [Column(Order = 0)] [StringLength(255)] public string column1 { get; set; } [Key] [Column(Order = 1)] [StringLength(255)] public string column2 { get; set; } } </code></pre> <p>When I run the xunit test, I got this error</p> <pre><code>The entity type xxx has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.' </code></pre> <p>This is the code for xunit.</p> <pre><code> public MyServicesTest() { var options = new DbContextOptionsBuilder&lt;MyContext&gt;(); options.UseSqlServer(myServiceSqlConnStr); _myServicesContext = new MyContext(options.Options); _myServicesContext.Database.EnsureDeleted(); } </code></pre> <p>Error is from <code>_myServicesContext.Database.EnsureDeleted();</code></p> <p>This is my context classs</p> <pre><code>public class MyContext : DbContext { public MyContext(DbContextOptions&lt;MyContext&gt; options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyContext).Assembly); } } </code></pre> <p>I have tried to use <code>OnModelCreating</code> in <code>MyContext</code> but still the same error.</p> <pre><code> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity&lt;MyModel&gt;() .HasKey(m =&gt; new { m.column1 , m.column2 }); } </code></pre>
[ { "answer_id": 74342758, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 0, "selected": false, "text": "[Key]" }, { "answer_id": 74342856, "author": "Paul Karam", "author_id": 6783663, "author_profile": "https://Stackoverflow.com/users/6783663", "pm_score": 3, "selected": true, "text": "[Key]" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4971859/" ]
74,342,265
<p>I'm working on project where I have an an accordion with checkboxes. When the checkboxes have a value of true they go to my <code>trueItems</code> array. I have an array <code>filter</code> that I need to register the change of value to true when the button with <code>handleSubmit</code> is clicked. The issue that I'm having is with the final part. I'm struggling to figure out how to get the variables in <code>filter</code> to change to true. I've tried: <code>x =&gt; {setFilter({...filter, x,}), true</code> but that didn't do anything, and I've tried <code>x =&gt; {setFilter({...filter, x: true,}), </code> but that didn't work either. I would really appreciate any help or advice on how to do this. Thank you!</p> <pre><code>function handleSubmit () { for (var items of trueItems){ for (var x in filter){ if(x === items.name) { x =&gt; { setFilter({ ...filter, x, }) }}}}} </code></pre> <p>where filter is:</p> <pre><code> const [filter, setFilter] = useState({ pescatarian: false, vegan: false, vegetarian: false, ... }); </code></pre> <p>and trueItems is:</p> <pre><code>[{&quot;name&quot;: &quot; pescatarian&quot;, &quot;value&quot;: true}...] </code></pre>
[ { "answer_id": 74342758, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 0, "selected": false, "text": "[Key]" }, { "answer_id": 74342856, "author": "Paul Karam", "author_id": 6783663, "author_profile": "https://Stackoverflow.com/users/6783663", "pm_score": 3, "selected": true, "text": "[Key]" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11486899/" ]
74,342,278
<p>I am trying build frontend app using <code>npm run build</code> using jenkins.But getting below error. Could you let me know, how to fix below error?</p> <pre><code>Creating an optimized production build... Failed to compile. ./node_modules/xlsx/jszip.js 7855:112 Module parse failed: Unexpected token (7855:112) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders. | * not null. | */ &gt; function gen_bitlen(s, desc) /* deflate_state *s;*/ /* tree_desc *desc; /* the tree descriptor */*/{ | var tree = desc.dyn_tree; | var max_code = desc.max_code; </code></pre> <p>I am using nodejs version v16.18.1 and npm version 8.19.2..</p>
[ { "answer_id": 74342758, "author": "José Ramírez", "author_id": 13886104, "author_profile": "https://Stackoverflow.com/users/13886104", "pm_score": 0, "selected": false, "text": "[Key]" }, { "answer_id": 74342856, "author": "Paul Karam", "author_id": 6783663, "author_profile": "https://Stackoverflow.com/users/6783663", "pm_score": 3, "selected": true, "text": "[Key]" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8283800/" ]
74,342,281
<p>How to execute javascript code like <code>JSON.parse()</code> in the angular html template itself instead of making a method and calling the method in the angular html template file</p> <p>I tried below ways:</p> <p><code>&lt;p [innerHTML]=&quot;JSON.parse(['\\u2013'])[0]&quot;&gt;&lt;/p&gt;</code></p> <p><code>&lt;p&gt;{{ JSON.parse(['\\u2013'])[0] }}&lt;/p&gt;</code></p> <p>But getting <strong>Property 'JSON' does not exist on type 'AppComponent'.</strong></p> <p>Can it be possible to write javascript code on angular html template itself?</p>
[ { "answer_id": 74342485, "author": "Suhail Akhtar", "author_id": 6613333, "author_profile": "https://Stackoverflow.com/users/6613333", "pm_score": 0, "selected": false, "text": "parseJson(data) {\n return JSON.parse(data);\n}\n" }, { "answer_id": 74343196, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 2, "selected": true, "text": "{{Math.random()}}" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8593983/" ]
74,342,360
<p>I have been trying to write a program in C but I don't know if it's correct because my <code>for</code> loop at the start ends after only 3 loops when it should end after 10. If someone could tell me where the issue is, I would appreciate it. Here is the program.</p> <pre><code>#include &lt;stdio.h&gt; #define size 10 int main(int argc, char *argv[]){ int array[size],sum[size],k,sum1,i,j; sum1=0; printf(&quot;give 10 integers:\n&quot;); for(i=0; i&lt;size; i++){ scanf(&quot;%d&quot;, array[i]); sum[i]=0; } for(i=1; i&lt;size; i++) { for(j=10; j&gt;i; j--){ if(array[j-1]&gt;array[j]){ k=array[j-1]; array[j-1]=array[j]; array[j]=array[j-1]; } } } for(i=1; i&lt;size; i++){ if(array[i]=array[i+1]) sum[i]=sum[i]+1; } for(i=1; i&lt;size; i++){ sum1=sum1+sum[i]; } printf(&quot;%d&quot;, sum1); } </code></pre> <p>I've tried deleting the other loops but then the for loops only once.</p>
[ { "answer_id": 74342416, "author": "Rajarshi Bandopadhyay", "author_id": 9548172, "author_profile": "https://Stackoverflow.com/users/9548172", "pm_score": 0, "selected": false, "text": "for(i = 0; i < size; i++) {\n ...\n}\n" }, { "answer_id": 74343463, "author": "AR7CORE", "author_id": 12945333, "author_profile": "https://Stackoverflow.com/users/12945333", "pm_score": 1, "selected": false, "text": "scanf(\"%d\", array[i]);\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18291360/" ]
74,342,444
<p>Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a post can have a null for the parent post attribute - this would denote the &quot;root&quot; post. However, when I implement the views, model and serializer for the posts, I get the following error (stack trace):</p> <pre><code>Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Post.objects.create()`. You may need to make the field read-only, or override the PostSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/serializers.py&quot;, line 962, in create instance = ModelClass._default_manager.create(**validated_data) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/manager.py&quot;, line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py&quot;, line 669, in create obj = self.model(**kwargs) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py&quot;, line 564, in __init__ _setattr(self, field.attname, val) File &quot;/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py&quot;, line 606, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_post_id.set() instead. </code></pre> <p>Here's my model:</p> <pre><code>class Post(models.Model): &quot;&quot;&quot; Post model &quot;&quot;&quot; class PostObjects(models.Manager): &quot;&quot;&quot; Return the Post object and all children posts &quot;&quot;&quot; def get_queryset(self): return super().get_queryset().filter(id='') title = models.CharField(max_length=250) body = models.TextField() # Author deletion cascade deletes all of author's posts author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='forum_posts') # if a post is deleted, all children posts will also be deleted # defines recursive many-to-one relationship parent_post = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='parent_post_id') time_stamp = models.DateTimeField(default=timezone.now) # Default object manager objects = models.Manager() # Custom object manager for a particular object post_objects = PostObjects() def __str__(self): return self.title </code></pre> <p>Here's my serializer:</p> <pre><code>class PostSerializer(serializers.ModelSerializer): &quot;&quot;&quot; Serializer for Post class &quot;&quot;&quot; class Meta: model = Post fields = ('id', 'title', 'body', 'author', 'time_stamp') </code></pre> <p>Here's my view:</p> <pre><code>class PostList(generics.ListCreateAPIView): &quot;&quot;&quot; Create a post or get a list of all posts within the database that are parent posts API endpoints that use this view: - /posts - /createPost &quot;&quot;&quot; queryset = Post.objects.all() serializer_class = PostSerializer </code></pre> <p>Urls:</p> <pre><code>from django.urls import path, include from .views import * urlpatterns = [ # path('', ), path('createPost/', PostList.as_view(), name='createPost'), path('createUser/', CreateUser.as_view(), name='createUser'), path('getUser/&lt;int:pk&gt;', GetUser.as_view(), name='getUser'), path('admin/addQuestion', GetQuestions.as_view(), name='addQuestion'), path('admin/addCategory', Category.as_view(), name='addCategory'), path('admin/deletePost/&lt;int:pk&gt;', PostDetail.as_view(), name='deletePost'), path('admin/getCategories', Category.as_view(), name='getCategories'), path('questionsBank/', GetQuestions.as_view(), name='questionsBank'), path('posts/', PostList.as_view(), name='getPosts'), path('posts/&lt;int:pk&gt;', PostDetail.as_view(), name='getPost'), path('userProgress/&lt;int:pk&gt;', UserProgress.as_view(), name='getUserProgress'), path('modifyUserProgress/&lt;int:pk&gt;', UserProgress.as_view(), name='modifyUserProgress'), path('deletePost/&lt;int:pk&gt;', PostDetail.as_view(), name='deletePost'), path('jobPostings/', JobPostings.as_view(), name='getJobPostings'), ] </code></pre> <p>POST request I make through API viewer to encounter error: <a href="https://i.stack.imgur.com/93IwX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/93IwX.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74342495, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 1, "selected": false, "text": "fields = ('id', 'title', 'body', 'author', 'time_stamp')\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19456156/" ]
74,342,476
<p>My team was in trouble in push alarm with FCM token in flutter (especially ios),<br /> So we decided to push alarm to each user with topics.</p> <p>I know that &quot;One app instance can be subscribed to no more than 2000 topics.&quot; in <a href="https://firebase.google.com/docs/cloud-messaging/android/topic-messaging" rel="nofollow noreferrer">Firebase Document</a></p> <p>But i confused about &quot;One app instance&quot;. Is that mean each android or ios application user can subscribe 2000 topics? or Each FCM Server can create up to 2000 topics?</p> <p>I wonder about One app instance's meaning in &quot;One app instance can be subscribed to no more than 2000 topics&quot;</p>
[ { "answer_id": 74342495, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 1, "selected": false, "text": "fields = ('id', 'title', 'body', 'author', 'time_stamp')\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20437172/" ]
74,342,503
<p>I have a table with given values</p> <pre><code>| id | level | value | | --- | ------ | ----- | | 1 | 30000 | 0.05 | | 2 | 100000 | 0.06 | | 3 | 120000 | 0.07 | </code></pre> <p>I want to create an postgres sql query to get a sum in the following logic. I will be providing a value (level) as as parameter to the query (170000).</p> <p><code>(100000- 30000)*0.05 + (120000-100000)*0.06 + (170000-120000)*0.07</code></p> <p>(difference of level of row2 and row1) * value of row1 + (difference of level of row3 and row2) * value of row2 + (difference of level as input and row3) * value of row3</p>
[ { "answer_id": 74342664, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": false, "text": "LEAD" }, { "answer_id": 74342672, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 3, "selected": true, "text": "LEAD" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14403738/" ]
74,342,504
<p>I have a library that I use in my application. In my library, I need to get a resource ( a bks file). I don't have a main activity in my library. How do I get a resource without an activity. Here is the code I have.</p> <pre><code>public class PostRequest { Context context; MyApplication application; public String post(){ KeyStore trustStore = KeyStore.getInstance(&quot;BKS&quot;); InputStream trustStoreStream = application.getResources().openRawResource(R.raw.certificate); } } </code></pre> <p>I am getting the error, <code>Attempt to invoke virtual method getResources() on a null object reference. </code></p> <p>I created a variable <code>Context context</code> to and used that <code>context.getResources().openRawResource(R.raw.certificate);</code> but still with no success. This is a library so I don't have MainActivity or any activity classes.</p>
[ { "answer_id": 74342664, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": false, "text": "LEAD" }, { "answer_id": 74342672, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 3, "selected": true, "text": "LEAD" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6780883/" ]
74,342,543
<p>I am mapping through an array like this</p> <pre><code>const isFocused = useIsFocused(); async function getProfile() { const [labels, setLabels] = useState([]) ... array.map(x =&gt; { handleChange(x.date) }) ... } useEffect(() =&gt; { isFocused &amp;&amp; getProfile() }, [isFocused]); </code></pre> <p>The code for handleChange()</p> <pre><code>function handleChange(date) { console.log(date,&quot;THIS IS DATE IN HANDLE&quot;) setLabels([...labels, date]) } </code></pre> <p>The value of label after this is only the last index of the array. How do I fix this issue?</p>
[ { "answer_id": 74342664, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": false, "text": "LEAD" }, { "answer_id": 74342672, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 3, "selected": true, "text": "LEAD" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19545651/" ]
74,342,550
<p>I have several images that are 50x50, fit into a row of 6 columns (ie, 6 images to a row). However, on rendering each image is seemingly on its own individual row, so it looks like the images are stacked on top of another, instead of on a single row.</p> <p>The code is simple:</p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot;/&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-2&quot;&gt; &lt;img style=&quot;height:50px;width:50px&quot; src=&quot;https://www.seiu1000.org/sites/main/files/main-images/camera_lense_0.jpeg&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>See live example: <a href="https://jsfiddle.net/sedf765k/" rel="nofollow noreferrer">https://jsfiddle.net/sedf765k/</a></p> <p>The problem is confusing because there are 6 <code>col-xs-2</code> which add up to <code>12</code>, so they should perfectly be aligned in the row. Why is this happening, and how can I properly line them up in the row?</p> <p><strong>Additionally</strong>, because the images are smaller than the row itself in most cases, is there a way to decrease the empty space between them and float them to the left nicely, so that it looks like each image is next to each other, like people standing in a line?</p>
[ { "answer_id": 74342831, "author": "Eric Kong", "author_id": 15723533, "author_profile": "https://Stackoverflow.com/users/15723533", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n" }, { "answer_id": 74342973, "author": "Junaid Shaikh", "author_id": 17033432, "author_profile": "https://Stackoverflow.com/users/17033432", "pm_score": 2, "selected": true, "text": "xs" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8152261/" ]
74,342,555
<p>So when inputting my third elif variable in my main function, my other functions don't work. My question, is what's stopping it. Lines 123, 124, 125, keep receiving the &quot;UnboundLocalError: totalcost referenced before assignement&quot;</p> <p>`</p> <pre><code>def welcome(): print(&quot;Hello and Welcome Super Maids&quot;) def LC (a , b): totalcost = 150 + a + (b * 10) print(&quot;The total of your service is:\n$&quot;,totalcost) return totalcost def DC (a, b): totalcost = 300 + a + (b * 10) print(&quot;The total of your service is:\n$&quot;,totalcost) return totalcost def SeniorDiscount(totalcost): ans = str(input(&quot;Are you by a chance a serior citizen? [y/n]&quot;)) if ans == 'y': age = eval(input(&quot;What year were you born? [XXXX]&quot;)) if age &gt;= 1960: print(&quot;Perfect! Thank you, sir/ma'am!&quot;) discount = totalcost * .15 print(&quot;Your discount is:\n$&quot;, discount) totalcost = totalcost - discount print(&quot;Great! The total cost of your serivce is:$&quot;,totalcost) return totalcost elif ans == 'n': print(&quot;Thank you for being honest!&quot;) print(&quot;Great! The total cost of your serivce is:$&quot;,totalcost) return totalcost else: print(&quot;We'll need an actual answer from you in order to continue&quot;) SeniorDiscount(totalcost) return totalcost def YardService(): shrubCost = 10 edgingCost = 20 sqftCost = 20 sqrft = eval(input(&quot;What is the square footage of your yard?\n&quot;)) linsqft = eval(input(&quot;What is the linear square footage of your yard?\n&quot;)) shrubs = eval(input(&quot;How many shrubs do you have?\n&quot;)) totalcost = (shrubCost * shrubs)+(edgingCost + linsqft)+(sqftCost * sqrft) return totalcost def YardService1(): shrubCost = 10 edgingCost = 20 sqftCost = 20 sqrft = eval(input(&quot;What is the square footage of your yard?\n&quot;)) linsqft = eval(input(&quot;What is the linear square footage of your yard?\n&quot;)) shrubs = eval(input(&quot;How many shrubs do you have?\n&quot;)) totalcost = (shrubCost * shrubs)+(edgingCost + linsqft)+(sqftCost * sqrft) return totalcost def homeservice(): welcome() NumberOfRooms = eval(input(&quot;How many rooms are in need of cleaning?\n&quot;)) if NumberOfRooms &lt; 3: print(&quot;Your starting total is: $&quot;, 120) CostOfRooms = 120 windows = eval(input(&quot;How many windows do you have in need of cleaning?\n&quot;)) CostOfWindows = 10 TypeClean = eval(input(&quot;What kind of cleaning service are you in search of?\n1-Light Cleaning\n2-Deep Cleaning\n&quot;)) if TypeClean == 1: totalcost = LC(CostOfRooms,windows) return totalcost elif TypeClean == 2: totalcost = DC(CostOfRooms,windows) return totalcost else: print(&quot;You must select a service in order to continue&quot;) elif 2 &lt; NumberOfRooms &lt; 4: print(&quot;Your starting total is: $&quot;, 150) CostOfRooms = 150 windows = eval(input(&quot;How many windows do you have in need of cleaning?\n&quot;)) CostOfWindows = 10 TypeClean = eval(input(&quot;What kind of cleaning service are you in search of?\n1-Light Cleaning\n2-Deep Cleaning\n&quot;)) if TypeClean == 1: totalcost = LC(CostOfRooms,windows) return totalcost elif TypeClean == 2: totalcost = DC(CostOfRooms,windows) return totalcost else: print(&quot;You must select a service in order to continue&quot;) elif 3 &lt; NumberOfRooms &lt; 6: print(&quot;Your starting total is: $&quot;, 175) CostOfRooms = 175 windows = eval(input(&quot;How many windows do you have in need of cleaning?\n&quot;)) CostOfWindows = 10 TypeClean = eval(input(&quot;What kind of cleaning service are you in search of?\n1-Light Cleaning\n2-Deep Cleaning\n&quot;)) if TypeClean == 1: LC(CostOfRooms,windows) return totalcost elif TypeClean == 2: DC(CostOfRooms,windows) return totalcost else: print(&quot;You must select a service in order to continue&quot;) elif NumberOfRooms &gt;= 6: print(&quot;We do not offer a service of this size&quot;) def main(): print(&quot;We'll start by asking you a set of questions&quot;) YHB = eval(input(&quot;What kind of cleaning service are you in search of?\n1-Home Serivce\n2-Yard Service\n3-Both\n&quot;)) if YHB == 1: totalcost = homeservice() SeniorDiscount(totalcost) elif YHB == 2: totalcost = YardService() SeniorDiscount(totalcost) elif YHB == 3: toatlcost = homeservice() + YardService() #print(totalcost) #YardService1(totalcost) SeniorDiscount(totalcost) else: print(&quot;You must have selected nothing, we'll try again.&quot;) main() #--- Execute -------------------------------------------------------- main() </code></pre> <p>`</p> <p>The process works when trying to do elif on 1 and 2, however it completely shuts down when attempting to work within the last version process.</p>
[ { "answer_id": 74342831, "author": "Eric Kong", "author_id": 15723533, "author_profile": "https://Stackoverflow.com/users/15723533", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n" }, { "answer_id": 74342973, "author": "Junaid Shaikh", "author_id": 17033432, "author_profile": "https://Stackoverflow.com/users/17033432", "pm_score": 2, "selected": true, "text": "xs" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20287939/" ]
74,342,585
<p>The problem here is when I'm returning from my support fragment to home fragment back every time my items in the recycle viewer got doubled. Each time i am shifting fragment to fragment my recycle viewer item in the homefragment got doubled. But when, I reopen the app its all got corrected but when i click on another fragment and come back the item in recycle viewer in home fragment got doubled. Kindly help me</p> <pre><code> // **HomeFragment.kt** package com.service.bookitapp import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.fragment_home.* private const val ARG_PARAM1 = &quot;param1&quot; private const val ARG_PARAM2 = &quot;param2&quot; class HomeFragment : Fragment() { private var param1: String? = null private var param2: String? = null private val arrCategory = ArrayList&lt;CategoryModel&gt;() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_home, container, false) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerView =view.findViewById&lt;RecyclerView&gt;(R.id.recyclerCategory) arrCategory.add(CategoryModel(R.drawable.electrician,&quot;Electrician&quot;)) arrCategory.add(CategoryModel(R.drawable.plumber,&quot;Plumber&quot;)) arrCategory.add(CategoryModel(R.drawable.acservice,&quot;AC Service&quot;)) arrCategory.add(CategoryModel(R.drawable.carpentry,&quot;Carpentry&quot;)) arrCategory.add(CategoryModel(R.drawable.drop,&quot;Pick up &amp; Drop&quot;)) arrCategory.add(CategoryModel(R.drawable.painting,&quot;Painting&quot;)) arrCategory.add(CategoryModel(R.drawable.waterfilter,&quot;Water Filter Repair&quot;)) arrCategory.add(CategoryModel(R.drawable.packer,&quot;Pack and Move&quot;)) recyclerView.layoutManager = GridLayoutManager(context,3) val recyclerAdapter = context?.let { RecycleCategoryAdapter(it,arrCategory) } recyclerView.adapter = recyclerAdapter } } // **fragment_home.xml** &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:background=&quot;#FAF9F6&quot; android:padding=&quot;5dp&quot; android:orientation=&quot;vertical&quot; tools:context=&quot;.HomeFragment&quot;&gt; &lt;RelativeLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; tools:ignore=&quot;UselessParent&quot;&gt; &lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/welcome_user&quot; android:textColor=&quot;@color/teal_200&quot; android:textSize=&quot;28sp&quot; android:padding=&quot;8dp&quot; android:textStyle=&quot;bold&quot; tools:ignore=&quot;RelativeOverlap&quot; /&gt; &lt;ImageView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;50dp&quot; android:layout_alignParentEnd=&quot;true&quot; android:src=&quot;@drawable/profile&quot; android:padding=&quot;4dp&quot; android:contentDescription=&quot;@string/app_name&quot; /&gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout android:layout_marginTop=&quot;5dp&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:padding=&quot;4dp&quot;&gt; &lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/catg&quot; android:textStyle=&quot;bold&quot; android:textColor=&quot;#6E16e8&quot; android:layout_alignParentStart=&quot;true&quot; android:textSize=&quot;22sp&quot;/&gt; &lt;/RelativeLayout&gt; &lt;androidx.recyclerview.widget.RecyclerView android:layout_marginTop=&quot;5dp&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;370dp&quot; android:id=&quot;@+id/recyclerCategory&quot;&gt; &lt;/androidx.recyclerview.widget.RecyclerView&gt; &lt;LinearLayout android:layout_marginTop=&quot;10dp&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:orientation=&quot;vertical&quot;&gt; &lt;TextView android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/offers&quot; android:textStyle=&quot;bold&quot; android:layout_marginBottom=&quot;5dp&quot; android:textColor=&quot;#6E16e8&quot; android:textSize=&quot;22sp&quot;/&gt; &lt;HorizontalScrollView android:layout_margin=&quot;8dp&quot; android:layout_width=&quot;350dp&quot; android:layout_height=&quot;200dp&quot; tools:ignore=&quot;UselessParent&quot;&gt; &lt;LinearLayout android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;ImageView android:layout_width=&quot;350dp&quot; android:layout_height=&quot;wrap_content&quot; android:src=&quot;@drawable/plumbingservice&quot; android:contentDescription=&quot;@string/elect&quot; /&gt; &lt;ImageView android:layout_width=&quot;350dp&quot; android:layout_height=&quot;wrap_content&quot; android:contentDescription=&quot;@string/elect&quot; android:src=&quot;@drawable/cleanview&quot; /&gt; &lt;ImageView android:layout_width=&quot;360dp&quot; android:layout_height=&quot;wrap_content&quot; android:contentDescription=&quot;@string/elect&quot; android:src=&quot;@drawable/elecview&quot; /&gt; &lt;/LinearLayout&gt; &lt;/HorizontalScrollView&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>The followig are the images</p> <p><a href="https://i.stack.imgur.com/4B5qs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4B5qs.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/aikSY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aikSY.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74342831, "author": "Eric Kong", "author_id": 15723533, "author_profile": "https://Stackoverflow.com/users/15723533", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n" }, { "answer_id": 74342973, "author": "Junaid Shaikh", "author_id": 17033432, "author_profile": "https://Stackoverflow.com/users/17033432", "pm_score": 2, "selected": true, "text": "xs" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20437146/" ]
74,342,586
<pre><code>$('.flip-button').each(function() { $(this).click(function() { $(this).closest('.flip-card-inners').toggleClass('flip-card-active') }) }) </code></pre> <p>I wasn't able to translate this in vanilla js because I encountered several problems with get element by class</p>
[ { "answer_id": 74342831, "author": "Eric Kong", "author_id": 15723533, "author_profile": "https://Stackoverflow.com/users/15723533", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n" }, { "answer_id": 74342973, "author": "Junaid Shaikh", "author_id": 17033432, "author_profile": "https://Stackoverflow.com/users/17033432", "pm_score": 2, "selected": true, "text": "xs" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20437284/" ]
74,342,624
<p>It worked on .NET 6, but now when I migrated my .net maui project to .net 7 the problem starts occurring: I have MediaPicker placed to one xaml page of my project in order to capture a picture and store it at the app data directory. I can run Android emulator and get permission for camera, but it stopped working for storage. I deleted and re-created Android emulator device, I tried different Android versions like API 29, 33, but nothing works. I used to pop up Android permission dialog window automatically when it executes <code>CapturePhotoAsync</code>, now it does not, and even when explicitly request the permission it still does not show dialog window and retuns <code>Denied</code> immidiatelly</p> <pre><code>// got PermissionStatus.Denied, no dialog window requesting permission pops up PermissionStatus status = await Permissions.RequestAsync&lt;Permissions.StorageWrite&gt;(); </code></pre> <p>If I ignore it and tries to store the picture it predictably raises the exception <code>Microsoft.Maui.ApplicationModel.PermissionException: 'StorageWrite permission was not granted: Denied'</code></p> <p>Anyone can suggest what could be wrong and what can I try to get it resolved</p> <p><strong>UPDATE</strong>: created min. project and uploaded it to the github: github.com/YMichurin/mauiStoragePermissions</p>
[ { "answer_id": 74343160, "author": "Liyun Zhang - MSFT", "author_id": 17455524, "author_profile": "https://Stackoverflow.com/users/17455524", "pm_score": 1, "selected": false, "text": " <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738999/" ]
74,342,636
<p>I updated my flutter version to the latest one and since I observed the app can't get the firebase token and it returns an error <code>[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: The method 'getToken' was called on null.</code>. I am trying to get the token with the below code:</p> <pre><code>FirebaseMessaging firebaseMessaging ; String firebaseToken; Future&lt;void&gt; firebaseCloudMessaging_Listeners() async { firebaseMessaging.getToken().then((token){ firebaseToken = token; }); } </code></pre> <p>I have My <code>pubspec.yaml</code> for firebase_message is <code>firebase_messaging: ^13.0.4</code> And <code>android/build.gradle</code> dependencies is</p> <pre><code> buildscript { ext.kotlin_version = '1.5.31' repositories { google() jcenter() mavenCentral() // Maven Central repository } dependencies { classpath 'com.android.tools.build:gradle:4.1.3' classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot; classpath 'com.google.gms:google-services:4.3.13' } subprojects { project.configurations.all { resolutionStrategy.eachDependency { details -&gt; if (details.requested.group == 'com.android.support' &amp;&amp; !details.requested.name.contains('multidex') ) { details.useVersion &quot;27.1.1&quot; } if (details.requested.group == 'androidx.core' &amp;&amp; !details.requested.name.contains('androidx') ) { //details.useVersion &quot;1.0.1&quot; details.useVersion &quot;1.5.0&quot; } } } } } allprojects { repositories { google() jcenter() mavenCentral() // Maven Central repository } } rootProject.buildDir = '../build' subprojects { project.buildDir = &quot;${rootProject.buildDir}/${project.name}&quot; } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>And and my <code>app/build.gradle</code> dependencies is</p> <pre><code> def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -&gt; localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException(&quot;Flutter SDK not found. Define location with flutter.sdk in the local.properties file.&quot;) } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'com.google.gms.google-services' apply from: &quot;$flutterRoot/packages/flutter_tools/gradle/flutter.gradle&quot; android { compileSdkVersion 33 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId &quot;appname&quot; minSdkVersion 20 //noinspection OldTargetApi multiDexEnabled true targetSdkVersion 33 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner &quot;android.support.test.runner.AndroidJUnitRunner&quot; } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot; testImplementation 'junit:junit:4.12' implementation 'com.google.firebase:firebase-analytics' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:multidex:1.0.3' implementation platform('com.google.firebase:firebase-bom:31.0.2') } </code></pre> <p>I am not sure where I got it wrong but I will appreciate it if anyone can help in case of any additional info let me know.</p>
[ { "answer_id": 74343160, "author": "Liyun Zhang - MSFT", "author_id": 17455524, "author_profile": "https://Stackoverflow.com/users/17455524", "pm_score": 1, "selected": false, "text": " <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20230706/" ]
74,342,657
<p>I am getting the above error in my TypeScript code. I am attaching the codes of 2 files along with the error message. Please look into it.</p> <p>This is the &quot;NewPostForm.tsx&quot; file in which error is occuring.</p> <pre><code>import React, { useState } from 'react'; import {AlertIcon, Flex, Icon, Alert, Text} from &quot;@chakra-ui/react&quot;; import {BiPoll} from &quot;react-icons/bi&quot;; import { BsLink45Deg, BsMic } from 'react-icons/bs'; import { IoDocumentText, IoImageOutline } from 'react-icons/io5'; import {AiFillCloseCircle, AiTwotoneWallet} from &quot;react-icons/ai&quot;; import TabItem from './TabItem'; import TextInputs from &quot;./PostForm/TextInputs&quot; import { render } from 'react-dom'; import ImageUpload from './ImageUpload'; import { User } from 'firebase/auth'; import { useRouter } from 'next/router'; import { addDoc, collection, serverTimestamp, Timestamp, updateDoc } from 'firebase/firestore'; import { firestore, storage } from '../../firebase/clientApp'; import { getDownloadURL, ref, uploadString } from 'firebase/storage'; import { Post } from '../../atoms/postsAtom'; import useSelectFile from '../../hooks/useSelectFile'; type NewPostFormProps = { user: User; }; const formTabs = [ { title: &quot;Post&quot;, icon: IoDocumentText, }, { title: &quot;Images &amp; Video&quot;, icon: IoImageOutline, }, { title: &quot;Link&quot;, icon: BsLink45Deg, }, { title: &quot;Poll&quot;, icon: BiPoll, }, { title: &quot;Talk&quot;, icon: BsMic, }, ]; export type TabItem = { title: string; icon: typeof Icon.arguments; }; const NewPostForm:React.FC&lt;NewPostFormProps&gt; = ({user}) =&gt; { const router = useRouter(); const [selectedTab, setSelectedTab] = useState(formTabs[0].title); const [textInputs, setTextInputs] = useState({ title: &quot;&quot;, body: &quot;&quot;, }); const {selectedFile, setSelectedFile, onSelectFile} = useSelectFile(); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const handleCreatePost = async() =&gt; { const {communityId} = router.query; // Create new post object =&gt; type Post const newPost: Post = { communityId: communityId as string, creatorId: user?.uid, creatorDisplayName: user.email!.split(&quot;@&quot;)[0], title: textInputs.title, body: textInputs.body, numberOfComments: 0, voteStatus: 0, createdAt: serverTimestamp() as Timestamp, id: '' }; setLoading(true); try { // Store the post in DB const postDocRef = await addDoc(collection(firestore, &quot;posts&quot;), newPost); // Check for selected file if(selectedFile) { // Store in storage =&gt; getDownloadURL {return imageURL} const imageRef = ref(storage, `posts/${postDocRef.id}/image`); await uploadString(imageRef, selectedFile, &quot;data_url&quot;); const downloadURL = await getDownloadURL(imageRef); // Update post doc by adding imageURL await updateDoc(postDocRef, { imageURL: downloadURL, }); } // redirect the user back to the communityPage using the router router.back(); } catch(error: any) { console.log(&quot;handleCreatePost error&quot;, error.message); setError(true); } setLoading(false); }; const onTextChange = ( event: React.ChangeEvent&lt;HTMLInputElement | HTMLTextAreaElement&gt; ) =&gt; { const { target: {name, value}, } = event; setTextInputs((prev) =&gt; ({ ...prev, [name]: value, })); }; return &lt;div&gt; &lt;Flex direction=&quot;column&quot; bg=&quot;white&quot; borderRadius={4} mt={2}&gt; &lt;Flex width=&quot;100%&quot;&gt; {formTabs.map((item) =&gt; ( &lt;TabItem key={item.title} item={item} selected={item.title === selectedTab} setSelectedTab={setSelectedTab} /&gt; ))} &lt;/Flex&gt; &lt;Flex p={4}&gt; {selectedTab === &quot;Post&quot; &amp;&amp; ( &lt;TextInputs textInputs={textInputs} handleCreatePost={handleCreatePost} onChange={onTextChange} loading={loading} /&gt;)} {selectedTab === &quot;Images &amp; Video&quot; &amp;&amp; ( &lt;ImageUpload selectedFile={selectedFile} onSelectImage={onSelectFile} setSelectedTab={setSelectedTab} setSelectedFile={setSelectedFile} /&gt; )} &lt;/Flex&gt; {error &amp;&amp; ( &lt;Alert status=&quot;error&quot;&gt; &lt;AlertIcon /&gt; &lt;Text mr={2}&gt;Error Creating the Post&lt;/Text&gt; &lt;/Alert&gt; )} &lt;/Flex&gt; &lt;/div&gt; } export default NewPostForm; </code></pre> <p>Also I am attaching another &quot;useSelectFile.tsx&quot; file for reference.</p> <pre><code>import React, {useState} from 'react'; const useSelectFile = () =&gt; { const [selectedFile, setSelectedFile] = useState&lt;string&gt;(); const onSelectFile = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; { console.log(&quot;THIS IS HAPPENING&quot;, event); const reader = new FileReader(); if(event.target.files?.[0]) { reader.readAsDataURL(event.target.files[0]); } reader.onload = (readerEvent) =&gt; { if(readerEvent.target?.result) { setSelectedFile(readerEvent.target.result as string); } }; }; return { selectedFile setSelectedFile onSelectFile }; }; export default useSelectFile; </code></pre> <p>Also I am attaching the screenshot of error message. <a href="https://i.stack.imgur.com/mKa28.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mKa28.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74342727, "author": "Anis", "author_id": 6316804, "author_profile": "https://Stackoverflow.com/users/6316804", "pm_score": 2, "selected": true, "text": " return {\n selectedFile,\n setSelectedFile,\n onSelectFile,\n };\n" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16423451/" ]
74,342,697
<p><code>while [List]: </code> vs <code>while [List] is True</code>? What is the different?</p> <p>For example I am doing this problem (heap and priority queues) <a href="https://leetcode.com/problems/find-k-pairs-with-smallest-sums/" rel="nofollow noreferrer">https://leetcode.com/problems/find-k-pairs-with-smallest-sums/</a> and here is a sample solution that I retrieved. I do not understand this line <code>while len(res) &lt; k and heap:</code>. Why do I need <code>while heap:</code>? and Also when I tried <code>while ... heap is True</code>, the code no longer works.</p> <pre><code>class Solution: &quot;&quot;&quot;Returns List[List[int]]&quot;&quot;&quot; def kSmallestPairs(self, nums1, nums2, k): # nums1 and nums2 are both sorted list res = [] if not nums1 or not nums2 or not k: return res heap = [] visited = set() heapq.heappush(heap, (nums1[0] + nums2[0], 0, 0)) visited.add((0, 0)) while len(res) &lt; k and heap: _, i, j = heapq.heappop(heap) res.append([nums1[i], nums2[j]]) if i + 1 &lt; len(nums1) and (i + 1, j) not in visited: heapq.heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j)) visited.add((i + 1, j)) if j + 1 &lt; len(nums2) and (i, j + 1) not in visited: heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1)) visited.add((i, j + 1)) return res </code></pre>
[ { "answer_id": 74342804, "author": "Dmitriy Neledva", "author_id": 16786350, "author_profile": "https://Stackoverflow.com/users/16786350", "pm_score": 0, "selected": false, "text": "True" }, { "answer_id": 74368320, "author": "Blckknght", "author_id": 1405065, "author_profile": "https://Stackoverflow.com/users/1405065", "pm_score": 1, "selected": false, "text": "is" } ]
2022/11/07
[ "https://Stackoverflow.com/questions/74342697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10824975/" ]