qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,646,634
<p>Hi I wanted to separate integers in a string an build an array For example 50 + 80 in column I wanted to get [50,80] this is simple example in my column I will have more complex expressions such as (10 + 20) / 30 I want [10,20,30]<br /> I may have +,-,*,/,(,),' ' remove all this and wanted to build and array with comma separated numbers.</p> <p>I tried replace but the output is string so my array is coming as ['10,20,30'] can we do this regexp</p>
[ { "answer_id": 74646897, "author": "JRiggles", "author_id": 8512262, "author_profile": "https://Stackoverflow.com/users/8512262", "pm_score": 1, "selected": false, "text": "tkinter.after() after # I don't know what your imports look like, so this is a boilerplate example\nimport tkinter as tk\n\nroot = tk.Tk() # this is whatever you're calling 'mainloop()' on right now\nrace_step_count = 230 # define how 'long' the race is\n\n\ndef race():\n global race_step_count\n if race_step_count:\n red.forward(randint(1,8))\n blue.forward(randint(1,8))\n purple.forward(randint(1,8))\n orange.forward(randint(1,8))\n race_step_count -= 1\n next_step = root.after(100, race) # call this function again after 100mS\n else: # no more steps - the race is over!\n root.after_cancel(next_step) # stop calling the race function\n race()" }, { "answer_id": 74660701, "author": "cdlane", "author_id": 5771269, "author_profile": "https://Stackoverflow.com/users/5771269", "pm_score": 1, "selected": true, "text": "AttributeError: '_Screen' object has no attribute 'after'\n \"Exit Game\" from random import randint\nfrom turtle import TurtleScreen, RawTurtle\nimport tkinter as tk\nimport sys\n\ndef back_canvas():\n # Landscape making\n # Making the ground\n\n pen.color('sienna')\n\n pen.penup()\n pen.setpos(-640, -162.5)\n pen.pendown()\n\n pen.begin_fill()\n\n for _ in range(2):\n pen.forward(1280)\n pen.right(90)\n pen.forward(162.5)\n pen.right(90)\n\n pen.end_fill()\n\n # Making Racing Area\n\n pen.color('lime')\n pen.begin_fill()\n\n for _ in range(2):\n pen.forward(1280)\n pen.left(90)\n pen.forward(325)\n pen.left(90)\n\n pen.end_fill()\n\n # Making Top Area\n\n pen.color('dodgerblue')\n pen.begin_fill()\n pen.left(90)\n pen.forward(325)\n\n for _ in range(2):\n pen.forward(162.5)\n pen.right(90)\n pen.forward(1280)\n pen.right(90)\n\n pen.end_fill()\n pen.penup()\n\n # Writing \"Turtle Race Game\"\n pen.color('lime')\n pen.setpos(0, 250)\n pen.color('black')\n pen.write(\"Turtle Race Game\", align='center', font=('Arial', 27, 'normal'))\n\n # Making the first finish line\n pen.right(90)\n pen.setpos(500, 143)\n\n def flag():\n pen.color('black')\n pen.begin_fill()\n\n for _ in range(4):\n pen.forward(20)\n pen.right(90)\n\n pen.end_fill()\n pen.forward(20)\n\n pen.color('white')\n pen.begin_fill()\n\n for _ in range(4):\n pen.forward(20)\n pen.right(90)\n\n pen.end_fill()\n pen.forward(20)\n\n for _ in range(7):\n flag()\n\n pen.right(90)\n pen.forward(40)\n pen.right(90)\n\n flag()\n\n pen.right(180)\n\n # placing main pen to right place to say who won\n pen.setpos(520, 180)\n\nrace_step_count = 230\n\ndef race():\n global race_step_count\n\n if race_step_count > 0:\n red.forward(randint(1, 8))\n blue.forward(randint(1, 8))\n purple.forward(randint(1, 8))\n orange.forward(randint(1, 8))\n\n race_step_count -= 1\n screen.ontimer(race, 100) # call this function again after 100mS\n else:\n who_won()\n\ndef who_won():\n if blue.xcor() > red.xcor() and blue.xcor() > purple.xcor() and blue.xcor() > orange.xcor():\n pen.write(\"Blue won!\", align='center', font=('Arial', 25, 'bold'))\n elif red.xcor() > blue.xcor() and red.xcor() > purple.xcor() and red.xcor() > orange.xcor():\n pen.write(\"Red won!\", align='center', font=('Arial', 25, 'bold'))\n elif purple.xcor() > blue.xcor() and purple.xcor() > red.xcor() and purple.xcor() > orange.xcor():\n pen.write(\"Purple won!\", align='center', font=('Arial', 25, 'bold'))\n elif orange.xcor() > blue.xcor() and orange.xcor() > red.xcor() and orange.xcor() > purple.xcor():\n pen.write(\"Orange won!\", align='center', font=('Arial', 25, 'bold'))\n\nmaster = tk.Tk()\nmaster.title(\"Turtle Race Game\")\n\ncanvas = tk.Canvas(master, width=1280, height=650)\ncanvas.pack()\n\nscreen = TurtleScreen(canvas)\n\ntk.Button(master, text=\"Exit Game\", command=sys.exit, width=0, height=4, fg='gold', bg='dodgerblue').pack()\n\n# Main drawing turtle\npen = RawTurtle(screen)\npen.hideturtle()\npen.speed('fastest')\n\nback_canvas()\n\nred = RawTurtle(screen)\nred.speed('fastest')\nred.shape('turtle')\nred.penup()\n\nred.color('red')\nred.setpos(-550, 90)\n\nblue = red.clone()\nblue.color('blue')\nblue.setpos(-550, 30)\n\npurple = red.clone()\npurple.color('purple')\npurple.setpos(-550, -30)\n\norange = red.clone()\norange.color('orange')\norange.setpos(-550, -90)\n\nrace()\n\nscreen.mainloop()\n import import" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659196/" ]
74,646,642
<p>So I'm building a quiz app and that quiz is divided into difficulty levels. I change that level on a button click by setting params into my path. Then I try to insert a difficulty index because the structure of my obj is:</p> <pre><code>const questions = { easy: [...], medium: [...], hard: [...] } </code></pre> <pre><code> const [searchParams, setSearchParams] = useSearchParams(); const [currentPage, setCurrentPage] = useState(0); const difficulty = searchParams.get(&quot;difficulty&quot;); const handlePageChange = () =&gt; { if (currentPage + 1 &lt; questions[difficulty].length) { setCurrentPage((prevState) =&gt; prevState + 1); } }; const handleDifficultyChoice = (difficulty: DifficultyType) =&gt; { setSearchParams({ difficulty }); }; </code></pre> <p>Unfortunately I cannot insert that index because index cannot be null. How to solve that?</p>
[ { "answer_id": 74646655, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 0, "selected": false, "text": "difficulty const handlePageChange = () => {\n if (difficulty && currentPage + 1 < questions[difficulty]?.length) {\n setCurrentPage((prevState) => prevState + 1);\n }\n};\n" }, { "answer_id": 74646860, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "handlePageChange difficulty questions if (\n // This expresion evaluates to true or false,\n // depending on whether difficulty is a valid property key in questions:\n (difficulty as DifficultyType) in questions\n // If it evaluates to false, this one won't execute:\n && currentPage + 1 < questions[difficulty as DifficultyType].length\n // and neither will the setCurrentPage invocation:\n) setCurrentPage((prevState) => prevState + 1);\n difficulty as DifficultyType import {useState} from 'react';\nimport {useSearchParams} from 'react-router-dom';\n\nconst questions = {\n easy: [],\n medium: [],\n hard: []\n};\n\ntype DifficultyType = keyof typeof questions;\n\nfunction Component () {\n const [searchParams, setSearchParams] = useSearchParams();\n const [currentPage, setCurrentPage] = useState(0);\n\n const difficulty = searchParams.get(\"difficulty\");\n\n const handlePageChange = () => {\n if (\n (difficulty as DifficultyType) in questions\n && currentPage + 1 < questions[difficulty as DifficultyType].length\n ) setCurrentPage((prevState) => prevState + 1);\n };\n\n const handleDifficultyChoice = (difficulty: DifficultyType) => {\n setSearchParams({ difficulty });\n };\n}\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18367514/" ]
74,646,644
<p>Hej!</p> <p>I own a domain registered through GCP and it's connected with Cloud DNS in GCP, I would be very happy if you could help me setup my custom domain for my web page at <a href="https://buahaha.github.io" rel="nofollow noreferrer">buahaha.github.io</a>.</p> <p>I think I know how to do this, because I did it before with other domain(s), but this time something is not working as it should. I have set up even a TXT record, and it does not propagate through DNS servers, and the same goes for my CNAME record. I attach screenshots of my setup below.</p> <p><a href="https://i.stack.imgur.com/PDACZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PDACZ.png" alt="GCP Cloud DNS setup" /></a></p> <p><a href="https://i.stack.imgur.com/ztAli.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ztAli.png" alt="dig command" /></a></p> <p>It's strange to me as it is the basic setup for this kind of service, and I'm really confused...</p> <p>Pozdrawiam,<br> Szymon </p>
[ { "answer_id": 74646655, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 0, "selected": false, "text": "difficulty const handlePageChange = () => {\n if (difficulty && currentPage + 1 < questions[difficulty]?.length) {\n setCurrentPage((prevState) => prevState + 1);\n }\n};\n" }, { "answer_id": 74646860, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": true, "text": "handlePageChange difficulty questions if (\n // This expresion evaluates to true or false,\n // depending on whether difficulty is a valid property key in questions:\n (difficulty as DifficultyType) in questions\n // If it evaluates to false, this one won't execute:\n && currentPage + 1 < questions[difficulty as DifficultyType].length\n // and neither will the setCurrentPage invocation:\n) setCurrentPage((prevState) => prevState + 1);\n difficulty as DifficultyType import {useState} from 'react';\nimport {useSearchParams} from 'react-router-dom';\n\nconst questions = {\n easy: [],\n medium: [],\n hard: []\n};\n\ntype DifficultyType = keyof typeof questions;\n\nfunction Component () {\n const [searchParams, setSearchParams] = useSearchParams();\n const [currentPage, setCurrentPage] = useState(0);\n\n const difficulty = searchParams.get(\"difficulty\");\n\n const handlePageChange = () => {\n if (\n (difficulty as DifficultyType) in questions\n && currentPage + 1 < questions[difficulty as DifficultyType].length\n ) setCurrentPage((prevState) => prevState + 1);\n };\n\n const handleDifficultyChoice = (difficulty: DifficultyType) => {\n setSearchParams({ difficulty });\n };\n}\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14041713/" ]
74,646,662
<pre><code>menu = { &quot;Baja Taco&quot;: 4.00, &quot;Burrito&quot;: 7.50, &quot;Bowl&quot;: 8.50, &quot;Nachos&quot;: 11.00, &quot;Quesadilla&quot;: 8.50, &quot;Super Burrito&quot;: 8.50, &quot;Super Quesadilla&quot;: 9.50, &quot;Taco&quot;: 3.00, &quot;Tortilla Salad&quot;: 8.00 } while True: # keep adding to the price if user prompts another item # i know the operation won't work its just what i want to happen try: x = input(&quot;Item: &quot;) y = 0 if x in menu: z = x + y print(f&quot;Total: ${z}&quot;) # If u want to ctrl+d out and get ur price except (EOFError): print(f&quot;Total: ${menu[x]}&quot;) break # so code can handle wrong inputs except (KeyError): pass </code></pre> <p>can't find a way to make items add up</p>
[ { "answer_id": 74646747, "author": "Chrispresso", "author_id": 2599709, "author_profile": "https://Stackoverflow.com/users/2599709", "pm_score": 0, "selected": false, "text": "total menu = {\n \"Baja Taco\": 4.00,\n \"Burrito\": 7.50,\n \"Bowl\": 8.50,\n \"Nachos\": 11.00,\n \"Quesadilla\": 8.50,\n \"Super Burrito\": 8.50,\n \"Super Quesadilla\": 9.50,\n \"Taco\": 3.00,\n \"Tortilla Salad\": 8.00\n}\n\ntotal = 0.0\nwhile True:\n try:\n x = input(\"Item: \")\n if x in menu:\n total += menu[x] # Notice that you're just adding the menu item price here\n print(f\"Total: ${total}\")\n...\n" }, { "answer_id": 74646772, "author": "KingWealth", "author_id": 6829943, "author_profile": "https://Stackoverflow.com/users/6829943", "pm_score": 2, "selected": true, "text": "menu total = 0\nwhile True:\n try:\n x = input(\"Item: \")\n if x in menu:\n total = total + menu[x]\n print(f\"Total: ${total}\")\n # If u want to ctrl+d out and get ur price\n except (EOFError):\n print(f\"Total: ${menu[x]}\")\n break\n # so code can handle wrong inputs\n except (KeyError):\n pass\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574466/" ]
74,646,722
<p><strong>App.js</strong></p> <pre><code>function App() { return ( &lt;div className=&quot;sm:text-center&quot;&gt; &lt;h1&gt; Hello &lt;/h1&gt; &lt;/div&gt; ); } export default App; </code></pre> <p><strong>tailwind.js</strong></p> <pre><code>/** @type {import('tailwindcss').Config} */ module.exports = { content: [], presets: [], darkMode: 'media', // or 'class' theme: { screens: { sm: '640px', md: '768px', lg: '1024px', xl: '1280px', '2xl': '1536px', }, </code></pre> <p>I'm expecting for the text to be aligned to the left by default and on screens 640px and above text should be centered. However the text stays aligned to the left. I do have the html meta tag for responsiveness on my index.html file '</p> <p>Any help is appreciated!</p>
[ { "answer_id": 74646747, "author": "Chrispresso", "author_id": 2599709, "author_profile": "https://Stackoverflow.com/users/2599709", "pm_score": 0, "selected": false, "text": "total menu = {\n \"Baja Taco\": 4.00,\n \"Burrito\": 7.50,\n \"Bowl\": 8.50,\n \"Nachos\": 11.00,\n \"Quesadilla\": 8.50,\n \"Super Burrito\": 8.50,\n \"Super Quesadilla\": 9.50,\n \"Taco\": 3.00,\n \"Tortilla Salad\": 8.00\n}\n\ntotal = 0.0\nwhile True:\n try:\n x = input(\"Item: \")\n if x in menu:\n total += menu[x] # Notice that you're just adding the menu item price here\n print(f\"Total: ${total}\")\n...\n" }, { "answer_id": 74646772, "author": "KingWealth", "author_id": 6829943, "author_profile": "https://Stackoverflow.com/users/6829943", "pm_score": 2, "selected": true, "text": "menu total = 0\nwhile True:\n try:\n x = input(\"Item: \")\n if x in menu:\n total = total + menu[x]\n print(f\"Total: ${total}\")\n # If u want to ctrl+d out and get ur price\n except (EOFError):\n print(f\"Total: ${menu[x]}\")\n break\n # so code can handle wrong inputs\n except (KeyError):\n pass\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16300552/" ]
74,646,730
<p>I have the following group of <code>GET</code> routes on Laravel:</p> <pre><code>Route::get('/location/get', 'Ajax@getProducts'); Route::get('/products/get', 'Ajax@getProducts'); Route::get('/schedule/get', 'Ajax@getProducts'); </code></pre> <p>I want to protect those routes with the automatically generated <code>CSRF</code> token from <code>Laravel</code>.</p> <p>I have read some workarounds about overriding method: <code>VerifyCsrfToken@isReading(...)</code>, but I'm not too much convinced about that.</p> <p>Then I'm looking for a more elegant solution.</p> <p>Thanks!</p>
[ { "answer_id": 74646926, "author": "Arthur Shlain", "author_id": 2453148, "author_profile": "https://Stackoverflow.com/users/2453148", "pm_score": 2, "selected": true, "text": "csrf Route::group(['before' => 'csrf'], function() {\n // your ::post routes\n});\n csrf_get Route::group(['before' => 'csrf_get'], function() {\n // your routes\n});\n" }, { "answer_id": 74648094, "author": "Ed McDarwin", "author_id": 19543917, "author_profile": "https://Stackoverflow.com/users/19543917", "pm_score": 0, "selected": false, "text": " <form action=“{{ your route name }}” method=“GET”> @csrf </form>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10541642/" ]
74,646,731
<p>Problem Statement</p> <p>A matrix is a 2D array of numbers arranged in rows and columns. We give you a Matrix of <code>N</code> rows and <code>M</code> columns.</p> <p>Now your task is to do this operation on this matrix:</p> <ul> <li>If the value matches with the current row and column number then add <code>3</code> with the value.</li> <li>If the value matches with only the current row number then add <code>2</code> with the value.</li> <li>If the value matches with only the current column number then add <code>1</code> with the value.</li> </ul> <p>Input Format</p> <ul> <li>The first line contains <code>N</code> is the number of rows in this matrix and <code>M</code> is the number of columns in this matrix</li> <li>The second line contains a 2D array <code>Arr[i][j]</code>.</li> </ul> <p>Constraints</p> <ul> <li><code>1 &lt;= N, M &lt;= 10</code></li> <li><code>0 &lt;= Arr[i][j] &lt;= 100</code></li> </ul> <p>Output Format</p> <pre><code>Print the matrix after the operation is done. </code></pre> <p>Sample Input 0</p> <pre class="lang-none prettyprint-override"><code>3 3 1 1 1 1 1 1 1 1 1 </code></pre> <p>Sample Output 0</p> <pre class="lang-none prettyprint-override"><code>4 3 3 2 1 1 2 1 1 </code></pre> <pre><code>#include &lt;stdio.h&gt;  int main(){ //here taking the row and column from the users int row; int column, temp; printf(&quot;enter row and column\n&quot;); scanf(&quot;%d%d&quot;, &amp;row, &amp;column); int arr[row][column]; //here taking the matrix input through the users for(int i = 0; i &lt; row; i++){ for(int j = 0; j &lt; column; j++){ scanf(&quot;%d&quot;, &amp;arr[i][j]); } for (int i=0; i&lt;row; i++){ for(int j=0; j&lt;column; j++ ){ if (arr[i][j] == arr[i+1] &amp;&amp; arr[i][j]== arr[j+1]){ temp= arr[i][j]+3; printf(&quot;%d&quot;, temp); } else if (arr[i][j] == arr[i+1]){ temp= arr[i][j]+ 2; printf(&quot;%d&quot;, temp); } else if (arr[i][j]== arr[j+1]){ temp= arr[i][j]+ 1; printf(&quot;%d&quot;, temp); } else{ temp= arr[i][j]; printf(&quot;%d&quot;, temp); } } } } return 0; } </code></pre> <p>After I run the code, this doesn't work.</p>
[ { "answer_id": 74647565, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 1, "selected": false, "text": "if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ int arr[row][column]; arr[i+1] arr[j+1] arr[i][j] == arr[i+1] int" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20584362/" ]
74,646,757
<p>I've been trying to run a PowerShell script, and upon doing so, I receive a message that NuGet Provider is required.</p> <pre><code>NuGet provider is required to continue This version of PowerShellGet requires minimum version '2.8.5.201' of NuGet provider to publish an item to NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or 'C:\Users\timothy.granata\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import the NuGet provider now? [Y] Yes [N] No [S] Suspend [?] Help (default is &quot;Y&quot;): </code></pre> <p>If I input <code>Y</code>, an error is returned:</p> <pre><code>Find-Module: NuGet provider is required to interact with NuGet-based repositories. Please ensure that '2.8.5.201' or newer version of NuGet provider is installed. </code></pre> <p>If I try running <code>Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force</code> as it recommends, I also get an error:</p> <pre><code>Install-PackageProvider: Unable to find repository with SourceLocation ''. Use Get-PSRepository to see all available repositories. </code></pre> <p>And finally, if I run <code>Get-PSRepository</code>, that also errors:</p> <pre><code>Get-PackageSource: Unable to find module providers (PowerShellGet). </code></pre> <p>In the script I am trying to debug, the code that seems to trigger this prompt is <code>Install-AWSToolsModule SecurityToken -Force</code>. The surrounding code looks like:</p> <pre class="lang-bash prettyprint-override"><code>if (-not (Get-Module AWS.Tools.Installer -ListAvailable)) { Install-Module AWS.Tools.Installer -Force } Install-AWSToolsModule SecurityToken -Force Get-AWSCredential -ListProfileDetail | ForEach-Object { Remove-AWSCredentialProfile -ProfileName $_.ProfileName -Force } </code></pre> <p>I have tried:</p> <ul> <li>Reinstalling PowerShell 7</li> <li>Making sure <a href="https://stackoverflow.com/a/61078227/6530134">I am using TLS 1.2</a> by running <code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12</code></li> <li>Running PowerShell as Administrator</li> <li><a href="https://learn.microsoft.com/en-us/answers/questions/257840/powershell-unable-to-find-module-providers-powersh.html" rel="nofollow noreferrer">Deleting the Modules folder</a> found in my C:\Users&lt;user&gt;\Documents\WindowsPowerShell folder</li> </ul> <p>I'm unsure what else I can try at this point. How can I install the NuGet provider for use with PowerShell 7.3?</p>
[ { "answer_id": 74647565, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 1, "selected": false, "text": "if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ int arr[row][column]; arr[i+1] arr[j+1] arr[i][j] == arr[i+1] int" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6530134/" ]
74,646,759
<p>I am creating an interactive website where the user is able to click anywhere on the page and each paragraph will show up one by one. At the moment the paragraphs are displaying to the right of the click but i want the paragraph to be centred on the mouse position. Is there a way to do this?</p> <p>Is there also a way to restrict the paragraphs from going off the screen as this creates a landscape scroll which i don't want, Any help would be appreciated.</p> <pre><code>const texts = [ &quot;Paragraph: 1&quot;, &quot;Paragraph: 2&quot;, &quot;Paragraph: 3&quot;, &quot;Paragraph: 4&quot;, &quot;Paragraph: 5&quot;, &quot;Paragraph: 6&quot;, &quot;Paragraph: 7&quot;, &quot;Paragraph: 8&quot;, &quot;Paragraph: 9&quot;, &quot;Paragraph: 10&quot; ]; const classes = [ &quot;red gray-bg font-1&quot;, &quot;blue font-2&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;red&quot;, &quot;blue&quot;, ]; // Keeps Track of Current Text let currentParaIdx = 0; document.addEventListener(&quot;click&quot;, (e) =&gt; { // Stop once All Texts are Displayed if (currentParaIdx === texts.length) return; const { clientX, clientY } = e; //get the click position //create the div const div = document.createElement(&quot;div&quot;); //set its text div.innerText = texts[currentParaIdx]; //set its position and position style div.classList=classes[currentParaIdx]; div.style.position = &quot;absolute&quot;; div.style.left = clientX + &quot;px&quot;; div.style.top = clientY + &quot;px&quot;; currentParaIdx++; document.body.append(div); //add div to the page }); </code></pre> <p>This is the code I have so far</p>
[ { "answer_id": 74647390, "author": "EssXTee", "author_id": 2339619, "author_profile": "https://Stackoverflow.com/users/2339619", "pm_score": 2, "selected": true, "text": "width height width height top left const paragraphs = [\n {text: `Paragraph: 1`, class: \"red gray-bg font-1\"},\n {text: `Paragraph: 2`, class: \"blue font-2\"},\n {text: `Paragraph: 3`, class: \"red\"},\n {text: `Paragraph: 4`, class: \"blue\"},\n {text: `Paragraph: 5<br>Different sized paragraph`, class: \"red\"},\n {text: `Paragraph: 6<br><br><br>Another different sized paragraph`, class: \"blue\"},\n {text: `Paragraph: 7 | This is a wider paragraph`, class: \"red\"},\n {text: `Paragraph: 8 | This is also wider but max-width prevents this paragraph from becoming too wide`, class: \"blue\"},\n {text: `Paragraph: 9`, class: \"red\"},\n {text: `Paragraph: 10`, class: \"blue\"}\n]\n\nlet currentParaIdx = 0\n\ndocument.body.addEventListener(\"click\", e => {\n if(currentParaIdx === paragraphs.length) return\n\n const { clientX, clientY } = e,\n div = document.createElement(\"div\")\n\n div.innerHTML = paragraphs[currentParaIdx].text\n div.className = `${paragraphs[currentParaIdx].class} paragraph`\n currentParaIdx++\n document.body.append(div)\n\n // Once the div is added, we can get its computed size\n // Then calculate if it will go off screen or not\n let bodyW = parseInt(getComputedStyle(document.body).width),\n bodyH = parseInt(getComputedStyle(document.body).height),\n divW = parseInt(getComputedStyle(div).width),\n divH = parseInt(getComputedStyle(div).height),\n divX = (clientX - Math.round(divW / 2) < 0) ? 0 : (clientX + Math.round(divW / 2) > bodyW) ? bodyW - (divW * 1.1) : clientX - Math.round(divW / 2),\n divY = (clientY - Math.round(divH / 2) < 0) ? 0 : (clientY + Math.round(divH / 2) > bodyH) ? bodyH - (divH * 1.1) : clientY - Math.round(divH / 2)\n \n div.style.left = `${divX}px`\n div.style.top = `${divY}px`\n}) html, body {\n width: 100%;\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\n.paragraph {\n max-width: 500px;\n position: absolute;\n cursor: default;\n}\n\n.red { color: #F00; }\n.blue { color: #00F; }\n\n.gray-bg { background: #CCC; }\n\n.font-1 { font-size: 1em; }\n.font-2 { font-size: 1.1em; font-weight: bold; } getComputedStyle() getBoundingClientRect() width height padding div.style.top = `${clientY + window.scrollY}px`\n ${} +" }, { "answer_id": 74657816, "author": "Cobain Ambrose", "author_id": 8410287, "author_profile": "https://Stackoverflow.com/users/8410287", "pm_score": 0, "selected": false, "text": "div {\n transform: translate(-50%, -50%);\n}\n body {\n overflow-x: hidden;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504382/" ]
74,646,761
<p>I have been trying to make a simple program to check a person's birthday and if their birthday is the same as their pet, for it to be printed out on the console, or if it's not the same to type out no valid input. I don't know why but the variables are not being taken in saying they aren't properly added or it just says they need a get/set. If anyone could show and explain how it should be done it would be like really awesome and cool and amazing. Here's the code:</p> <pre><code>using System; namespace MyApplication { class Program { static void Main(string[] args) { Human human = new Human(); human.name(); human.age(); human.id(); human.birthday(); Robot robot = new Robot(); robot.id(); robot.model(); Pet pet = new Pet(); pet.name(); pet.birthday(); Program program = new Program(); program.BirthdayCheck(&quot;&quot;,&quot;&quot;); } public static void BirthdayCheck(string userResponse1, string userResponse2) { if (userResponse1 == userResponse2) { Console.WriteLine(&quot;&quot; + userResponse1); } else { Console.WriteLine(&quot;No matching birthday&quot;); } } interface IHuman { void name(); void age(); void id(); void birthday(); } interface IRobot { void model(); void id(); } interface IPet { void name(); void birthday(); } class Human : IHuman { public string userResponse2; public string Birthday { get { return userResponse2; } set { userResponse2 = value; } } public void name() { Console.WriteLine(&quot;Citizen name: &quot;); Console.ReadLine(); } public void age() { Console.WriteLine(&quot;Citizen's age: &quot;); Console.ReadLine(); } public void id() { Console.WriteLine(&quot;Citizen's id: &quot;); Console.ReadLine(); } public void birthday() { Console.WriteLine(&quot;Citizen's birthday: &quot;); userResponse2 = Console.ReadLine(); } } class Robot : IRobot { public void model() { Console.WriteLine(&quot;Enter Robot Model: &quot;); Console.ReadLine(); } public void id() { Console.WriteLine(&quot;Enter Robot Id: &quot;); Console.ReadLine(); } } class Pet : IPet { public string userResponse1; public string Birthday { get { return userResponse1; } set { userResponse1 = value; } } public void name() { Console.WriteLine(&quot;Enter pet name: &quot;); Console.ReadLine(); } public void birthday() { Console.WriteLine(&quot;Enter pet birthday: &quot;); userResponse1 = Console.ReadLine(); } } } } </code></pre> <p>I had no issues with the interfaces themselves and it does that the information, it just doesn't want to compare the two between them. I don't know if it's just a logical or syntax error, but hopefully, it's at least partially correct. Finished up some syntax errors but the issues still remain. The error message that appears is &quot;Member Program.BitrhdayCheck(string, string) cannot be accessed with an instance reference; qualify it with a type name instead.&quot;</p>
[ { "answer_id": 74646846, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": -1, "selected": false, "text": " public string BirthdayCheck()\n { \n" }, { "answer_id": 74649708, "author": "Ceemah Four", "author_id": 9278478, "author_profile": "https://Stackoverflow.com/users/9278478", "pm_score": 0, "selected": false, "text": " Program program = new Program();\n program.BirthdayCheck(\"\",\"\");\n BirthdayCheck static void Main(string[] args)\n {\n\n\n Human human = new Human();\n human.name();\n human.age();\n human.id();\n human.birthday();\n\n\n Robot robot = new Robot();\n robot.id();\n robot.model();\n\n\n Pet pet = new Pet();\n pet.name();\n pet.birthday();\n\n BirthdayCheck(pet.Birthday, human.Birthday); // birthdaycheck is method of the program class, hence does not need to be invoked with a new program object. \n// Additionally, you need to pass an actual birthday value to compare instead of blank strings. \n\n Console.ReadKey(); // this step ensures the console does not close after the birthday check\n }\n public static void BirthdayCheck(string userResponse1, string userResponse2)\n {\n if (userResponse1 == userResponse2)\n {\n\n Console.WriteLine(\"\" + userResponse1);\n }\n else\n {\n Console.WriteLine(\"No matching birthday\");\n }\n\n }\n Citizen name:\nw\nCitizen's age:\n12\nCitizen's id:\n1\nCitizen's birthday:\n10/10/1990\nEnter Robot Id:\n2\nEnter Robot Model:\nr2d2\nEnter pet name:\np2v2\nEnter pet birthday:\n11/11/1991\nNo matching birthday\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209877/" ]
74,646,811
<p>I was trying to find the way you can identify embed message text and author, but never found it. So is there any way to do that?</p> <p>Googled through out of the Internet but not found it unfortunately.</p>
[ { "answer_id": 74646938, "author": "Chrispresso", "author_id": 2599709, "author_profile": "https://Stackoverflow.com/users/2599709", "pm_score": 1, "selected": false, "text": "obj obj.author obj.title" }, { "answer_id": 74650668, "author": "J Muzhen", "author_id": 12341397, "author_profile": "https://Stackoverflow.com/users/12341397", "pm_score": 0, "selected": false, "text": "Message author = message.author\n embed = discord.Embed.from_data(message.embeds[0]) # gets embed from message\n discord.Embed title description embedTitle = embed.title # get title\nembedDescription = embed.description # get description\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659342/" ]
74,646,866
<p>When I compile this code</p> <pre class="lang-rust prettyprint-override"><code> fn read(&amp;mut self) -&gt; Result&lt;u8, &amp;str&gt; { if self.pos &gt;= 512 { return Err(&quot;End of buffer&quot;.into()); } let res = self.buf[self.pos]; self.pos += 1; Ok(res) } fn read_u16(&amp;mut self) -&gt; Result&lt;u16, &amp;str&gt; { let res = ((self.read()? as u16) &lt;&lt; 8) | (self.read()? as u16); Ok(res) } </code></pre> <p>The compiler throws the following error</p> <pre class="lang-none prettyprint-override"><code>error[E0499]: cannot borrow `*self` as mutable more than once at a time --&gt; src/byte_packet_buffer.rs:53:51 | 52 | fn read_u16(&amp;mut self) -&gt; Result&lt;u16, &amp;str&gt; { | - let's call the lifetime of this reference `'1` 53 | let res = ((self.read()? as u16) &lt;&lt; 8) | (self.read()? as u16); | ------------ ^^^^^^^^^^^ second mutable borrow occurs here | | | first mutable borrow occurs here | returning this value requires that `*self` is borrowed for `'1` For more information about this error, try `rustc --explain E0499`. error: could not compile `dns_self` due to previous error </code></pre> <p>But if I modify the return value from <code>&amp;str</code> to <code>String</code>, it compiles without error.</p> <p>Can anybody explain why I get an error when returning <code>&amp;str</code> but not when returning <code>String</code>?</p>
[ { "answer_id": 74646962, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 3, "selected": true, "text": "fn read<'a>(&'a mut self) -> Result<u8, &'a str>\n self Result str fn read(&mut self) -> Result<u8, &'static str>\n" }, { "answer_id": 74647730, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 1, "selected": false, "text": "self &str self ? match expr {\n Ok(v) => v,\n Err(e) => return Err(From::from(e)),\n}\n &str cargo +nightly rustc -- -Zpolonius" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12294900/" ]
74,646,885
<p>In my Effect im listening on an Action, that value of the Action is a string Array. Now i need to loop over the array and use the values as inputs for the next asnyc function.</p> <pre><code>someEffect$ = createEffect(() =&gt; this.action$.pipe( ofType(someAction), mergeMap(({ someValue }) =&gt; this.httpCall.getSomeTh(someValue[0]).pipe( map((result) =&gt; someOtherAction) ) ) ) ) </code></pre> <p>I have tried a few different things. The one below seemed to get me to the closest one i wanted. But since the Rest-calls need a moment to return, the array is always empty.</p> <pre><code>someEffect$ = createEffect(() =&gt; this.action$.pipe( ofType(someAction), mergeMap(({ someValue }) =&gt; { const array = []; someValue.forEach((value) =&gt; this.http.get(value).pipe(tap((object) =&gt; array.push(object))) ) return of(someOtherAction(array)) } ) ) ) </code></pre> <p>Does anyone have an idea, how to make the whole thing wait for the rest calls to return back?</p>
[ { "answer_id": 74649482, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 3, "selected": true, "text": "forkJoin someEffect$ = createEffect(() => \n this.action$.pipe(\n ofType(someAction),\n mergeMap(({ someValue }) => \n forkJoin(someValue.map(value => this.http.get(value))) \n ) \n )\n)\n forkJoin" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11896081/" ]
74,646,887
<p>I am trying to run linear regression through functional programming. However, I am not able to get the output successfully. <code>purrr:::map</code> returns multiple rows per nested list instead of one row.</p> <pre><code>#perform linear regression for each cylinder mtcars_result &lt;- mtcars%&gt;% nest(-cyl)%&gt;% mutate(model=map(data,~ lm(as.formula(&quot;mpg~disp&quot;),data=.)), n=map(data,~nrow(.))) #predict values mtcars_result$predict &lt;- 1:3 #helper function to obtain predict values get_prediction &lt;- function(m,varname,predict){ predictdata &lt;- data.frame(predict) names(predictdata) &lt;- c(varname) predict(m,newdata=predictdata,interval=&quot;confidence&quot;,level=0.95) } #prediction, notice it returns three rows per nested list mtcars_result2 &lt;- mtcars_result%&gt;%mutate(predicted_values=map(model,get_prediction,&quot;disp&quot;,predict)) mtcars_result2$predicted_values [[1]] fit lwr upr 1 19.08559 11.63407 26.53712 2 19.08920 11.67680 26.50160 3 19.09280 11.71952 26.46609 [[2]] fit lwr upr 1 40.73681 32.68945 48.78418 2 40.60167 32.62715 48.57619 3 40.46653 32.56482 48.36824 [[3]] fit lwr upr 1 22.01316 14.74447 29.28186 2 21.99353 14.74479 29.24227 3 21.97390 14.74511 29.20268 </code></pre> <p>My attempt:</p> <p>I notice the main issue is probably due to the <code>predict</code> argument in <code>get_prediction()</code>. When I run this version of <code>get_prediction()</code></p> <pre><code>get_prediction &lt;- function(m,varname,predict){ predict_global&lt;&lt;-predict predictdata &lt;- data.frame(predict) names(predictdata) &lt;- c(varname) predict(m,newdata=predictdata,interval=&quot;confidence&quot;,level=0.95) } &gt; predict_global [1] 1 2 3 </code></pre> <p>Therefore, my instinct is to use <code>rowwise()</code>, but it ends up with an error:</p> <pre><code>mtcars_result2 &lt;- mtcars_result%&gt;%rowwise()%&gt;%mutate(predicted_values=map(model,get_prediction,&quot;disp&quot;,predict)) Error in UseMethod(&quot;predict&quot;) : no applicable method for 'predict' applied to an object of class &quot;c('double', 'numeric')&quot; </code></pre> <p>Can anyone shed some lights for me? maybe we can use <code>purrr::pmap</code> instead of <code>purrr::map</code>?</p>
[ { "answer_id": 74647498, "author": "TimTeaFan", "author_id": 9349302, "author_profile": "https://Stackoverflow.com/users/9349302", "pm_score": 3, "selected": true, "text": "imap predict .y mtcars_result %>%\n mutate(predicted_values = imap(model, ~ get_prediction(.x, \"disp\", predict[.y])))\n rowwise() mtcars_result %>% \n rowwise() %>% \n mutate(predicted_values = list(get_prediction(model, \"disp\", predict)))\n\n#> # A tibble: 3 × 6\n#> # Rowwise: \n#> cyl data model n predict predicted_values\n#> <dbl> <list> <list> <list> <int> <list> \n#> 1 6 <tibble [7 × 10]> <lm> <int [1]> 1 <dbl [1 × 3]> \n#> 2 4 <tibble [11 × 10]> <lm> <int [1]> 2 <dbl [1 × 3]> \n#> 3 8 <tibble [14 × 10]> <lm> <int [1]> 3 <dbl [1 × 3]>\n" }, { "answer_id": 74647545, "author": "peter861222", "author_id": 17918739, "author_profile": "https://Stackoverflow.com/users/17918739", "pm_score": 1, "selected": false, "text": "purrr::map2 get_prediction get_prediction <- function(m,predict,varname){\n predictdata <- data.frame(predict)\n names(predictdata) <- c(varname)\n predict(m,newdata=predictdata,interval=\"confidence\",level=0.95)\n}\n\n#prediction, notice there are duplicates\nmtcars_result2 <- mtcars_result%>%mutate(predicted_values=map2(model,predict,get_prediction,\"disp\"))\nmtcars_result2$predicted_values\n\n[[1]]\n fit lwr upr\n1 19.08559 11.63407 26.53712\n\n[[2]]\n fit lwr upr\n1 40.60167 32.62715 48.57619\n\n[[3]]\n fit lwr upr\n1 21.9739 14.74511 29.20268\n" }, { "answer_id": 74647605, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": false, "text": "cyl map2 library(tidyverse)\n\noptions(pillar.sigfig = 7)\n\nmtcars %>%\n split(f = .$cyl) %>% \n map2_dfr(c(2, 1, 3), \n ~lm(mpg ~ disp, data = .) %>% \n get_prediction(\"disp\", .y) %>% \n as_tibble(),\n .id = \"cyl\")\n 2, 1, 3 # A tibble: 3 × 4\n cyl fit lwr upr\n <chr> <dbl> <dbl> <dbl>\n1 4 40.60167 32.62715 48.57619\n2 6 19.08559 11.63407 26.53712\n3 8 21.97390 14.74511 29.20268\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17918739/" ]
74,646,952
<p>Trying to edit the below grammar and define the semantic actions required to translate arithmetic expressions written in the language defined below into postfix notation.</p> <pre><code>grammar Expr; expr: expr ('*'|'/') term | expr ('+'|'-') term | term ; term: '('expr')' | ID | NUM ; ID: [a-z]+; NUM: [0-9]+; WS: [\t\r\n]+-&gt;skip; </code></pre> <p>To implement the translator I'm embedding semantic actions as Java code in the g4 grammar file by using the push and pop operations of a stack. But when compiling I'm hit with a bunch of errors.</p> <p>Here is what I have so far:</p> <pre><code>grammar Expr; expr: expr (op=('*'|'/') term { Stack&lt;String&gt; s = new Stack&lt;String&gt;(); s.push($op.text); s.push($term.text); String result = s.pop() + s.pop() + s.pop(); $expr.text = result; } ) | expr (op=('+'|'-') term { Stack&lt;String&gt; s = new Stack&lt;String&gt;(); s.push($op.text); s.push($term.text); String result = s.pop() + s.pop() + s.pop(); $expr.text = result; } ) | term ; term: '('expr')' { Stack&lt;String&gt; s = new Stack&lt;String&gt;(); s.push($expr.text); String result = s.pop(); $term.text = result; } | ID {Stack&lt;String&gt; s = new Stack&lt;String&gt;(); s.push($ID.text); String result = s.pop(); $term.text = result; } | NUM {Stack&lt;String&gt; s = new Stack&lt;String&gt;(); s.push($NUM.text); String result = s.pop(); $term.text = result; } ; ID: [a-z]+; NUM: [0-9]+; WS: [\t\r\n]+-&gt;skip; </code></pre> <p>When compiling I'm hit with an error block</p> <p><a href="https://i.stack.imgur.com/S7oJt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S7oJt.png" alt="enter image description here" /></a></p> <p>I'm not sure how to fix this or if there's a better way to implement.</p>
[ { "answer_id": 74647498, "author": "TimTeaFan", "author_id": 9349302, "author_profile": "https://Stackoverflow.com/users/9349302", "pm_score": 3, "selected": true, "text": "imap predict .y mtcars_result %>%\n mutate(predicted_values = imap(model, ~ get_prediction(.x, \"disp\", predict[.y])))\n rowwise() mtcars_result %>% \n rowwise() %>% \n mutate(predicted_values = list(get_prediction(model, \"disp\", predict)))\n\n#> # A tibble: 3 × 6\n#> # Rowwise: \n#> cyl data model n predict predicted_values\n#> <dbl> <list> <list> <list> <int> <list> \n#> 1 6 <tibble [7 × 10]> <lm> <int [1]> 1 <dbl [1 × 3]> \n#> 2 4 <tibble [11 × 10]> <lm> <int [1]> 2 <dbl [1 × 3]> \n#> 3 8 <tibble [14 × 10]> <lm> <int [1]> 3 <dbl [1 × 3]>\n" }, { "answer_id": 74647545, "author": "peter861222", "author_id": 17918739, "author_profile": "https://Stackoverflow.com/users/17918739", "pm_score": 1, "selected": false, "text": "purrr::map2 get_prediction get_prediction <- function(m,predict,varname){\n predictdata <- data.frame(predict)\n names(predictdata) <- c(varname)\n predict(m,newdata=predictdata,interval=\"confidence\",level=0.95)\n}\n\n#prediction, notice there are duplicates\nmtcars_result2 <- mtcars_result%>%mutate(predicted_values=map2(model,predict,get_prediction,\"disp\"))\nmtcars_result2$predicted_values\n\n[[1]]\n fit lwr upr\n1 19.08559 11.63407 26.53712\n\n[[2]]\n fit lwr upr\n1 40.60167 32.62715 48.57619\n\n[[3]]\n fit lwr upr\n1 21.9739 14.74511 29.20268\n" }, { "answer_id": 74647605, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": false, "text": "cyl map2 library(tidyverse)\n\noptions(pillar.sigfig = 7)\n\nmtcars %>%\n split(f = .$cyl) %>% \n map2_dfr(c(2, 1, 3), \n ~lm(mpg ~ disp, data = .) %>% \n get_prediction(\"disp\", .y) %>% \n as_tibble(),\n .id = \"cyl\")\n 2, 1, 3 # A tibble: 3 × 4\n cyl fit lwr upr\n <chr> <dbl> <dbl> <dbl>\n1 4 40.60167 32.62715 48.57619\n2 6 19.08559 11.63407 26.53712\n3 8 21.97390 14.74511 29.20268\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659370/" ]
74,646,964
<p>I have a function that returns a byte array that represents a JSON string I need to parse. Generally, I would use <code>Encoding.Default.GetString(myByteArray)</code> to convert it to a string, but the resulting string has some unrecognized characters in it: <code>?{&quot;rects&quot;:[],&quot;text&quot;:&quot;&quot;}</code> instead of <code>{&quot;rects&quot;:[],&quot;text&quot;:&quot;&quot;}</code>.</p> <p>I have tried using every other encoding scheme the <code>Encoding</code> class has (that I know of anyway): <code>UTF8</code>, <code>UTF7</code>, <code>UTF32</code>, <code>Unicode</code>, <code>BigEndianUnicode</code>, <code>Latin1</code>, and <code>ASCII</code>, but every single one resulted in a string with <code>?</code>, <code>??</code>, or <code>ÿ_</code> at the beginning (or in the case of UTF32, the whole string was <code>?</code>'s).</p> <p>Strangely, using <code>new StreamReader(new MemoryStream(myByteArray)).ReadToEnd()</code> decoded the string perfectly, and is what I'm currently using in my code. I used <code>StreamReader.CurrentEncoding</code> to figure out what encoding it was using and printed it to the console (<code>System.Text.UnicodeEncoding</code>), then tried using <code>new UnicodeEncoding().GetString(myByteArray)</code>, but still no luck.</p> <p>How do I identify what encoding the byte arrays are using so I can decode it directly instead of wrapping it in streams?</p> <pre class="lang-cs prettyprint-override"><code>// data is the example JSON string: {&quot;rects&quot;:[],&quot;text&quot;:&quot;&quot;} // In practice, the JSON strings are much longer. var data = new byte[] { 255, 254, 123, 0, 34, 0, 114, 0, 101, 0, 99, 0, 116, 0, 115, 0, 34, 0, 58, 0, 91, 0, 93, 0, 44, 0, 34, 0, 116, 0, 101, 0, 120, 0, 116, 0, 34, 0, 58, 0, 34, 0, 34, 0, 125, 0 }; var ms = new MemoryStream(data); var sr = new StreamReader(ms); var text = sr.ReadToEnd(); Console.WriteLine(sr.CurrentEncoding); Console.WriteLine(text); var text2 = Encoding.Default.GetString(data); Console.WriteLine(text2); dynamic json = JsonConvert.DeserializeObject&lt;dynamic&gt;(text); Console.WriteLine(json.text); Console.WriteLine(json.rects); </code></pre> <p>Thanks!</p>
[ { "answer_id": 74647367, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 2, "selected": true, "text": "FE UTF-16 (LE) var data = new byte[] { \n 255, 254, // <- BOM (UTF-16 (LE))\n 123, 0, 34, 0, 114, 0, /* Payload */ };\n string result = Encoding.Unicode.GetString(data.AsSpan(2));\n StreamReader" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14121186/" ]
74,646,975
<p>I have a template twig in html for example:</p> <pre><code>&lt;p&gt;Test document&lt;/p&gt; &lt;p&gt;However&lt;/p&gt; </code></pre> <p>I would like to replace the word 'Test' in the include template. <code>{% include '@template/testing' %}</code></p> <p>Is there some solution to replace the word in the include statement?</p> <p>I tried to use replace inside the <code>{% include '@template/testing' %}</code> but I don`t how to start it.</p>
[ { "answer_id": 74649978, "author": "thomasf10", "author_id": 18219390, "author_profile": "https://Stackoverflow.com/users/18219390", "pm_score": -1, "selected": false, "text": "{%- set block_modify -%}\n{% include 'template.html' %}\n{%- endset -%}\n\n{% if 'Hi' in block_modify %}\n\n{{ block_modify | replace ({'Hi':'Hello'}) | raw}}\n\n{% endif %}\n" }, { "answer_id": 74651257, "author": "Arleigh Hix", "author_id": 6127393, "author_profile": "https://Stackoverflow.com/users/6127393", "pm_score": 1, "selected": true, "text": "{# template.html will have access to the variables from the current context and the additional ones provided #}\n{% include 'template.html' with {'foo': 'bar'} %}\n\n{% set vars = {'foo': 'bar'} %}\n{% include 'template.html' with vars %}\n {# only the foo variable will be accessible #}\n{% include 'template.html' with {'foo': 'bar'} only %}\n{# no variables will be accessible #}\n{% include 'template.html' only %}\n <p>{{ doc_name|default('Test') }} document</p>\n\n<p>However</p>\n {% set doc_name = 'new name' %}\n{% include '@template/testing' %}\n {% include '@template/testing' with {'doc_name':'new name'} %}\n {% include '@template/testing' with {'doc_name':'new name'} only %}\n <p>new name document</p>\n\n<p>However</p>\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74646975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18219390/" ]
74,647,047
<p>I am trying to round up 5.9999998 to 5.999.</p> <p>But I have a problem, If I do round(number) it'll round it up to 6. How can I round a number like this to max 3 decimals?</p>
[ { "answer_id": 74647133, "author": "3dSpatialUser", "author_id": 5775358, "author_profile": "https://Stackoverflow.com/users/5775358", "pm_score": 2, "selected": false, "text": "number = 5.999999998\nnew_number = int(number * 1e3) / 1e3\n" }, { "answer_id": 74647167, "author": "Dhruvin Vadgama", "author_id": 20499874, "author_profile": "https://Stackoverflow.com/users/20499874", "pm_score": 0, "selected": false, "text": "\nx = 4/3\n\n# round up to 3 decimal places\nx = round(x, 3)\n\nprint(x)\n\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494538/" ]
74,647,052
<p>My dataframe is like this:</p> <pre><code>data = { &quot;a&quot;: [420, 380, 390], &quot;b&quot;: [50, 40, 45] } df = pd.DataFrame(data) </code></pre> <p>I want to add new item at the end of this dataframe, and remove the first item. I mean cont will be 3 each addition.</p> <p>New item add</p> <pre><code>{&quot;a&quot;: 300, b: 88} </code></pre> <p>and last stuation will be:</p> <pre><code>data = { &quot;a&quot;: [380, 390, 300], &quot;b&quot;: [40, 45, 88] } </code></pre> <p>Is there a short way to do this?</p>
[ { "answer_id": 74647078, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 1, "selected": false, "text": "pd.concat append dct = {\"a\": 300, \"b\": 88}\ndf_new = pd.concat([df, pd.Series(dct).to_frame().T]\n ).iloc[1:, :].reset_index(drop=True)\nprint(df_new)\n\n# If maybe the values of 'dict' have multiple items.\n# dct = {\"a\": [300, 400], \"b\": [88, 98]}\n# df_new = pd.concat([df, pd.DataFrame(dct)]\n# ).iloc[1:, :].reset_index(drop=True)\n df pandas.DataFrame.append index reset_index dct = {\"a\": 300, \"b\": 88}\ndf_new = df.append(dct, ignore_index=True).drop(0, axis=0).reset_index(drop=True)\nprint(df_new)\n a b\n0 380 40\n1 390 45\n2 300 88\n" }, { "answer_id": 74647198, "author": "Tiansu Yu", "author_id": 7063856, "author_profile": "https://Stackoverflow.com/users/7063856", "pm_score": 0, "selected": false, "text": "df.append() new_row = {\"a\": 300, \"b\": 88}\ndf2 = df.append(new_row, ignore_index=True)\n append Dataframe dict ignore_index=True iloc df3 = df2.iloc[1:, :]\n df3 = df2.drop(df.index[0], axis=0, inplace=False)\n inplace=True df2 None" }, { "answer_id": 74647417, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "concat df = pd.concat([df.iloc[1:],\n pd.DataFrame.from_dict({0: d}, orient='index')], \n ignore_index=True)\n a b\n0 380 40\n1 390 45\n2 300 88\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694716/" ]
74,647,054
<p>I would like to import a CSV in Django. The issue occurs when trying to import based on the attributes. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>class Event(models.Model): id = models.BigAutoField(primary_key=True) amount = models.ForeignKey(Amount, on_delete=models.CASCADE) value = models.FloatField() space = models.ForeignKey(Space, on_delete=models.RESTRICT) time = models.ForeignKey(Time, on_delete=models.RESTRICT) class Meta: managed = True db_table = &quot;event&quot; class Space(models.Model): objects = SpaceManager() id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=100) type = models.ForeignKey(SpaceType, on_delete=models.RESTRICT) space_date = models.DateField(blank=True, null=True) def natural_key(self): return self.code # + self.type + self.source_date def __str__(self): return f&quot;{self.name}&quot; class Meta: managed = True db_table = &quot;space&quot; class Time(models.Model): objects = TimeManager() id = models.BigAutoField(primary_key=True) type = models.ForeignKey(TimeType, on_delete=models.RESTRICT) startdate = models.DateTimeField() enddate = models.DateTimeField() def natural_key(self): return self.name def __str__(self): return f&quot;{self.name}&quot; class Meta: managed = True db_table = &quot;time&quot; </code></pre> <p>Now, I create the resource that should find the right objects, but it seems it does not enter into <code>ForeignKeyWidget(s)</code> at all:</p> <pre class="lang-py prettyprint-override"><code>class AmountForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, **kwargs): logger.critical(&quot;&lt;&lt;&lt;&lt;&lt; {AmountForeignKeyWidget} &lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;) name_upper = value.upper() amount = Amount.objects.get_by_natural_key(name=name_upper) return amount class SpaceForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row, **kwargs): logger.critical(&quot;&lt;&lt;&lt;&lt;&lt; {SpaceForeignKeyWidget} &lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;) space_code = row[&quot;space_code&quot;] space_type = SpatialDimensionType.objects.get_by_natural_key(row[&quot;space_type&quot;]) try: space_date = datetime.strptime(row[&quot;space_date&quot;], &quot;%Y%m%d&quot;) except ValueError: space_date = None space = Space.objects.get( code=space_code, type=space_type, source_date=space_date ) return space class TimeForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row, **kwargs): logger.critical(&quot;&lt;&lt;&lt;&lt;&lt; {TimeForeignKeyWidget} &lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;) time_type = TimeType.objects.get_by_natural_key(row[&quot;time_type&quot;]) time_date = parse_datetime(row[&quot;time_date&quot;]) time = Time.objects.get_or_create( type=time_type, startdate=time_date), defaults={...} ) return time class EventResource(ModelResource): amount = Field( column_name=&quot;amount&quot;, attribute=&quot;amount&quot;, widget=AmountForeignKeyWidget(Amount), ) space = Field( # column_name=&quot;space_code&quot;, attribute=&quot;space&quot;, widget=SpaceForeignKeyWidget(Space), ) time = Field( attribute=&quot;time&quot;, widget=TimeForeignKeyWidget(Time), ) def before_import_row(self, row, row_number=None, **kwargs): logger.error(f&quot;&gt;&gt;&gt;&gt; before_import_row() &gt;&gt;&gt;&gt;&gt;&gt;&quot;) time_date = datetime.strptime(row[&quot;time_date&quot;], &quot;%Y%m%d&quot;).date() time_type = TimeType.objects.get_by_natural_key(row[&quot;time_type&quot;]) Time.objects.get_or_create( type=time_type, startdate=time_date, defaults={ &quot;name&quot;: str(time_type) + str(time_date), &quot;type&quot;: time_type, &quot;startdate&quot;: time_date, &quot;enddate&quot;: time_date + timedelta(days=1), }, ) class Meta: model = Event </code></pre> <p>I added some loggers, but I only print out the log at <code>AmountForeignKeyWidget</code>. The main question is: How to search for objects in <code>Space</code> by attributes (<code>space_code</code>,<code>space_type</code>,<code>space_date</code>) and in <code>Time</code> search and create by (<code>time_date</code>,<code>time_type</code>) A lesser question is why <code>SpaceForeignKeyWidget</code> and <code>TimeForeignKeyWidget</code> are not used?</p>
[ { "answer_id": 74648526, "author": "Matthew Hegarty", "author_id": 39296, "author_profile": "https://Stackoverflow.com/users/39296", "pm_score": 1, "selected": false, "text": "Space (space_code,space_type,space_date) Time (time_date,time_type) import-export before_import_row() get_or_create() (Time Space Event import-export before_save_instance() import_obj() def import_obj(self, obj, data, dry_run, **kwargs):\n # 'obj' is the object instance\n # 'data' is the row data\n # go ahead and create the relation objects\n time_type = TimeType.objects.get_by_natural_key(row[\"time_type\"])\n time_date = parse_datetime(row[\"time_date\"])\n obj.time = Time.objects.get_or_create(\n type=time_type, startdate=time_date), defaults={...}\n )\n # other relation creations omitted...\n super().import_obj(obj, data, dry_run, **kwargs)\n SpaceForeignKeyWidget TimeForeignKeyWidget clean() row SpaceForeignKeyWidget TimeForeignKeyWidget clean() def clean(self, value, row=None, **kwargs):\n # your implementation here\n AmountForeignKeyWidget class EventResource(ModelResource):\n amount = Field(\n column_name=\"amount\",\n attribute=\"amount\",\n widget=ForeignKeyWidget(Amount, field=\"name__iexact\"),\n )\n" }, { "answer_id": 74666498, "author": "miller", "author_id": 1600108, "author_profile": "https://Stackoverflow.com/users/1600108", "pm_score": 0, "selected": false, "text": "class EventResource(ModelResource):\n amount = Field(\n column_name=\"amount\",\n attribute=\"amount\",\n widget=ForeignKeyWidget(Amount, field=\"name__iexact\"),\n )\n space_code = Field(\n attribute=\"space\",\n widget=SpaceForeignKeyWidget(Space),\n )\n time_date = Field(\n attribute=\"time\",\n widget=TimeForeignKeyWidget(Time),\n )\n\n class Meta:\n model = Event\n amount class SpaceForeignKeyWidget(ForeignKeyWidget):\n def clean(self, value, row, **kwargs):\n space_code = row[\"spacial_code\"]\n space_type = SpaceDimensionType.objects.get(type=row[\"space_type\"])\n try:\n space_date = datetime.strptime(row[\"space_date\"], \"%Y%m%d\")\n except ValueError:\n space_date = None\n\n space = SpaceDimension.objects.get(\n code=space_code, type=space_type, source_date=space_date\n )\n return space\n\n\nclass TimeForeignKeyWidget(ForeignKeyWidget):\n def clean(self, value, row, **kwargs):\n time_type = TimeDimensionType.objects.get(type=row[\"time_type\"])\n delta = T_TYPES[time_type]\n\n start_date = datetime.strptime(row[\"time_date\"], \"%Y%m%d\").date()\n end_date = start_date + timedelta(days=delta)\n time, created = TimeDimension.objects.get_or_create(\n type=time_type,\n startdate=start_date,\n enddate=start_date + timedelta(days=delta),\n defaults={\n \"name\": f\"{time_type}: {start_date}-{end_date}\",\n \"type\": time_type,\n \"startdate\": start_date,\n \"enddate\": end_date,\n },\n )\n return temporal\n\n SpaceForeignKeyWidget TimeForeignKeyWidget before_import_row()" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1600108/" ]
74,647,061
<p>I have a task to practice and I just can't get the solution. It should be noted that I am a total beginner. There is 1min for the exercise, so it should be child's play. But I am racking my brains over it.</p> <p>I am supposed to write an expression for the following :</p> <p>Let x and k be variables of type int. Formulate a C condition with bitwise operator that is true exactly when x is less than 2^(k-1).</p> <p>I would have done this with the ?-operator. So something like</p> <p>( ) ? 1 : 0</p> <p>But which condition must be in the brackets? I can't think of a bitwise operator that can be used to compare less than?</p> <p>I really don't have any Idea :/</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15052389/" ]
74,647,074
<p>I'm working on an university project with ML, and the project got quite big, I usually don't use github but I need to format my pc and do not trust the Google Drive backup I have, therefore I wanna have a second one so I don't lose the code whatsoever.</p> <p>I'm using Git with GitHub desktop, I'm not very knowledgeable in Git, so I'm having a hard time uploading this project, since it disconnects everytime I try to upload it, I'm pretty sure it is because of the size, any help with that?</p> <p>The IDE I'm using is PyCharm and the Python version is 3.7, I already have a requirements.txt created.</p> <p>I tried searching for pre made git ignore files, but it didn't work.</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15192515/" ]
74,647,098
<p>I have the following dataframe <strong><code>df</code></strong>, where the variable <strong><code>types</code></strong> corresponds to up to 3 types for each ID (the dataset has approximately 3000 rows):</p> <pre><code>ID types grade num a01 a,b,c 7.1 1 a02 c,d 7.7 3 a03 c 7.3 4 a04 a,c,f 7.9 5 a05 a,c,e 6.7 3 </code></pre> <p>I want to create a scatterplot, where the x axis corresponds to the <strong><code>num</code></strong> column, the y axis corresponds to the <strong><code>grade</code></strong> and the color of each point corresponds to its type, similar to this: <a href="https://i.stack.imgur.com/vWmVK.png" rel="nofollow noreferrer">https://i.stack.imgur.com/vWmVK.png</a></p> <p>However, since <strong><code>types</code></strong> has more than one value, I'm struggling to plot it. If types only had one type, I know I could simply do <code>geom_point(aes(colour = types))</code>, but since it can have up to 3, I don't know how to proceed.</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20638561/" ]
74,647,169
<p>Structure of my directories and files is:</p> <pre><code>Folder1: File1 Folder2: File2 File3 File4 Folder3: File5 File6 File7 file8 </code></pre> <p>What i want to acheive is to copy File1, File2, File6 and File7 into one Folder4. I need a script for that because i have multiple sets like that and i want to have a set made of different Folder4 in a folder 5:</p> <pre><code>Folder5: Folder4a: File1, File2, File6, File7 Filder4b: File1, File2,File6, File7 </code></pre> <p>etc. all the files have the same prefix but different extensions and contain different informations that are linked together.</p> <p>Thanks a lot for any hepl!</p> <pre><code>#!/bin/bash export output_dir='./Folder5' if [ ! -e ${output_dir} ] then echo ${output_dir} mkdir ${output_dir} fi for i in `ls file1` do export folder=`echo ${i} | awk -F . '{print $1}'` if [ ! -f ${folder} ] then mkdir ./${output_dir}/${folder} cp ${i} ./${output_dir}/${folder} fi done </code></pre> <p>this created Folder5, and in Folder1 where my File1 is it copies its prefix creates the Folder4 named as the prefix of file1 and copies file1 into that folder. And now i have an issue how do i access other files in subfolders and how do i copy them into folder4.</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659417/" ]
74,647,208
<p>In Razor Pages, how can I redirect to a URL that contains slugs?</p> <p>For example, the code below takes me to the URL that contains rootValue:</p> <pre><code>return RedirectToPage(&quot;/EmailConfirmation&quot;, new {email = command.Email}); </code></pre> <p>The output is like this: https://localhost:5001/EmailConfirmation/example@gmail.com</p> <p>But how can I use Razor Pages commands to go to the following URL that contains slugs? https://localhost:5001/EmailConfirmation?email=example@gmail.com</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648138/" ]
74,647,215
<p>I have been using the Python Jenkins APIs to manager my Jenkins jobs. It has worked for a long time, but it stopped suddenly working. This is the code excerpt:</p> <pre><code>import jenkins server = jenkins.Jenkins('https://jenkins.company.com', username='xxxx', password='password') server._session.verify = False print(server.jobs_count()) </code></pre> <p>The traceback:</p> <blockquote> <p>File &quot;&quot;, line 1, in server.jobs_count()</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 1160, in jobs_count return len(self.get_all_jobs())</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 1020, in get_all_jobs jobs = [(0, [], self.get_info(query=jobs_query)['jobs'])]</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 769, in get_info requests.Request('GET', self._build_url(url))</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 557, in jenkins_open return self.jenkins_request(req, add_crumb, resolve_auth).text</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 573, in jenkins_request self.maybe_add_crumb(req)</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 371, in maybe_add_crumb 'GET', self._build_url(CRUMB_URL)), add_crumb=False)</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 557, in jenkins_open return self.jenkins_request(req, add_crumb, resolve_auth).text</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 576, in jenkins_request self._request(req))</p> <p>File &quot;E:\anaconda3\Lib\site-packages\jenkins_<em>init</em>_.py&quot;, line 550, in _request return self._session.send(r, **_settings)</p> <p>File &quot;E:\anaconda3\Lib\site-packages\requests\sessions.py&quot;, line 622, in send r = adapter.send(request, **kwargs)</p> <p>File &quot;E:\anaconda3\Lib\site-packages\requests\adapters.py&quot;, line 507, in send raise ProxyError(e, request=request)</p> <p>ProxyError: HTTPSConnectionPool(host='jenkins.company.com', port=443): Max retries exceeded with url: /job/scp/job/sm/job/9218/job/4198/job/SIT/crumbIssuer/api/json (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))</p> </blockquote> <p>Note that there isn't any proxy on the Jenkins server, and I can use the user/password logon to the Jenkins server without any issues.</p> <p>I have the crum id and API token, but I haven't found anything that is indicating how to add the crum into the Python-Jenkins API.</p>
[ { "answer_id": 74647077, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "if ( x < 1 << k - 1 ) { /*...*/ }\n k - 1 1 << k - 1 int" }, { "answer_id": 74647137, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "int x;\nint k;\n if ( x < pow(2,k-1) ) { ... }\n pow 1<<(k-1) 2 ^ 3 == 1 << 3 == 8\n2 ^ 5 == 1 << 5 == 32\n ( x < 1<<(k-1) ); // Result will either be 1 or 0\n ?: <" }, { "answer_id": 74662023, "author": "Ruud Helderman", "author_id": 2485966, "author_profile": "https://Stackoverflow.com/users/2485966", "pm_score": 0, "selected": false, "text": "!(x >> k-1)\n < (x & ~0xFF) == 0\n (x >> k-1) == 0\n !(x >> k-1)\n - !(x << 1 >> k)\n ! (~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n int int INT_MIN (x & INT_MIN) | ~((x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n (x >> 31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> k) & 1\n k (k & ~k>>31) (k < 0 ? 0 : k) (x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n int (((k>>5 | k>>6 | k>>7 | ... | k>>30) & ~k>>31) | x>>31 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>31) >> (k & ~k>>31)) & 1\n k>>5 k>>6 (((k>>6 | k>>7 | k>>8 | ... | k>>62) & ~k>>63) | x>>63 | ~(x<<1 | x | x>>1 | x>>2 | x>>3 | ... | x>>63) >> (k & ~k>>63)) & 1\n ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31))\n #include <stdio.h>\n#include <limits.h>\n\nstatic int purely_bitwise(int x, int k)\n{\n return (\n ((\n k>>5 | k>>6 | k>>7 | k>>8 | k>>9 |\n k>>10 | k>>11 | k>>12 | k>>13 | k>>14 | k>>15 | k>>16 | k>>17 | k>>18 | k>>19 |\n k>>20 | k>>21 | k>>22 | k>>23 | k>>24 | k>>25 | k>>26 | k>>27 | k>>28 | k>>29 |\n k>>30\n ) & ~k>>31) |\n x>>31 |\n ~(\n x<<1 | x | x>>1 | x>>2 | x>>3 | x>>4 | x>>5 | x>>6 | x>>7 | x>>8 | x>>9 |\n x>>10 | x>>11 | x>>12 | x>>13 | x>>14 | x>>15 | x>>16 | x>>17 | x>>18 | x>>19 |\n x>>20 | x>>21 | x>>22 | x>>23 | x>>24 | x>>25 | x>>26 | x>>27 | x>>28 | x>>29 |\n x>>30 | x>>31\n ) >> (k & ~k>>31)\n ) & 1;\n}\n\nstatic int bitwise_and_logical(int x, int k)\n{\n return ((k & ~31) && ~k>>31) || (x >> 31) || !(x << 1 >> (k & ~k>>31));\n}\n\nstatic int comparison(int x, int k)\n{\n return k >= 32 || x < (k < 1 ? 1 : 1 << (k-1));\n}\n\nstatic int values[] = {\n INT_MIN, INT_MIN+1, INT_MIN/2-1, INT_MIN/2, INT_MIN/2+1, -99, -9, -3, -2, -1,\n 0, 1, 2, 3, 9, 99, INT_MAX/2-1, INT_MAX/2, INT_MAX/2+1, INT_MAX-1, INT_MAX\n};\n#define LEN_VALUES (sizeof values / sizeof *values)\n\nint main()\n{\n for (int ik = 0; ik < LEN_VALUES; ik++)\n {\n for (int ix = 0; ix < LEN_VALUES; ix++)\n {\n int x = values[ix];\n int k = values[ik];\n int actual1 = purely_bitwise(x, k);\n int actual2 = bitwise_and_logical(x, k);\n int expected = comparison(x, k);\n if (actual1 != expected || actual2 != expected)\n {\n printf(\"x = %11d, k = %11d: expected = %d, actual = %d, %d\\n\",\n x, k, expected, actual1, actual2);\n }\n }\n }\n return 0;\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4483819/" ]
74,647,222
<p>I have two tables A and B, Table A have 3 cols and table B have 2 cols.</p> <p>Table A data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>id</th> <th>city</th> </tr> </thead> <tbody> <tr> <td>xyz</td> <td>1</td> <td>ab</td> </tr> <tr> <td>xyz2</td> <td>2</td> <td>ab1</td> </tr> <tr> <td>xyz3</td> <td>3</td> <td>ab2</td> </tr> </tbody> </table> </div> <p>Table B data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>id</th> </tr> </thead> <tbody> <tr> <td>xyz3</td> <td>3</td> </tr> <tr> <td>abc2</td> <td>4</td> </tr> </tbody> </table> </div> <p>Output I want:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>id</th> <th>city</th> <th>match</th> </tr> </thead> <tbody> <tr> <td>xyz</td> <td>1</td> <td>ab</td> <td>no</td> </tr> <tr> <td>xyz2</td> <td>2</td> <td>ab1</td> <td>no</td> </tr> <tr> <td>xyz3</td> <td>3</td> <td>ab2</td> <td>yes</td> </tr> <tr> <td>abc2</td> <td>4</td> <td>NULL</td> <td>no</td> </tr> </tbody> </table> </div> <p>I have tried this but it is giving op in different column:</p> <pre><code>select * from TableA a full outer join TableB b on a.id= b.id </code></pre> <p>Output I'm getting</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>id</th> <th>city</th> <th>name</th> <th>id</th> </tr> </thead> <tbody> <tr> <td>xyz</td> <td>1</td> <td>ab</td> <td>null</td> <td>null</td> </tr> <tr> <td>xyz2</td> <td>2</td> <td>ab1</td> <td>null</td> <td>null</td> </tr> <tr> <td>xyz3</td> <td>3</td> <td>ab2</td> <td>xyz3</td> <td>3</td> </tr> <tr> <td>Null</td> <td>null</td> <td>null</td> <td>abc2</td> <td>4</td> </tr> </tbody> </table> </div> <p>Output I want:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>id</th> <th>city</th> <th>match</th> </tr> </thead> <tbody> <tr> <td>xyz</td> <td>1</td> <td>ab</td> <td>no</td> </tr> <tr> <td>xyz2</td> <td>2</td> <td>ab1</td> <td>no</td> </tr> <tr> <td>xyz3</td> <td>3</td> <td>ab2</td> <td>yes</td> </tr> <tr> <td>abc2</td> <td>4</td> <td>NULL</td> <td>no</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74647599, "author": "Cetin Basoz", "author_id": 894977, "author_profile": "https://Stackoverflow.com/users/894977", "pm_score": 0, "selected": false, "text": "select * from (\nselect a.name, a.id, a.city, \n case when b.id is not null then 'Yes' else 'No' end as [Match]\nfrom tableA a\n left join tableB b on b.name = a.name and b.id = a. id\nunion \nselect b.name, b.id, a.city,\n case when a.id is not null then 'Yes' else 'No' end as [Match]\nfrom tableB b left join tableA a on b.name = a.name and b.id = a. id) tmp\n order by id ;\n" }, { "answer_id": 74647853, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 3, "selected": true, "text": "with c as (\n select name, id, city\n from a union all\n select name, id, null\n from b\n)\nselect name, id, Max(city) City,\n case when Count(*)> 1 then 'yes' else 'no' end Match\nfrom c\ngroup by name, id;\n" }, { "answer_id": 74648231, "author": "GRIV", "author_id": 3092847, "author_profile": "https://Stackoverflow.com/users/3092847", "pm_score": 1, "selected": false, "text": "UNION TableA TableB CASE id TableA TableB match NOT EXISTS TableA TableB WHERE TableB SELECT *, \n CASE WHEN id IN (SELECT DISTINCT id FROM TableB) THEN 'yes' ELSE 'no' END AS match\nFROM TableA a\n UNION\nSELECT *, NULL AS city, 'no' AS match\nFROM TableB b \n WHERE NOT EXISTS (SELECT 1 FROM TableA a2 WHERE a2.id = b.id)\nORDER BY id ASC\n | name | id | city | match |\n|------|----|------|--------|\n| xyz | 1 | ab | no |\n| xyz2 | 2 | ab1 | no |\n| xyz3 | 3 | ab2 | yes |\n| abc2 | 4 | null | no |\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12694274/" ]
74,647,277
<p>I have a function that runs a <code>fetch()</code> and at the very end of the fetch call it logs to the console.</p> <p>I want to <em>conditionally</em> add a second fetch function before the end of the first. It also logs to the console.</p> <p>I'm having trouble working out how to ensure the first log waits for the second fetch to complete and log its data before actually logging (whether or not it actually needs to run). I've been able to do this with several <code>else</code> statements, but I'd like to avoid the repetition.</p> <p>Codepen @ <a href="https://codepen.io/cfxd/pen/bGKmRZj" rel="nofollow noreferrer">https://codepen.io/cfxd/pen/bGKmRZj</a></p> <pre class="lang-js prettyprint-override"><code>function alwaysRuns() { fetch('https://api.spacexdata.com/v4/launches/latest') .then(result =&gt; result.json()) .then(resultJson =&gt; { const rocketId = resultJson.rocket; const rocketName = resultJson.name; if(rocketName.includes('Crew')) { fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`) .then(rocketResponse =&gt; rocketResponse.json()) .then(rocketJson =&gt; { console.log('This fetch might not happen, depending on the conditional') }); } console.log('this should always log last whether the conditional causes the second fetch to run or not!'); }); } alwaysRuns(); </code></pre>
[ { "answer_id": 74647287, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "await function alwaysRuns() {\n fetch('https://api.spacexdata.com/v4/launches/latest')\n .then(result => result.json())\n .then(async resultJson => {\n const rocketId = resultJson.rocket;\n const rocketName = resultJson.name;\n if(rocketName.includes('Crew')) {\n await fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`)\n .then(rocketResponse => rocketResponse.json())\n .then(rocketJson => {\n console.log('This fetch might not happen, depending on the conditional')\n });\n }\n console.log('this should always log last whether the conditional causes the second fetch to run or not!');\n });\n}\nalwaysRuns();\n function alwaysRuns() {\n fetch('https://api.spacexdata.com/v4/launches/latest')\n .then(result => result.json())\n .then(resultJson => {\n const rocketId = resultJson.rocket;\n const rocketName = resultJson.name;\n if(rocketName.includes('Crew')) {\n return fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`)\n .then(rocketResponse => rocketResponse.json())\n .then(rocketJson => {\n console.log('This fetch might not happen, depending on the conditional')\n });\n }\n }).then(() => {\n console.log('this should always log last whether the conditional causes the second fetch to run or not!');\n });\n}\nalwaysRuns();\n" }, { "answer_id": 74647332, "author": "Guido Carugati", "author_id": 13290792, "author_profile": "https://Stackoverflow.com/users/13290792", "pm_score": 2, "selected": false, "text": "async function alwaysRuns() {\n // Make the function asynchronous so we can use `await`\n const result = await fetch('https://api.spacexdata.com/v4/launches/latest');\n const resultJson = await result.json();\n const rocketId = resultJson.rocket;\n const rocketName = resultJson.name;\n\n if(rocketName.includes('Crew')) {\n const rocketResponse = await fetch(`https://api.spacexdata.com/v4/rockets/${rocketId}`);\n const rocketJson = await rocketResponse.json();\n console.log('This fetch might not happen, depending on the conditional')\n }\n\n console.log('this should always log last whether the conditional causes the second fetch to run or not!');\n}\n\nalwaysRuns();\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231001/" ]
74,647,310
<p>I have a set of <code>x</code> and <code>y</code> data and I want to use exponential regression to find the line that best fits those set of points. i.e.:</p> <pre><code>y = P1 + P2 exp(-P0 x) </code></pre> <p>I want to calculate the values of <code>P0</code>, <code>P1</code> and <code>P2</code>.</p> <p>I use a software &quot;Igor Pro&quot; that calculates the values for me, but want a Python implementation. I used the <code>curve_fit</code> function, but the values that I get are nowhere near the ones calculated by Igor software. Here is the sets of data that I have:</p> <p>Set1:</p> <pre class="lang-py prettyprint-override"><code>x = [ 1.06, 1.06, 1.06, 1.06, 1.06, 1.06, 0.91, 0.91, 0.91 ] y = [ 476, 475, 476.5, 475.25, 480, 469.5, 549.25, 548.5, 553.5 ] </code></pre> <p>Values calculated by Igor:</p> <pre class="lang-py prettyprint-override"><code>P1=376.91, P2=5393.9, P0=3.7776 </code></pre> <p>Values calculated by <code>curve_fit</code>:</p> <pre class="lang-py prettyprint-override"><code>P1=702.45, P2=-13.33. P0=-2.6744 </code></pre> <p>Set2:</p> <pre class="lang-py prettyprint-override"><code>x = [ 1.36, 1.44, 1.41, 1.745, 2.25, 1.42, 1.45, 1.5, 1.58] y = [ 648, 618, 636, 485, 384, 639, 630, 583, 529] </code></pre> <p>Values calculated by Igor:</p> <pre class="lang-py prettyprint-override"><code>P1=321, P2=4848, P0=-1.94 </code></pre> <p>Values calculated by curve_fit:</p> <pre><code>No optimal values found </code></pre> <p>I use <code>curve_fit</code> as follow:</p> <pre class="lang-py prettyprint-override"><code>from scipy.optimize import curve_fit popt, pcov = curve_fit(lambda t, a, b, c: a * np.exp(-b * t) + c, x, y) </code></pre> <p>where:</p> <pre class="lang-py prettyprint-override"><code>P1=c, P2=a and P0=b </code></pre>
[ { "answer_id": 74647526, "author": "Miquel Rigo", "author_id": 7480676, "author_profile": "https://Stackoverflow.com/users/7480676", "pm_score": -1, "selected": false, "text": "import numpy as np\nfrom scipy.optimize import minimize\n\n# Define the function that we want to fit to the data\ndef func(x, P1, P2, P0):\n return P1 + P2 * np.exp(-P0 * x)\n\n# Define a function that takes the parameters of the function as arguments\n# and returns the sum of the squared differences between the predicted\n# and observed values of y\ndef objective(params):\n P1, P2, P0 = params\n y_pred = func(x, P1, P2, P0)\n return np.sum((y - y_pred) ** 2)\n\n# Define the initial values for the parameters\nparams_init = [376.91, 5393.9, 3.7776]\n\n# Use the minimize function to find the values of the parameters that\n# minimize the objective function\nresult = minimize(objective, params_init)\n\n# Print the optimized values of the parameters\nprint(result.x)\n" }, { "answer_id": 74650930, "author": "M Newville", "author_id": 5179748, "author_profile": "https://Stackoverflow.com/users/5179748", "pm_score": 0, "selected": false, "text": "curve_fit import numpy as np\nfrom lmfit import Model\n \nx = [ 1.06, 1.06, 1.06, 1.06, 1.06, 1.06, 0.91, 0.91, 0.91 ]\ny = [ 476, 475, 476.5, 475.25, 480, 469.5, 549.25, 548.5, 553.5 ]\n# x = [ 1.36, 1.44, 1.41, 1.745, 2.25, 1.42, 1.45, 1.5, 1.58]\n# y = [ 648, 618, 636, 485, 384, 639, 630, 583, 529] \n\n# Define the function that we want to fit to the data\ndef func(x, offset, scale, decay):\n return offset + scale * np.exp(-decay* x)\n \nmodel = Model(func)\nparams = model.make_params(offset=375, scale=5000, decay=4)\n \nresult = model.fit(y, params, x=x)\n \nprint(result.fit_report())\n [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 49\n # data points = 9\n # variables = 3\n chi-square = 72.2604167\n reduced chi-square = 12.0434028\n Akaike info crit = 24.7474672\n Bayesian info crit = 25.3391410\n R-squared = 0.99362489\n[[Variables]]\n offset: 413.168769 +/- 17348030.9 (4198775.95%) (init = 375)\n scale: 16689.6793 +/- 1.3337e+10 (79909638.11%) (init = 5000)\n decay: 5.27555726 +/- 1016721.11 (19272297.84%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 1.000\n C(offset, decay) = 1.000\n C(offset, scale) = 1.000\n x [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 82\n # data points = 9\n # variables = 3\n chi-square = 1118.19957\n reduced chi-square = 186.366596\n Akaike info crit = 49.4002551\n Bayesian info crit = 49.9919289\n R-squared = 0.98272310\n[[Variables]]\n offset: 320.876843 +/- 42.0154403 (13.09%) (init = 375)\n scale: 4797.14487 +/- 2667.40083 (55.60%) (init = 5000)\n decay: 1.93560164 +/- 0.47764470 (24.68%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 0.995\n C(offset, decay) = 0.940\n C(offset, scale) = 0.904\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20005411/" ]
74,647,349
<p>The workflow Supabase uses for version controlling the (PostgreSQL) schema is for the developer to manually run a tool that diffs the schema after every change and saves the resulting migration to a file.</p> <p>I found it surprising to build the database schema using imperative commands (CREATE TABLE, ENABLE ROW LEVEL SECURITY, etc.) and then use a diffing tool to create imperative migrations.</p> <p>It seems like a better approach would be to describe the schema using some declarative markup language, like JSON, YAML, XML, etc., and then migrations could just be the Git diffs between versions of the schema declaration.</p> <p>I found the confusing assertion from many people that SQL <em>is</em> declarative, when from my perspective (as a newbie) it appears to consist of commands that must be executed in order. I found a couple of projects that claimed to be working on declarative database schema instead of migrations (skeema.io, schemahero.io), but no sign of widespread adoption.</p> <p>Why this is the case? Is it an artifact of history, or are there some key challenges with a declarative approach to schema management that I am missing?</p> <p>I found <a href="https://www.reddit.com/r/devops/comments/br4qxw/comment/eobfj48/?utm_source=share&amp;utm_medium=web2x&amp;context=3" rel="nofollow noreferrer">this answer</a> on Reddit:</p> <blockquote> <p>90% of the effort in updating database schemas is updating the data. Thich can not be done with desired state. For example, introduce a city reference table, you just can't do this with schema diff, you need to make business logic decisions while you migrate your data over. So use one of the many existing migration systems and forget about this idea.</p> </blockquote> <p>So is the answer that you need to issue imperative commands on a case-by-case basis to deal with migrating the data, and a declarative engine would be unable to do that?</p>
[ { "answer_id": 74647526, "author": "Miquel Rigo", "author_id": 7480676, "author_profile": "https://Stackoverflow.com/users/7480676", "pm_score": -1, "selected": false, "text": "import numpy as np\nfrom scipy.optimize import minimize\n\n# Define the function that we want to fit to the data\ndef func(x, P1, P2, P0):\n return P1 + P2 * np.exp(-P0 * x)\n\n# Define a function that takes the parameters of the function as arguments\n# and returns the sum of the squared differences between the predicted\n# and observed values of y\ndef objective(params):\n P1, P2, P0 = params\n y_pred = func(x, P1, P2, P0)\n return np.sum((y - y_pred) ** 2)\n\n# Define the initial values for the parameters\nparams_init = [376.91, 5393.9, 3.7776]\n\n# Use the minimize function to find the values of the parameters that\n# minimize the objective function\nresult = minimize(objective, params_init)\n\n# Print the optimized values of the parameters\nprint(result.x)\n" }, { "answer_id": 74650930, "author": "M Newville", "author_id": 5179748, "author_profile": "https://Stackoverflow.com/users/5179748", "pm_score": 0, "selected": false, "text": "curve_fit import numpy as np\nfrom lmfit import Model\n \nx = [ 1.06, 1.06, 1.06, 1.06, 1.06, 1.06, 0.91, 0.91, 0.91 ]\ny = [ 476, 475, 476.5, 475.25, 480, 469.5, 549.25, 548.5, 553.5 ]\n# x = [ 1.36, 1.44, 1.41, 1.745, 2.25, 1.42, 1.45, 1.5, 1.58]\n# y = [ 648, 618, 636, 485, 384, 639, 630, 583, 529] \n\n# Define the function that we want to fit to the data\ndef func(x, offset, scale, decay):\n return offset + scale * np.exp(-decay* x)\n \nmodel = Model(func)\nparams = model.make_params(offset=375, scale=5000, decay=4)\n \nresult = model.fit(y, params, x=x)\n \nprint(result.fit_report())\n [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 49\n # data points = 9\n # variables = 3\n chi-square = 72.2604167\n reduced chi-square = 12.0434028\n Akaike info crit = 24.7474672\n Bayesian info crit = 25.3391410\n R-squared = 0.99362489\n[[Variables]]\n offset: 413.168769 +/- 17348030.9 (4198775.95%) (init = 375)\n scale: 16689.6793 +/- 1.3337e+10 (79909638.11%) (init = 5000)\n decay: 5.27555726 +/- 1016721.11 (19272297.84%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 1.000\n C(offset, decay) = 1.000\n C(offset, scale) = 1.000\n x [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 82\n # data points = 9\n # variables = 3\n chi-square = 1118.19957\n reduced chi-square = 186.366596\n Akaike info crit = 49.4002551\n Bayesian info crit = 49.9919289\n R-squared = 0.98272310\n[[Variables]]\n offset: 320.876843 +/- 42.0154403 (13.09%) (init = 375)\n scale: 4797.14487 +/- 2667.40083 (55.60%) (init = 5000)\n decay: 1.93560164 +/- 0.47764470 (24.68%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 0.995\n C(offset, decay) = 0.940\n C(offset, scale) = 0.904\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7541458/" ]
74,647,356
<p>I'm trying to scrape an apartment website and it's not looping. I get different apartments but the rest of the information is the same. Yesterday it was pulling a different address.</p> <pre><code>url = &quot;https://www.apartments.com/atlanta-ga/?bb=lnwszyjy-H4lu8uqH&quot; header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'} page = requests.get(url, headers=header) soup = BeautifulSoup(page.content, 'html.parser') lists = soup.find_all('section', class_=&quot;placard-content&quot;) properties = soup.find_all('li', class_=&quot;mortar-wrapper&quot;) addresses = soup.find_all('a', class_=&quot;property-link&quot;) for list in lists: price = list.find('p', class_=&quot;property-pricing&quot;).text beds = list.find('p', class_=&quot;property-beds&quot;).text for address in addresses: location = address.find('div', class_=&quot;property-address js-url&quot;).text for property in properties: name = property.find('span', class_=&quot;js-placardTitle title&quot;).text info = [name,location,beds,price] print(info)``` Here is the output I'm getting </code></pre> <p>['Broadstone Pullman', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['1660 Peachtree Midtown', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['Mira at Midtown Union', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['Alexan Summerhill', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['1824 Defoor', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['3005 Buckhead', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['AMLI Westside', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['Novel O4W', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['The Cliftwood', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825'] ['Ellington Midtown', '105 Rogers St NE, Atlanta, GA 30317', 'Studio - 2 Beds', '$1,630 - 2,825']```</p>
[ { "answer_id": 74647526, "author": "Miquel Rigo", "author_id": 7480676, "author_profile": "https://Stackoverflow.com/users/7480676", "pm_score": -1, "selected": false, "text": "import numpy as np\nfrom scipy.optimize import minimize\n\n# Define the function that we want to fit to the data\ndef func(x, P1, P2, P0):\n return P1 + P2 * np.exp(-P0 * x)\n\n# Define a function that takes the parameters of the function as arguments\n# and returns the sum of the squared differences between the predicted\n# and observed values of y\ndef objective(params):\n P1, P2, P0 = params\n y_pred = func(x, P1, P2, P0)\n return np.sum((y - y_pred) ** 2)\n\n# Define the initial values for the parameters\nparams_init = [376.91, 5393.9, 3.7776]\n\n# Use the minimize function to find the values of the parameters that\n# minimize the objective function\nresult = minimize(objective, params_init)\n\n# Print the optimized values of the parameters\nprint(result.x)\n" }, { "answer_id": 74650930, "author": "M Newville", "author_id": 5179748, "author_profile": "https://Stackoverflow.com/users/5179748", "pm_score": 0, "selected": false, "text": "curve_fit import numpy as np\nfrom lmfit import Model\n \nx = [ 1.06, 1.06, 1.06, 1.06, 1.06, 1.06, 0.91, 0.91, 0.91 ]\ny = [ 476, 475, 476.5, 475.25, 480, 469.5, 549.25, 548.5, 553.5 ]\n# x = [ 1.36, 1.44, 1.41, 1.745, 2.25, 1.42, 1.45, 1.5, 1.58]\n# y = [ 648, 618, 636, 485, 384, 639, 630, 583, 529] \n\n# Define the function that we want to fit to the data\ndef func(x, offset, scale, decay):\n return offset + scale * np.exp(-decay* x)\n \nmodel = Model(func)\nparams = model.make_params(offset=375, scale=5000, decay=4)\n \nresult = model.fit(y, params, x=x)\n \nprint(result.fit_report())\n [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 49\n # data points = 9\n # variables = 3\n chi-square = 72.2604167\n reduced chi-square = 12.0434028\n Akaike info crit = 24.7474672\n Bayesian info crit = 25.3391410\n R-squared = 0.99362489\n[[Variables]]\n offset: 413.168769 +/- 17348030.9 (4198775.95%) (init = 375)\n scale: 16689.6793 +/- 1.3337e+10 (79909638.11%) (init = 5000)\n decay: 5.27555726 +/- 1016721.11 (19272297.84%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 1.000\n C(offset, decay) = 1.000\n C(offset, scale) = 1.000\n x [[Model]]\n Model(func)\n[[Fit Statistics]]\n # fitting method = leastsq\n # function evals = 82\n # data points = 9\n # variables = 3\n chi-square = 1118.19957\n reduced chi-square = 186.366596\n Akaike info crit = 49.4002551\n Bayesian info crit = 49.9919289\n R-squared = 0.98272310\n[[Variables]]\n offset: 320.876843 +/- 42.0154403 (13.09%) (init = 375)\n scale: 4797.14487 +/- 2667.40083 (55.60%) (init = 5000)\n decay: 1.93560164 +/- 0.47764470 (24.68%) (init = 4)\n[[Correlations]] (unreported correlations are < 0.100)\n C(scale, decay) = 0.995\n C(offset, decay) = 0.940\n C(offset, scale) = 0.904\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15564501/" ]
74,647,377
<p>I am trying to write a calculator using functions for each operation and switch case in c language but output is as follows: for example when i enter 5 and 6, and choose addition it prints sss5.000000 + 6.000000 = 11.000000 how can i remove the sss before 5.000000 and what causes this problem? thanks for helping.</p> <pre><code> #include &lt;stdio.h&gt; #include &lt;math.h&gt; float addTwoNumbers(float num1, float num2); float subtTwoNumbers(float num1, float num2); float divideTwoNumbers(float num1, float num2); float multTwoNumbers(float num1, float num2); float powerTwoNumbers(float num1, float num2); int main() { float num1, num2,add,subt,div,mult,pow; int choice; printf(&quot;choose one operation:\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\n&quot;); scanf(&quot;%d&quot; ,&amp;choice); printf(&quot;Enter two numbers: &quot;); scanf(&quot;%f %f&quot; ,&amp;num1,&amp;num2); add=addTwoNumbers(num1, num2); subt=subtTwoNumbers(num1, num2); div=divideTwoNumbers(num1, num2); mult=multTwoNumbers(num1, num2); pow=powerTwoNumbers(num1, num2); switch (choice) { case 1: printf(&quot;%f + %f = %f&quot; ,num1,num2); break; case 2: printf(&quot;%f - %f = %f&quot; ,num1,num2); break; case 3: printf(&quot;%f / %f = %f&quot; ,num1,num2); break; case 4: printf(&quot;%f * %f = %f&quot; ,num1,num2); case 5: printf(&quot;%f ? %f = %f&quot; ,num1,num2); break; default: printf(&quot;Error!&quot;); } return 0; } float addTwoNumbers(float num1, float num2) { return num1+num2; } float subtTwoNumbers(float num1, float num2) { float result2; result2 = num1-num2; return result2; } float divideTwoNumbers(float num1, float num2) { printf(&quot;s&quot;); } float multTwoNumbers(float num1, float num2) { printf(&quot;s&quot;); } float powerTwoNumbers(float num1, float num2) { printf(&quot;s&quot;); } </code></pre>
[ { "answer_id": 74647541, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\nfloat addTwoNumbers (float num1, float num2) { return num1+num2; }\nfloat subtTwoNumbers (float num1, float num2) { return num1-num2; }\nfloat divideTwoNumbers(float num1, float num2) { return num1/num2; }\nfloat multTwoNumbers (float num1, float num2) { return num1*num2; }\nfloat powerTwoNumbers (float num1, float num2) { return powf(num1,num2); }\n\nfloat(*operation_map[])(float,float) =\n{\n addTwoNumbers,\n subtTwoNumbers,\n divideTwoNumbers,\n multTwoNumbers,\n powerTwoNumbers\n};\n\nchar choice_map[]= { '+', '-', '/', '*', '^' };\n\nint main() {\n\n int choice;\n printf(\"choose one operation:\\n\"\n \" 1.addition\\n\"\n \" 2.substraction\\n\"\n \" 3.division\\n\"\n \" 4.multiplication\\n\"\n \" 5.power\\n\");\n scanf(\"%d\" ,&choice);\n \n printf(\"Enter two numbers: \");\n float num1, num2;\n scanf(\"%f %f\" ,&num1, &num2);\n \n float result = operation_map[choice-1](num1, num2);\n printf(\"%.2f %c %.2f = %.2f\", num1, choice_map[choice-1], num2, result);\n\n return 0;\n}\n choose one operation: 1\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\nEnter two numbers: 3.14 2.71\n\n3.14 + 2.71 = 5.85\n" }, { "answer_id": 74647556, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": true, "text": "scanf() num2 &num2 scanf() printf() main() #include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat addTwoNumbers(float num1, float num2) {\n return num1 + num2;\n}\n\nfloat subtTwoNumbers(float num1, float num2) {\n return num1 - num2;\n}\n\nfloat divideTwoNumbers(float num1, float num2) {\n if(num2 == 0) {\n printf(\"divide by 0!\\n\");\n exit(1);\n }\n return num1 / num2;\n}\n\nfloat multTwoNumbers(float num1, float num2) {\n return num1 * num2;\n}\n\nfloat powerTwoNumbers(float num1, float num2) {\n return powf(num1, num2);\n}\n\nint main() {\n printf(\"choose one operation:\\n 1.addition\\n 2.substraction\\n 3.division\\n 4.multiplication\\n 5.power\\n\");\n int choice;\n if(scanf(\"%d\", &choice) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"Enter two numbers: \");\n float num1, num2;\n if(scanf(\"%f %f\", &num1, &num2) != 2) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n switch (choice) {\n case 1:\n printf(\"%f + %f = %f\\n\" ,\n num1,\n num2,\n addTwoNumbers(num1, num2)\n );\n break;\n case 2:\n printf(\"%f - %f = %f\\n\" ,\n num1,\n num2,\n subtTwoNumbers(num1, num2)\n );\n break;\n case 3:\n printf(\"%f / %f = %f\\n\",\n num1,\n num2,\n divideTwoNumbers(num1, num2)\n );\n break;\n case 4:\n printf(\"%f * %f = %f\\n\" ,\n num1,\n num2,\n multTwoNumbers(num1, num2)\n );\n break;\n case 5:\n printf(\"%f^%f = %f\\n\" ,\n num1,\n num2,\n powerTwoNumbers(num1, num2)\n );\n break;\n default:\n printf(\"Error!\");\n }\n}\n choose one operation:\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\n1 \nEnter two numbers: 1.2 2.3\n1.200000 + 2.300000 = 3.500000\n powf() print() OP() OP_FUNC() break #include <stdio.h>\n#include <math.h>\n\nvoid print(float num1, const char *op, float num2, float result) {\n printf(\"%f %s %f = %f\\n\", num1, op, num2, result);\n}\n\nint main() {\n printf(\"choose one operation:\\n 1.addition\\n 2.substraction\\n 3.division\\n 4.multiplication\\n 5.power\\n\");\n int choice;\n if(scanf(\"%d\" ,&choice) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"Enter two numbers: \");\n float num1, num2;\n if(scanf(\"%f %f\" ,&num1, &num2) != 2) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n#define OP(O) print(num1, #O, num2, num1 O num2);\\\n break\n\n#define OP_FUNC(O, F) print(num1, #O, num2, F(num1, num2));\\\n break\n\n switch (choice) {\n case 1: OP(+);\n case 2: OP(-);\n case 3: if(num2 != 0) OP(/); else printf(\"divide by 0\\n\");\n case 4: OP(*);\n case 5: OP_FUNC(^, powf);\n default: printf(\"Error!\");\n }\n\n#undef OP\n#undef OP_FUNC\n\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20647521/" ]
74,647,409
<p>In my <code>nextjs</code>-app I have a Button component:</p> <pre><code>interface IButton { text: string theme: 'primary' | 'secondary' size: 'small' | 'medium' | 'large' onClick?: () =&gt; void } const Button = ({ theme, text, size, onClick }: IButton) =&gt; { return ( &lt;button onClick={onClick} className={cn(styles.btn, { [styles.primary]: theme === 'primary', [styles.secondary]: theme === 'secondary', [styles.medium]: size === 'small', [styles.small]: size === 'medium', [styles.large]: size === 'large', })} &gt; {text} &lt;/button&gt; ) } export default Button </code></pre> <p>And I use it like this:</p> <pre><code>&lt;Button text=&quot;Click me&quot; theme=&quot;primary&quot; size=&quot;large&quot; onClick={clickHandler} /&gt; </code></pre> <p>When I try to do <code>npm run build</code> I get the error:</p> <pre><code>Type 'string' is not assignable to type '&quot;primary&quot; | &quot;secondary&quot;'. </code></pre> <p>Can someone help me out?</p>
[ { "answer_id": 74647541, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\nfloat addTwoNumbers (float num1, float num2) { return num1+num2; }\nfloat subtTwoNumbers (float num1, float num2) { return num1-num2; }\nfloat divideTwoNumbers(float num1, float num2) { return num1/num2; }\nfloat multTwoNumbers (float num1, float num2) { return num1*num2; }\nfloat powerTwoNumbers (float num1, float num2) { return powf(num1,num2); }\n\nfloat(*operation_map[])(float,float) =\n{\n addTwoNumbers,\n subtTwoNumbers,\n divideTwoNumbers,\n multTwoNumbers,\n powerTwoNumbers\n};\n\nchar choice_map[]= { '+', '-', '/', '*', '^' };\n\nint main() {\n\n int choice;\n printf(\"choose one operation:\\n\"\n \" 1.addition\\n\"\n \" 2.substraction\\n\"\n \" 3.division\\n\"\n \" 4.multiplication\\n\"\n \" 5.power\\n\");\n scanf(\"%d\" ,&choice);\n \n printf(\"Enter two numbers: \");\n float num1, num2;\n scanf(\"%f %f\" ,&num1, &num2);\n \n float result = operation_map[choice-1](num1, num2);\n printf(\"%.2f %c %.2f = %.2f\", num1, choice_map[choice-1], num2, result);\n\n return 0;\n}\n choose one operation: 1\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\nEnter two numbers: 3.14 2.71\n\n3.14 + 2.71 = 5.85\n" }, { "answer_id": 74647556, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": true, "text": "scanf() num2 &num2 scanf() printf() main() #include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nfloat addTwoNumbers(float num1, float num2) {\n return num1 + num2;\n}\n\nfloat subtTwoNumbers(float num1, float num2) {\n return num1 - num2;\n}\n\nfloat divideTwoNumbers(float num1, float num2) {\n if(num2 == 0) {\n printf(\"divide by 0!\\n\");\n exit(1);\n }\n return num1 / num2;\n}\n\nfloat multTwoNumbers(float num1, float num2) {\n return num1 * num2;\n}\n\nfloat powerTwoNumbers(float num1, float num2) {\n return powf(num1, num2);\n}\n\nint main() {\n printf(\"choose one operation:\\n 1.addition\\n 2.substraction\\n 3.division\\n 4.multiplication\\n 5.power\\n\");\n int choice;\n if(scanf(\"%d\", &choice) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"Enter two numbers: \");\n float num1, num2;\n if(scanf(\"%f %f\", &num1, &num2) != 2) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n switch (choice) {\n case 1:\n printf(\"%f + %f = %f\\n\" ,\n num1,\n num2,\n addTwoNumbers(num1, num2)\n );\n break;\n case 2:\n printf(\"%f - %f = %f\\n\" ,\n num1,\n num2,\n subtTwoNumbers(num1, num2)\n );\n break;\n case 3:\n printf(\"%f / %f = %f\\n\",\n num1,\n num2,\n divideTwoNumbers(num1, num2)\n );\n break;\n case 4:\n printf(\"%f * %f = %f\\n\" ,\n num1,\n num2,\n multTwoNumbers(num1, num2)\n );\n break;\n case 5:\n printf(\"%f^%f = %f\\n\" ,\n num1,\n num2,\n powerTwoNumbers(num1, num2)\n );\n break;\n default:\n printf(\"Error!\");\n }\n}\n choose one operation:\n 1.addition\n 2.substraction\n 3.division\n 4.multiplication\n 5.power\n1 \nEnter two numbers: 1.2 2.3\n1.200000 + 2.300000 = 3.500000\n powf() print() OP() OP_FUNC() break #include <stdio.h>\n#include <math.h>\n\nvoid print(float num1, const char *op, float num2, float result) {\n printf(\"%f %s %f = %f\\n\", num1, op, num2, result);\n}\n\nint main() {\n printf(\"choose one operation:\\n 1.addition\\n 2.substraction\\n 3.division\\n 4.multiplication\\n 5.power\\n\");\n int choice;\n if(scanf(\"%d\" ,&choice) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"Enter two numbers: \");\n float num1, num2;\n if(scanf(\"%f %f\" ,&num1, &num2) != 2) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n#define OP(O) print(num1, #O, num2, num1 O num2);\\\n break\n\n#define OP_FUNC(O, F) print(num1, #O, num2, F(num1, num2));\\\n break\n\n switch (choice) {\n case 1: OP(+);\n case 2: OP(-);\n case 3: if(num2 != 0) OP(/); else printf(\"divide by 0\\n\");\n case 4: OP(*);\n case 5: OP_FUNC(^, powf);\n default: printf(\"Error!\");\n }\n\n#undef OP\n#undef OP_FUNC\n\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3955607/" ]
74,647,416
<p>How to receive all data from a connection in <code>socketserver</code> so that it the connection does not hang on the client side</p> <pre><code>class ConnectionHandler(BaseRequestHandler): def handle(self): data = b'' while 1: tmp = self.request.recv(1024) if not tmp: break data += tmp print (data.decode()) </code></pre> <p>on the client side I am using</p> <pre><code> char text[] = &quot;Hello world\n&quot;; SSL_write(ssl, text, sizeof(text)); char tmp[20]; int received = SSL_read (ssl, tmp, 20); printf(&quot;Server replied: [%s]\n&quot;, tmp); </code></pre> <p>but this causes the connection not to close and the client hangs, I am sure this is the case since replacing the while loop with <code>self.request.recv(1024)</code> receives the client message and outputs it but what if i don't know the message size of the client</p>
[ { "answer_id": 74647482, "author": "Miquel Rigo", "author_id": 7480676, "author_profile": "https://Stackoverflow.com/users/7480676", "pm_score": 2, "selected": false, "text": "class ConnectionHandler(BaseRequestHandler):\n\ndef handle(self):\n # Use the makefile method to get a file-like object for the connection\n file_like_obj = self.request.makefile('rb')\n # Read all data from the file-like object\n data = file_like_obj.read()\n print(data.decode())\n class ConnectionHandler(BaseRequestHandler):\n\ndef handle(self):\n # Use the SSL_makefile method to get a file-like object for the SSL connection\n file_like_obj = self.request.SSL_makefile('rb')\n # Read all data from the file-like object\n data = file_like_obj.read()\n print(data.decode())\n" }, { "answer_id": 74648197, "author": "loaded_dypper", "author_id": 17975829, "author_profile": "https://Stackoverflow.com/users/17975829", "pm_score": 0, "selected": false, "text": "self.request.recv()" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17975829/" ]
74,647,428
<p>I have the following scenario and am trying to understand the right way to implement it.</p> <p>I have Okta as my IDP. Amazon API gateway for managing my APIs and some lambdas which handle the API requests. Identity Pool is used to provide AWS credentials to the client accessing the APIs.</p> <p>When the client accesses the API, I need my lambda (which handles the request) to fetch the data from DynamoDB, and filter it based on a few attributes that are specific to the user that has logged in to the client. e.g. I need to retrieve accounts for a customer using the API, but the user only has access to certain accounts and so the lambda should filter the result.</p> <p>I am thinking of having some custom claims defined for each user in Okta. When the client authenticates with Okta, it receives a JWT token with these claims. And it fetches the AWS credentials from Identity Pool with this token, to access the API. The API would trigger the lambda. Here, I would want to retrieve the claims and use them for filtering the data.</p> <p>Any thoughts on how this can be achieved? Or is there a better way to address this?</p> <p>Thank you.</p>
[ { "answer_id": 74659651, "author": "Sampath Dilhan", "author_id": 3668866, "author_profile": "https://Stackoverflow.com/users/3668866", "pm_score": 1, "selected": false, "text": "context context" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1081150/" ]
74,647,441
<p>Im creating this website using laravel and there is an option to add new items to the sell when an item adds the admin can mark it as a new arrival, I want to count 10 days from the date added and when the 10 days passed, I want to item no longer listed as new arrival. How can I implement this</p>
[ { "answer_id": 74659651, "author": "Sampath Dilhan", "author_id": 3668866, "author_profile": "https://Stackoverflow.com/users/3668866", "pm_score": 1, "selected": false, "text": "context context" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20370427/" ]
74,647,475
<p>I would like to parse some text or any data from <a href="https://drive.google.com/drive/folders/1IqnZJaWxyWqwHuzByV3XQHRvNbCJW_g6?usp=sharing" rel="nofollow noreferrer">this pdf</a> with Python. Everything I have tried is not working.</p> <p>I have a tried a variety of approaches:</p> <pre><code># importing required modules import PyPDF2 # creating a pdf file object pdfFileObj = open('example.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) # printing number of pages in pdf file print(pdfReader.numPages) # creating a page object pageObj = pdfReader.getPage(0) # extracting text from page print(pageObj.extractText()) # closing the pdf file object pdfFileObj.close() </code></pre> <p><strong>I receive this:</strong> <em>If this message is not eventually replaced by the proper contents of the document, your PDF viewer may not be able to display this type of document. You can upgrade to the latest version of Adobe Reader for Windows®, Mac, or Linux® by visiting <a href="http://www.adobe.com/go/reader_download" rel="nofollow noreferrer">http://www.adobe.com/go/reader_download</a>. For more assistance with Adobe Reader visit <a href="http://www.adobe.com/go/acrreader" rel="nofollow noreferrer">http://www.adobe.com/go/acrreader</a>.<br /> Windows is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. Mac is a trademark of Apple Inc., registered in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.</em></p> <p>I have tried:</p> <pre><code>from pdfrw import PdfReader pdf = PdfReader(&quot;example.pdf&quot;) </code></pre> <p><strong>I receive this:</strong> [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (111, 0) [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (110, 0) [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (109, 0) [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (108, 0) [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (112, 0) [ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (113, 0)</p>
[ { "answer_id": 74659651, "author": "Sampath Dilhan", "author_id": 3668866, "author_profile": "https://Stackoverflow.com/users/3668866", "pm_score": 1, "selected": false, "text": "context context" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659719/" ]
74,647,479
<p>I want to determine on macOS which version of .NET runtimes I have installed. I'm using command <code>dotnet --list-runtimes</code> to print available versions.</p> <pre><code>Microsoft.AspNetCore.App 6.0.9 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.11 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 6.0.9 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.11 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] </code></pre> <p>Would love to create an array with above versions like <code>[&quot;6.0.9, &quot;6.0.11&quot;]</code> to be able to see if there's a version higher or equal than, for example, 6.0.11.</p> <p>I have a code that looks like this:</p> <pre><code>if [[ -f &quot;/usr/local/share/dotnet/dotnet&quot; ]] then IFS=' ' declare sdks=$(dotnet --list-runtimes) for runtime in &quot;${sdks}&quot; do echo $runtime declare split=(&quot;&quot;) read -a split &lt;&lt;&lt; $runtime echo ${split[1]} done IFS='' else echo &quot;ERROR: Unable do determine installet .NET SDK.&quot; fi </code></pre> <p>Unfortunately <code>echo ${split[1]}</code> prints only once 6.0.9.</p>
[ { "answer_id": 74647512, "author": "Christian Fritz", "author_id": 1087119, "author_profile": "https://Stackoverflow.com/users/1087119", "pm_score": 0, "selected": false, "text": "dotnet --list-runtimes | cut -d ' ' -f 2 | sort | uniq | xargs\n6.0.11 6.0.9\n > for version in $(dotnet --list-runtimes | cut -d ' ' -f 2 | sort | uniq | xargs); do echo $version; done\n6.0.11\n6.0.9\n" }, { "answer_id": 74647519, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 1, "selected": true, "text": "$ array=( $(dotnet --list-runtimes | awk '{a[$2]=\"\"}END{for (i in a) print i}') )\n$ printf '%s\\n' \"${array[@]}\"\n6.0.9\n6.0.11\n" }, { "answer_id": 74647567, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 1, "selected": false, "text": "dotnet --list-runtimes | awk '!seen[$2]++{print $2}'\n vers=()\nwhile read -r v; do\n vers+=(\"$v\")\ndone < <(dotnet --list-runtimes | awk '!seen[$2]++{print $2}')\n\n# check array content\ndeclare -p vers\n\ndeclare -a vers=([0]=\"6.0.9\" [1]=\"6.0.11\")\n awk '!seen[$2]++{print $2}' < <(...) readarray vers" }, { "answer_id": 74648490, "author": "Cole Tierney", "author_id": 2820422, "author_profile": "https://Stackoverflow.com/users/2820422", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env bash\n\ndeclare -a sdks\nwhile read -r runtime; do\n set $runtime\n sdks+=(\"$2\")\ndone < <(dotnet --list-runtimes)\n\necho \"${sdks[@]}\"\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/878395/" ]
74,647,494
<p>My main.dart screen calls SplashScreen and then SplashScreen calls BottomNavigationScreen. I am manually calling all the screens for <strong>_widgetOptions.elementAt(_selectedIndex)</strong> in widgetOptions.</p> <p>I want not to call all screens manually. Instead I want to call screens by using named routes defined in my main.dart file. How to pass named routes to my another class where I am defining my BottomNavigatioBar?</p> <p>How to add BottomNavigationBar in class other than main and call the named routes instead of manually calling classes?</p> <h1>main.dart</h1> <pre><code>import 'package:flutter/material.dart'; import 'package:form_data_api/screens/all_articles_screen.dart'; import 'package:form_data_api/screens/article_detail_screen.dart'; import 'package:form_data_api/screens/user_profile_screen.dart'; // import 'package:form_data_api/screens/all_children_screen.dart'; // import 'package:form_data_api/screens/child_detail_screen.dart'; // import 'package:form_data_api/screens/user_profile_screen.dart'; import 'screens/all_children_screen.dart'; import 'screens/bottom_navigation_screen.dart'; import 'screens/child_detail_screen.dart'; import 'splash_screen.dart'; void main() =&gt; runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( initialRoute: '/splashScreen', routes: { // When navigating to the &quot;/&quot; route, build the FirstScreen widget. '/splashScreen': (_) =&gt; const SplashScreen(), // When navigating to the &quot;/second&quot; route, build the SecondScreen widget. '/bottomNavigationScreen': (_) =&gt; const BottomNavigationScreen(), '/userProfileScreen': (_) =&gt; const UserProfileScreen(), '/allChildrenScreen': (_) =&gt; const AllChildrenScreen(), '/childDetailScreen': (context) =&gt; const ChildDetailScreen(childName: '', childId: '',), '/allArticleScreen': (context) =&gt; const AllArticleScreen(), '/articleDetailScreen': (context) =&gt; const ArticleDetailScreen(articleName: '', articleId: '',), }, // home: SplashScreen(), ); } } </code></pre> <h1>bottom_navigation_screen.dart</h1> <pre><code>import 'package:flutter/material.dart'; import 'all_articles_screen.dart'; import 'all_children_screen.dart'; import 'user_profile_screen.dart'; class BottomNavigationScreen extends StatefulWidget { const BottomNavigationScreen({super.key}); @override State&lt;BottomNavigationScreen&gt; createState() =&gt; _BottomNavigationScreenState(); } class _BottomNavigationScreenState extends State&lt;BottomNavigationScreen&gt; { int _selectedIndex = 0; // static const TextStyle optionStyle = // TextStyle(fontSize: 30, fontWeight: FontWeight.bold); static const List&lt;Widget&gt; _widgetOptions = &lt;Widget&gt;[ UserProfileScreen(), AllChildrenScreen(), AllArticleScreen(), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: IndexedStack( index: _selectedIndex, children: _widgetOptions, ), // body: Center( // child: _widgetOptions.elementAt(_selectedIndex), // ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.blue[50], items: const &lt;BottomNavigationBarItem&gt;[ BottomNavigationBarItem( icon: Icon(Icons.person), label: 'Profile', ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'Children', ), BottomNavigationBarItem( icon: Icon(Icons.article), label: 'Articles', ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.blue, onTap: _onItemTapped, ), ); } } </code></pre> <p>My main.dart screen calls SplashScreen and then SplashScreen calls BottomNavigationScreen. I am manually calling all the screens for <strong>_widgetOptions.elementAt(_selectedIndex)</strong> in widgetOptions.</p> <p>I want not to call all screens manually. Instead I want to call screens by using named routes defined in my main.dart file. How to pass named routes to my another class where I am defining my BottomNavigatioBar?</p>
[ { "answer_id": 74647512, "author": "Christian Fritz", "author_id": 1087119, "author_profile": "https://Stackoverflow.com/users/1087119", "pm_score": 0, "selected": false, "text": "dotnet --list-runtimes | cut -d ' ' -f 2 | sort | uniq | xargs\n6.0.11 6.0.9\n > for version in $(dotnet --list-runtimes | cut -d ' ' -f 2 | sort | uniq | xargs); do echo $version; done\n6.0.11\n6.0.9\n" }, { "answer_id": 74647519, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 1, "selected": true, "text": "$ array=( $(dotnet --list-runtimes | awk '{a[$2]=\"\"}END{for (i in a) print i}') )\n$ printf '%s\\n' \"${array[@]}\"\n6.0.9\n6.0.11\n" }, { "answer_id": 74647567, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 1, "selected": false, "text": "dotnet --list-runtimes | awk '!seen[$2]++{print $2}'\n vers=()\nwhile read -r v; do\n vers+=(\"$v\")\ndone < <(dotnet --list-runtimes | awk '!seen[$2]++{print $2}')\n\n# check array content\ndeclare -p vers\n\ndeclare -a vers=([0]=\"6.0.9\" [1]=\"6.0.11\")\n awk '!seen[$2]++{print $2}' < <(...) readarray vers" }, { "answer_id": 74648490, "author": "Cole Tierney", "author_id": 2820422, "author_profile": "https://Stackoverflow.com/users/2820422", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env bash\n\ndeclare -a sdks\nwhile read -r runtime; do\n set $runtime\n sdks+=(\"$2\")\ndone < <(dotnet --list-runtimes)\n\necho \"${sdks[@]}\"\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16280202/" ]
74,647,530
<p>I have a route that needs to wait for a Redis pub/sub message before it can send a response.</p> <pre><code> app.post('/route', async function (req: any, rep) { // Listen for redis redis.on('message', async (ch, msg) =&gt; { let match = JSON.parse(msg) if (match.id == req.body.id) { rep.send('ok') } }) // How to &quot;wait&quot; here? }) </code></pre> <p>As <code>ioredis.on()</code> doesn't return a <code>Promise</code>, I can't use <code>await</code> to block. What can I do to to make the code &quot;wait&quot; for the Redis message?</p>
[ { "answer_id": 74647562, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "app.post(\"/route\", async function (req: any, rep) {\n const [ch, msg] = await waitForMessage(redis);\n let match = JSON.parse(msg);\n if (match.id == req.body.id) {\n rep.send(\"ok\");\n }\n});\n\nfunction waitForMessage(redis) {\n return new Promise((resolve) =>\n redis.on(\"message\", (...args) => resolve(args))\n );\n}\n" }, { "answer_id": 74648345, "author": "Some Noob Student", "author_id": 499125, "author_profile": "https://Stackoverflow.com/users/499125", "pm_score": 0, "selected": false, "text": "export async function onMessage(redis: ioredis, exec: (...args: any[]) => boolean) {\n return new Promise((resolve) => {\n redis.on('message', (...args) => { if (exec(args)) resolve(args) })\n })\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499125/" ]
74,647,547
<p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;matrix.h&quot; int main(){ //Prompt the user for the size of matrix to be calculated. printf(&quot;Welcome to the matrix determinant calculator!\n\n&quot;); printf(&quot;Please select the matrix size you would like to input: \n&quot;); printf(&quot;\t (A): 2x2 matrix\n&quot;); printf(&quot;\t (B): 3x3 matrix\n\n&quot;); char selection; //Stores matrix size selection scanf(&quot; %c&quot;, &amp;selection); int size; //Size of matrix //Uses selection from user to determine value to assign to 'size' if (selection == 'A' || selection == 'a'){ size = 2; } else if (selection == 'B' || selection == 'b'){ size = 3; } else{ printf(&quot;Your selection is invalid. Please start over.\n&quot;); return 0; } printf(&quot;\nYou have selected a %dx%d matrix.\n\n&quot;, size, size); //Initialize pointer array int** matrix = (int**)malloc(size * sizeof(int*)); for (int i = 0; i &lt; size; i++){ matrix[i] = (int*)malloc(size * sizeof(int)); } readMatrix(matrix, size); //Sets up matrix by taking input from user int calc = determinant(matrix, size); //Calculates determinant printf(&quot;The %dx%d matrix is: \n\n&quot;, size, size); //Displays the matrix on the console for (int row = 0; row &lt; size; row++){ for (int col = 0; col &lt; size; col++){ printf(&quot;%d\t&quot;, matrix[row][col]); } printf(&quot;\n&quot;); } //Deletes stored data for (int i = 0; i &lt; size; i++){ free(matrix[i]); } free(matrix); printf(&quot;\nThe determinant of the matrix is: %d\n&quot;, calc); return 0; } </code></pre> <p><strong>determinant.c</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &quot;matrix.h&quot; #include &quot;determinant.h&quot; using namespace std; int determinant(int** matrix, int size){ int detm_calc; //Determinant calculation variable //Determine which formula to use - 2x2 or 3x3 matrix. if (size == 2){ //2x2 case int a = matrix[0][0]; int b = matrix[0][1]; int c = matrix[1][0]; int d = matrix[1][1]; detm_calc = (a*d) - (b*c); } else{ //3x3 case int a = matrix[0][0]; int b = matrix[0][1]; int c = matrix[0][2]; int d = matrix[1][0]; int e = matrix[1][1]; int f = matrix[1][2]; int g = matrix[2][0]; int h = matrix[2][1]; int i = matrix[2][2]; detm_calc = a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g); } return detm_calc; } </code></pre> <p><strong>determinant.h</strong></p> <pre><code>#ifndef DETERMINANT_H #define DETERMINANT_H #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;matrix.h&quot; int determinant(int**, int); #endif </code></pre> <p><strong>matrix.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;matrix.h&quot; #include &quot;determinant.h&quot; void readMatrix(int** matrix, int size){ for (int i = 0; i &lt; size; i++){ for (int j = 0; j &lt; size; j++){ printf(&quot;Please enter the integer for row %d column %d:\t&quot;, i+1, j+1); scanf(&quot;%d&quot;, &amp;matrix[i][j]); } printf(&quot;\n&quot;); } } </code></pre> <p><strong>matrix.h</strong></p> <pre><code>#ifndef MATRIX_H #define MATRIX_H #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;determinant.h&quot; void readMatrix(int**, int); #endif </code></pre> <p><strong>Makefile</strong></p> <pre><code>determinant: main.o determinant.o matrix.o g++ main.o determinant.o matrix.o -o determinant.out main.o: main.c g++ -c main.c determinant.o: determinant.c determinant.h g++ -c determinant.c matrix.o: matrix.c matrix.h g++ -c matrix.c </code></pre> <p>My code to create a determinant of a matrix is infinitely looping. What is wrong with the code shown? I believe it has something to do with the code within the main.c function and Initializing the pointer array but I can't pinpoint what is wrong.</p>
[ { "answer_id": 74647562, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "app.post(\"/route\", async function (req: any, rep) {\n const [ch, msg] = await waitForMessage(redis);\n let match = JSON.parse(msg);\n if (match.id == req.body.id) {\n rep.send(\"ok\");\n }\n});\n\nfunction waitForMessage(redis) {\n return new Promise((resolve) =>\n redis.on(\"message\", (...args) => resolve(args))\n );\n}\n" }, { "answer_id": 74648345, "author": "Some Noob Student", "author_id": 499125, "author_profile": "https://Stackoverflow.com/users/499125", "pm_score": 0, "selected": false, "text": "export async function onMessage(redis: ioredis, exec: (...args: any[]) => boolean) {\n return new Promise((resolve) => {\n redis.on('message', (...args) => { if (exec(args)) resolve(args) })\n })\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659828/" ]
74,647,573
<p>I'm wondering if it's possible to add new type of charts, like a radar chart, to the React library plotly/react-pivottable <a href="https://github.com/plotly/react-pivottable" rel="nofollow noreferrer">https://github.com/plotly/react-pivottable</a>.</p> <p>I would like to add a spider chart, always from the chart library plotly, but I can't understand where to start as the documentation is a litle poor and the GitHub repo is quite silence...</p> <p>Maybe it's not even possible.</p> <p>Does anyone know if it's possible?</p>
[ { "answer_id": 74647562, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 2, "selected": true, "text": "app.post(\"/route\", async function (req: any, rep) {\n const [ch, msg] = await waitForMessage(redis);\n let match = JSON.parse(msg);\n if (match.id == req.body.id) {\n rep.send(\"ok\");\n }\n});\n\nfunction waitForMessage(redis) {\n return new Promise((resolve) =>\n redis.on(\"message\", (...args) => resolve(args))\n );\n}\n" }, { "answer_id": 74648345, "author": "Some Noob Student", "author_id": 499125, "author_profile": "https://Stackoverflow.com/users/499125", "pm_score": 0, "selected": false, "text": "export async function onMessage(redis: ioredis, exec: (...args: any[]) => boolean) {\n return new Promise((resolve) => {\n redis.on('message', (...args) => { if (exec(args)) resolve(args) })\n })\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2072676/" ]
74,647,596
<p>How to display the value of a ulong in the text property of a label in c#? I'm really new to c# sorry if that's a dumb question.</p> <p>(this is in an &quot;if&quot; that works apart from this)</p> <pre><code>label1.Text = nameOfUlong; </code></pre> <p>I didn't know that you can't convert ulong to string I guess.</p>
[ { "answer_id": 74647621, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 1, "selected": false, "text": "label1.Text = nameOfUlong.ToString();\n" }, { "answer_id": 74647654, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": true, "text": "label1.Text = $\"{nameOfUlong}\";\n label1.Text = $\"My value ({nameOfUlong}) is ulong\";\n" }, { "answer_id": 74649218, "author": "Héctor M.", "author_id": 9443618, "author_profile": "https://Stackoverflow.com/users/9443618", "pm_score": 1, "selected": false, "text": "ulong myUlong = 12;\n\n// ToString() conversion\nlabel1.Text = myUlong.ToString();\n\n// string concatenation (implicit ToString())\nlabel1.Text = myUlong + \"\";\n\n// string interpolation\nlabel1.Text = $\"{myUlong}\";\n\n// string format\nlabel1.Text = string.Format(\"{0}\", myUlong);\n\n// System.Convert\nlabel1.Text = System.Convert.ToString(myUlong);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20648756/" ]
74,647,600
<p>I have a directory structured like this:</p> <pre><code>main_folder .git .gitignore rootfolder .DS_Store folder1 .ipynb_checkpoints/filename-checkpoint.csv abc.txt def.json somedir more.json folder2 .DS_Store .ipynb_checkpoints/file-filename2-checkpoint.csv rty.csv somedir uis.py .ipynb_checkpoints/filename1-checkpoint.csv .DS_Store </code></pre> <p>Being in the main_folder, I would like to commit everything, except all folders and files having the <code>DS_Store</code> or <code>ipynb_checkpoints</code> substring.</p> <p>In this specific case, I would like to commit:</p> <pre><code>main_folder rootfolder folder1 abc.txt def.json somedir more.json folder2 rty.csv somedir uis.py </code></pre> <p>In <code>.gitignore</code>-file, I have added:</p> <pre><code>**/checkpoint.csv **/.DS_Store </code></pre> <p>But not all checkpoint files have being ignored. What command lines should I add into my <code>.gitignore</code> file located in <code>main_folder</code>-directory</p>
[ { "answer_id": 74647621, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 1, "selected": false, "text": "label1.Text = nameOfUlong.ToString();\n" }, { "answer_id": 74647654, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": true, "text": "label1.Text = $\"{nameOfUlong}\";\n label1.Text = $\"My value ({nameOfUlong}) is ulong\";\n" }, { "answer_id": 74649218, "author": "Héctor M.", "author_id": 9443618, "author_profile": "https://Stackoverflow.com/users/9443618", "pm_score": 1, "selected": false, "text": "ulong myUlong = 12;\n\n// ToString() conversion\nlabel1.Text = myUlong.ToString();\n\n// string concatenation (implicit ToString())\nlabel1.Text = myUlong + \"\";\n\n// string interpolation\nlabel1.Text = $\"{myUlong}\";\n\n// string format\nlabel1.Text = string.Format(\"{0}\", myUlong);\n\n// System.Convert\nlabel1.Text = System.Convert.ToString(myUlong);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11857974/" ]
74,647,631
<p>i am trying to display some data about a specific id and THATS where the WHERE Clause comes in place, but it doens't work. By the way in wp_posts the user_id is the wp_users.ID.</p> <pre><code>SELECT wp_users.ID, post_name FROM wp_users LEFT JOIN wp_posts ON wp_users.ID = user_id ORDER BY wp_users.ID WHERE wp_users.ID=&quot;2&quot; </code></pre> <p>This works and displays the wp_users.ID and post_name but if i want to display only the post_names of a specific ID with this line 'WHERE wp_users.ID=&quot;2&quot;' it doesn't work.</p> <p>New to MySQL</p>
[ { "answer_id": 74647621, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 1, "selected": false, "text": "label1.Text = nameOfUlong.ToString();\n" }, { "answer_id": 74647654, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": true, "text": "label1.Text = $\"{nameOfUlong}\";\n label1.Text = $\"My value ({nameOfUlong}) is ulong\";\n" }, { "answer_id": 74649218, "author": "Héctor M.", "author_id": 9443618, "author_profile": "https://Stackoverflow.com/users/9443618", "pm_score": 1, "selected": false, "text": "ulong myUlong = 12;\n\n// ToString() conversion\nlabel1.Text = myUlong.ToString();\n\n// string concatenation (implicit ToString())\nlabel1.Text = myUlong + \"\";\n\n// string interpolation\nlabel1.Text = $\"{myUlong}\";\n\n// string format\nlabel1.Text = string.Format(\"{0}\", myUlong);\n\n// System.Convert\nlabel1.Text = System.Convert.ToString(myUlong);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659884/" ]
74,647,633
<p>I'm switching from moment to Luxon. Currently, using moment I can can convert a <code>Date()</code> to timestamp format with this:</p> <pre><code> ....moment() .subtract(2, 'hours') .utc() .format('YYYY-MM-DD HH:mm:ss [GMT]'); </code></pre> <p>with the result looking like : <code>2022-12-01 17:40:16 GMT</code></p> <p>switching over to luxon and looking at the docs, I don't see any option to quite get me to that desired result. I've tried this:</p> <pre><code>const tryThis = date.minus({ hours: 2 }).toISO(); const getGMTIntheDate = DateTime.fromISO(tryThis); const finalResult = getGMTIntheDate.toJSDate().toString(); </code></pre> <p>which gives me this result: <code>Thu Dec 01 2022 09:49:44 GMT-0800 (Pacific Standard Time)</code></p> <p>is there a custom formatting option or am I missing something in the docs?</p>
[ { "answer_id": 74647621, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 1, "selected": false, "text": "label1.Text = nameOfUlong.ToString();\n" }, { "answer_id": 74647654, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": true, "text": "label1.Text = $\"{nameOfUlong}\";\n label1.Text = $\"My value ({nameOfUlong}) is ulong\";\n" }, { "answer_id": 74649218, "author": "Héctor M.", "author_id": 9443618, "author_profile": "https://Stackoverflow.com/users/9443618", "pm_score": 1, "selected": false, "text": "ulong myUlong = 12;\n\n// ToString() conversion\nlabel1.Text = myUlong.ToString();\n\n// string concatenation (implicit ToString())\nlabel1.Text = myUlong + \"\";\n\n// string interpolation\nlabel1.Text = $\"{myUlong}\";\n\n// string format\nlabel1.Text = string.Format(\"{0}\", myUlong);\n\n// System.Convert\nlabel1.Text = System.Convert.ToString(myUlong);\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20235789/" ]
74,647,636
<p>Hello I'm a beginner at PL/SQL and some help would be appreciated.</p> <p>So I have this procedure here and my goal is to have it so that when this procedure is executed that I can enter a 5 digit integer (a zipcode) and it will just select those values from the table and display just as if I've done a query like</p> <pre><code>SELECT * FROM customers WHERE customer_zipcode = &quot;input zipcode&quot;. create or replace PROCEDURE LIST_CUSTOMER_ZIPCODE( p_zipcode IN customers.customer_zipcode%TYPE, p_disp OUT SYS_REFCURSOR) -- User input Variable, Display Variable IS BEGIN OPEN p_disp for SELECT customer_first_name, customer_zipcode FROM customers WHERE customer_zipcode=p_zipcode; EXCEPTION -- Input Sanitization WHEN no_data_found THEN dbms_output.put_line('-1'); END; EXEC LIST_CUSTOMER_ZIPCODE(07080); </code></pre> <p>When I execute this command I just keep getting this error.</p> <p><a href="https://i.stack.imgur.com/nCI8T.png" rel="nofollow noreferrer">https://i.stack.imgur.com/nCI8T.png</a></p>
[ { "answer_id": 74647719, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 0, "selected": false, "text": "SQL> set serveroutput on\nSQL> create or replace procedure p_list\n 2 (p_deptno in dept.deptno%type,\n 3 p_disp out sys_refcursor\n 4 )\n 5 is\n 6 begin\n 7 open p_disp for select ename, job from emp\n 8 where deptno = p_deptno;\n 9 end;\n 10 /\n\nProcedure created.\n SQL> declare\n 2 l_list sys_refcursor;\n 3 l_ename emp.ename%type;\n 4 l_job emp.job%type;\n 5 begin\n 6 p_list(10, l_list); --> calling the procedure; use 2 parameters\n 7\n 8 loop\n 9 fetch l_list into l_ename, l_job;\n 10 exit when l_list%notfound;\n 11 dbms_output.put_line(l_ename ||' - '|| l_job);\n 12 end loop;\n 13 end;\n 14 /\nCLARK - MANAGER\nKING - PRESIDENT\nMILLER - CLERK\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74648182, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT * FROM customers WHERE customer_zipcode = \"input zipcode\".\n\ncreate or replace PROCEDURE LIST_CUSTOMER_ZIPCODE(\n p_zipcode IN customers.customer_zipcode%TYPE,\n p_disp OUT SYS_REFCURSOR\n)\nIS\nBEGIN\n OPEN p_disp FOR\n SELECT customer_first_name, customer_zipcode\n FROM customers \n WHERE customer_zipcode = p_zipcode;\nEXCEPTION\n -- Input Sanitization\n WHEN no_data_found THEN\n dbms_output.put_line('-1');\nEND;\n/\n\nVARIABLE cur SYS_REFCURSOR;\n\nEXEC LIST_CUSTOMER_ZIPCODE('07080', :cur);\n\nPRINT cur;\n create or replace PROCEDURE LIST_CUSTOMER_ZIPCODE(\n p_zipcode IN customers.customer_zipcode%TYPE,\n p_disp OUT SYS_REFCURSOR\n)\nIS\nBEGIN\n OPEN p_disp FOR\n SELECT customer_first_name, customer_zipcode\n FROM customers \n WHERE customer_zipcode = p_zipcode;\nEND;\n/\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15208122/" ]
74,647,640
<p>I have this DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Names</th> <th>Account_1</th> <th>Account_2</th> <th>ID_Movement</th> <th>Less_1</th> <th>Less_2</th> </tr> </thead> <tbody> <tr> <td>Peter</td> <td>35</td> <td>70</td> <td>Movement_1</td> <td>0</td> <td>5</td> </tr> <tr> <td>Peter</td> <td>35</td> <td>70</td> <td>Movement_2</td> <td>6</td> <td>0</td> </tr> <tr> <td>Peter</td> <td>35</td> <td>70</td> <td>Movement_3</td> <td>1</td> <td>0</td> </tr> <tr> <td>Peter</td> <td>35</td> <td>70</td> <td>Movement_4</td> <td>0</td> <td>2</td> </tr> <tr> <td>Jhon</td> <td>55</td> <td>60</td> <td>Movement_5</td> <td>6</td> <td>0</td> </tr> <tr> <td>Jhon</td> <td>55</td> <td>60</td> <td>Movement_6</td> <td>0</td> <td>2</td> </tr> <tr> <td>Jhon</td> <td>55</td> <td>60</td> <td>Movement_7</td> <td>0</td> <td>3</td> </tr> <tr> <td>Jhon</td> <td>55</td> <td>60</td> <td>Movement_8</td> <td>12</td> <td>0</td> </tr> <tr> <td>Jhon</td> <td>55</td> <td>60</td> <td>Movement_9</td> <td>6</td> <td>0</td> </tr> <tr> <td>William</td> <td>34</td> <td>88</td> <td>Movement_10</td> <td>0</td> <td>8</td> </tr> <tr> <td>William</td> <td>34</td> <td>88</td> <td>Movement_11</td> <td>0</td> <td>9</td> </tr> <tr> <td>William</td> <td>34</td> <td>88</td> <td>Movement_12</td> <td>0</td> <td>5</td> </tr> </tbody> </table> </div> <p>I was trying to create a new column with the current value of the account of each person with this code:</p> <p><code>s = (df['Account_1']).sub(df['Less_1']).groupby(df['Names']).cumsum()</code> <code>df2['New_Account1'] = s</code></p> <p>Desired Output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Names</th> <th style="text-align: center;">Account 1</th> <th style="text-align: center;">Account 2</th> <th style="text-align: center;">ID_Movement</th> <th style="text-align: center;">Less_1</th> <th style="text-align: center;">Less_2</th> <th style="text-align: center;">New_Account1</th> <th style="text-align: center;">New_Account2</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Peter</td> <td style="text-align: center;">35</td> <td style="text-align: center;">70</td> <td style="text-align: center;">Movement_1</td> <td style="text-align: center;">0</td> <td style="text-align: center;">11</td> <td style="text-align: center;">35</td> <td style="text-align: center;">59</td> </tr> <tr> <td style="text-align: center;">Peter</td> <td style="text-align: center;">35</td> <td style="text-align: center;">70</td> <td style="text-align: center;">Movement_2</td> <td style="text-align: center;">6</td> <td style="text-align: center;">0</td> <td style="text-align: center;">29</td> <td style="text-align: center;">59</td> </tr> <tr> <td style="text-align: center;">Peter</td> <td style="text-align: center;">35</td> <td style="text-align: center;">70</td> <td style="text-align: center;">Movement_3</td> <td style="text-align: center;">6</td> <td style="text-align: center;">0</td> <td style="text-align: center;">23</td> <td style="text-align: center;">59</td> </tr> <tr> <td style="text-align: center;">Peter</td> <td style="text-align: center;">35</td> <td style="text-align: center;">70</td> <td style="text-align: center;">Movement_4</td> <td style="text-align: center;">0</td> <td style="text-align: center;">4</td> <td style="text-align: center;">23</td> <td style="text-align: center;">55</td> </tr> <tr> <td style="text-align: center;">Jhon</td> <td style="text-align: center;">55</td> <td style="text-align: center;">60</td> <td style="text-align: center;">Movement_5</td> <td style="text-align: center;">6</td> <td style="text-align: center;">0</td> <td style="text-align: center;">49</td> <td style="text-align: center;">60</td> </tr> <tr> <td style="text-align: center;">Jhon</td> <td style="text-align: center;">55</td> <td style="text-align: center;">60</td> <td style="text-align: center;">Movement_6</td> <td style="text-align: center;">0</td> <td style="text-align: center;">14</td> <td style="text-align: center;">49</td> <td style="text-align: center;">46</td> </tr> <tr> <td style="text-align: center;">Jhon</td> <td style="text-align: center;">55</td> <td style="text-align: center;">60</td> <td style="text-align: center;">Movement_7</td> <td style="text-align: center;">0</td> <td style="text-align: center;">13</td> <td style="text-align: center;">49</td> <td style="text-align: center;">33</td> </tr> <tr> <td style="text-align: center;">Jhon</td> <td style="text-align: center;">55</td> <td style="text-align: center;">60</td> <td style="text-align: center;">Movement_8</td> <td style="text-align: center;">12</td> <td style="text-align: center;">0</td> <td style="text-align: center;">37</td> <td style="text-align: center;">33</td> </tr> <tr> <td style="text-align: center;">Jhon</td> <td style="text-align: center;">55</td> <td style="text-align: center;">60</td> <td style="text-align: center;">Movement_9</td> <td style="text-align: center;">6</td> <td style="text-align: center;">0</td> <td style="text-align: center;">31</td> <td style="text-align: center;">33</td> </tr> <tr> <td style="text-align: center;">William</td> <td style="text-align: center;">34</td> <td style="text-align: center;">88</td> <td style="text-align: center;">Movement_10</td> <td style="text-align: center;">12</td> <td style="text-align: center;">0</td> <td style="text-align: center;">22</td> <td style="text-align: center;">88</td> </tr> <tr> <td style="text-align: center;">William</td> <td style="text-align: center;">34</td> <td style="text-align: center;">88</td> <td style="text-align: center;">Movement_11</td> <td style="text-align: center;">0</td> <td style="text-align: center;">9</td> <td style="text-align: center;">22</td> <td style="text-align: center;">79</td> </tr> <tr> <td style="text-align: center;">William</td> <td style="text-align: center;">34</td> <td style="text-align: center;">88</td> <td style="text-align: center;">Movement_12</td> <td style="text-align: center;">0</td> <td style="text-align: center;">5</td> <td style="text-align: center;">22</td> <td style="text-align: center;">74</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74647833, "author": "Pawel Sznura", "author_id": 10457515, "author_profile": "https://Stackoverflow.com/users/10457515", "pm_score": 0, "selected": false, "text": "df['New_Account1'] = df.apply(lambda row : (row['Account 1'] - row['Less_1']), axis = 1)\n" }, { "answer_id": 74648525, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby.cumsum to_numpy() df[['New_Account1', 'New_Account2']] = (df[['Account_1', 'Account_2']]\n - df.groupby('Names')[['Less_1', 'Less_2']]\n .cumsum().to_numpy()\n )\n Names Account_1 Account_2 ID_Movement Less_1 Less_2 New_Account1 New_Account2\n0 Peter 35 70 Movement_1 0 5 35 65\n1 Peter 35 70 Movement_2 6 0 29 65\n2 Peter 35 70 Movement_3 1 0 28 65\n3 Peter 35 70 Movement_4 0 2 28 63\n4 Jhon 55 60 Movement_5 6 0 49 60\n5 Jhon 55 60 Movement_6 0 2 49 58\n6 Jhon 55 60 Movement_7 0 3 49 55\n7 Jhon 55 60 Movement_8 12 0 37 55\n8 Jhon 55 60 Movement_9 6 0 31 55\n9 William 34 88 Movement_10 0 8 34 80\n10 William 34 88 Movement_11 0 9 34 71\n11 William 34 88 Movement_12 0 5 34 66\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478046/" ]
74,647,645
<p>when I use updateCorrectAnswers with useEffect below. it is not updating my correct answers. it shows just empty array. when a new set of api call comes it shows my old data. I don't understand why. <a href="https://i.stack.imgur.com/MbW5L.png" rel="nofollow noreferrer">console.log image that shows old data and empty data</a></p> <p>i revisited some of stackoverflow posts about it but it mostly about useEffect but I am trying inside of useEffect. this is whole code if anyone need <a href="https://github.com/hyklops/react-starter/tree/master/quiz-app" rel="nofollow noreferrer">https://github.com/hyklops/react-starter/tree/master/quiz-app</a></p> <pre><code>function App() { const [trivias, setTrivias] = useState(null); const [isFetched, setIsFetched] = useState(false); const [correctAnswers, setCorrectAnswers] = useState([]); const updateCorrectAnswers = () =&gt; { trivias.map((trivia) =&gt; { setCorrectAnswers((prev) =&gt; [...prev, trivia.correct_answer]); }); }; async function dataFetch() { const res = await fetch( &quot;https://opentdb.com/api.php?amount=5&amp;type=multiple&quot; ); const data = await res.json(); return setTrivias(data.results); } const shuffle = (trivia, index) =&gt; { const answers = [...trivia.incorrect_answers, trivia.correct_answer]; const shuffledAnswers = getRandomAnswers(answers); // const shuffleArray = (answer) =&gt; [...array].sort(() =&gt; Math.random() - 0.5); return shuffledAnswers; }; const getRandomAnswers = (answers) =&gt; { const newAnswers = []; while (newAnswers.length !== 4) { const getRandomIndex = Math.floor(Math.random() * 4); const condition = newAnswers.some( (item) =&gt; item === answers[getRandomIndex] ); if (!condition) { newAnswers.push(answers[getRandomIndex]); } } return newAnswers; }; const getTrivias = () =&gt; { return trivias.map((trivia, index) =&gt; { return &lt;Trivia question={trivia.question} answers={shuffle(trivia)} /&gt;; }); }; useEffect(() =&gt; { dataFetch(); }, []); useEffect(() =&gt; { if (!!trivias) { setIsFetched(true); updateCorrectAnswers(); console.log({ correctAnswers }); } }, [trivias]); if (!isFetched) { return &lt;h1&gt;loading&lt;/h1&gt;; } return ( &lt;div className=&quot;App&quot;&gt; &lt;div&gt;{getTrivias()}&lt;/div&gt; &lt;div className=&quot;check&quot;&gt; &lt;button&gt;Check Answers&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>I tried useEffect and it did'nt worked.</p>
[ { "answer_id": 74647833, "author": "Pawel Sznura", "author_id": 10457515, "author_profile": "https://Stackoverflow.com/users/10457515", "pm_score": 0, "selected": false, "text": "df['New_Account1'] = df.apply(lambda row : (row['Account 1'] - row['Less_1']), axis = 1)\n" }, { "answer_id": 74648525, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby.cumsum to_numpy() df[['New_Account1', 'New_Account2']] = (df[['Account_1', 'Account_2']]\n - df.groupby('Names')[['Less_1', 'Less_2']]\n .cumsum().to_numpy()\n )\n Names Account_1 Account_2 ID_Movement Less_1 Less_2 New_Account1 New_Account2\n0 Peter 35 70 Movement_1 0 5 35 65\n1 Peter 35 70 Movement_2 6 0 29 65\n2 Peter 35 70 Movement_3 1 0 28 65\n3 Peter 35 70 Movement_4 0 2 28 63\n4 Jhon 55 60 Movement_5 6 0 49 60\n5 Jhon 55 60 Movement_6 0 2 49 58\n6 Jhon 55 60 Movement_7 0 3 49 55\n7 Jhon 55 60 Movement_8 12 0 37 55\n8 Jhon 55 60 Movement_9 6 0 31 55\n9 William 34 88 Movement_10 0 8 34 80\n10 William 34 88 Movement_11 0 9 34 71\n11 William 34 88 Movement_12 0 5 34 66\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659878/" ]
74,647,647
<p>I just started learning about Google Apps Scripts and I created this script that will help me copy a range of data in Google Sheets into another sheet.</p> <p>This is my code</p> <pre><code>function copyPaste() { const ss = SpreadsheetApp.openById('1btVcMHU2a4hyU6gz3D4ZN7RYXX_HYWLKJPxuGmdKvEI').getSheetByName('Form1'); const nutriSheet = SpreadsheetApp.openById('1btVcMHU2a4hyU6gz3D4ZN7RYXX_HYWLKJPxuGmdKvEI').getSheetByName('Data'); const nutriLastRow = nutriSheet.getLastRow(); let copyRange = ss.getSheetValues(3,7,1,30); let rowValues = ss.getRange(3,7,1,30).getValues(); nutriSheet.getRange(nutriLastRow+1, 2, 1, 30).setValues(rowValues); } </code></pre> <p>The code works when I run it from the app but when I tried to assign the script to a button(drawing) and entering copyPaste, it says &quot;Script function copyPaste could not be found&quot;.</p> <p>I made sure to name it as the function and not the google app script project name.</p> <p>I ahve also tried opening it in incognito but it still didn't work.</p> <p>I was really happy to get the code to work but now I need to figure out how to run it from Google Sheet.</p> <p>I have also tried to use the ui.createMenu('Custom Menu') but I can't seem to get it to work. It says &quot;Cannot call SpreadsheetApp.getUi() from this context&quot;</p> <pre><code>function onOpen(e) { let ui = SpreadsheetApp.getUi(); ui.createMenu('Shortcusts') .addItem('Copy to Data', 'copyPaste') .addToUi(); }; </code></pre> <p>I created this code by editting existing code on GitHub and modified it to fit my purpose.</p> <p>Hope someone can help me with this, thanks in advance!</p>
[ { "answer_id": 74647833, "author": "Pawel Sznura", "author_id": 10457515, "author_profile": "https://Stackoverflow.com/users/10457515", "pm_score": 0, "selected": false, "text": "df['New_Account1'] = df.apply(lambda row : (row['Account 1'] - row['Less_1']), axis = 1)\n" }, { "answer_id": 74648525, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "groupby.cumsum to_numpy() df[['New_Account1', 'New_Account2']] = (df[['Account_1', 'Account_2']]\n - df.groupby('Names')[['Less_1', 'Less_2']]\n .cumsum().to_numpy()\n )\n Names Account_1 Account_2 ID_Movement Less_1 Less_2 New_Account1 New_Account2\n0 Peter 35 70 Movement_1 0 5 35 65\n1 Peter 35 70 Movement_2 6 0 29 65\n2 Peter 35 70 Movement_3 1 0 28 65\n3 Peter 35 70 Movement_4 0 2 28 63\n4 Jhon 55 60 Movement_5 6 0 49 60\n5 Jhon 55 60 Movement_6 0 2 49 58\n6 Jhon 55 60 Movement_7 0 3 49 55\n7 Jhon 55 60 Movement_8 12 0 37 55\n8 Jhon 55 60 Movement_9 6 0 31 55\n9 William 34 88 Movement_10 0 8 34 80\n10 William 34 88 Movement_11 0 9 34 71\n11 William 34 88 Movement_12 0 5 34 66\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659798/" ]
74,647,651
<p>I am trying to add a parameter to a Revit family. When I open the Revit Family document and execute the code below in a macro, I get this error:</p> <blockquote> <p>System.Exception: Document regeneration failed. at MacroModule.executeMacro_(MacroModule*, AString* MacroName) at MacroModule.executeMacro_(MacroModule*, AString* ) at UIMacroGeneralManager.runMacro(UIMacroGeneralManager*, MacroModule* pModule, AString* macroName)</p> </blockquote> <p>Any idea how to solve this issue?</p> <pre><code>public void FamilyInstanceParameters() { Document document = this.ActiveUIDocument.ActiveView.Document; if (!document.IsFamilyDocument) { TaskDialog.Show(&quot;Info&quot;, &quot;This is not a FamilyDocument&quot;); } else { try { Transaction transaction = new Transaction(document); transaction.Start(&quot;Param&quot;); // Get the family document category Family family = document.OwnerFamily; Category category = family.FamilyCategory; FamilyType familyType = document.FamilyManager.NewType(&quot;New Type A&quot;); document.FamilyManager.CurrentType = familyType; // Parameter group BuiltInParameterGroup builtInParamGroup = BuiltInParameterGroup.PG_IDENTITY_DATA; document.Regenerate(); FamilyParameter familyParameter = document.FamilyManager .AddParameter(&quot;parameterName&quot;, builtInParamGroup, category, false); document.FamilyManager.Set(familyParameter, &quot;parameterValue&quot;); transaction.Commit(); transaction.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } } } </code></pre>
[ { "answer_id": 74651898, "author": "Jeremy Tammik", "author_id": 3552305, "author_profile": "https://Stackoverflow.com/users/3552305", "pm_score": 1, "selected": false, "text": "document.Regenerate" }, { "answer_id": 74653002, "author": "Ranj", "author_id": 3419211, "author_profile": "https://Stackoverflow.com/users/3419211", "pm_score": 0, "selected": false, "text": "public void FamilyInstanceParameters()\n{\n Document document = this.ActiveUIDocument.ActiveView.Document;\n if (!document.IsFamilyDocument)\n {\n TaskDialog.Show(\"Info\", \"This is not a FamilyDocument\");\n }\n else\n {\n try\n {\n Transaction transaction = new Transaction(document);\n transaction.Start(\"Param\");\n\n // Get the family document category\n Family family = document.OwnerFamily;\n Category category = family.FamilyCategory;\n\n FamilyType familyType = document.FamilyManager.NewType(\"New Type A\");\n document.FamilyManager.CurrentType = familyType;\n\n\n // ParameterName en value\n string parameterName = \"parameterNameLength\";\n int parameterValue = 20;\n\n FamilyParameter familyParameter = document.FamilyManager.AddParameter(parameterName: parameterName, groupTypeId: GroupTypeId.Constraints, specTypeId: SpecTypeId.Length, isInstance: false);\n\n\n document.FamilyManager.Set(familyParameter, parameterValue);\n\n transaction.Commit();\n transaction.Dispose();\n }\n catch (Exception ex)\n {\n throw new Exception(ex.Message);\n }\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3419211/" ]
74,647,659
<p>I have a question: we have a table that has (among other stuff) a couple of IP/port pairs that I would like to be globally unique to avoid crosstalk in streaming binaries that use this configuration.</p> <p>Assume a table as follows</p> <pre><code>Create table config ( Id serial NOT NULL, One_IP text, One_Port integer, Two_IP text, Two_Port integer ); </code></pre> <p>Then I could add constraints</p> <pre><code> UNIQUE(One_IP, One_Port) </code></pre> <p>and</p> <pre><code> UNIQUE(Two_IP, Two_Port) </code></pre> <p>This gets me much of the way there. The will be no crosstalk among different rows an each set.</p> <p>But these are independent of each other – no &quot;One&quot; IP/port pair will repeat and no &quot;Two&quot; IP/Port pair will repeat but I could still have a One IP/Port the same as a two IP/Port (on same or different rows) Is there a way to create a constraint that combines them? (not a simple 4 column unique)</p> <p>If I have these rows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>One_IP</th> <th>One_Port</th> <th>Two_Ip</th> <th>Two_Port</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>239.1.1.12</td> <td>21</td> <td>239.1.1.13</td> <td>21</td> </tr> <tr> <td>2</td> <td>239.1.1.12</td> <td>22</td> <td>239.1.1.13</td> <td>22</td> </tr> </tbody> </table> </div> <p>Then I shouldn't be able to insert any of the following rows ...</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>One_IP</th> <th>One_Port</th> <th>Two_Ip</th> <th>Two_Port</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>239.1.1.12</td> <td>21</td> <td>239.4.5.6</td> <td>44</td> </tr> <tr> <td>x</td> <td>239.1.1.12</td> <td>22</td> <td>239.4.5.6</td> <td>45</td> </tr> <tr> <td>x</td> <td>239.1.1.13</td> <td>21</td> <td>239.4.5.6</td> <td>46</td> </tr> <tr> <td>x</td> <td>239.1.1.13</td> <td>22</td> <td>239.4.5.6</td> <td>47</td> </tr> <tr> <td>x</td> <td>239.7.8.9</td> <td>81</td> <td>239.1.1.12</td> <td>21</td> </tr> <tr> <td>x</td> <td>239.7.8.9</td> <td>82</td> <td>239.1.1.12</td> <td>22</td> </tr> <tr> <td>x</td> <td>239.7.8.9</td> <td>83</td> <td>239.1.1.13</td> <td>21</td> </tr> <tr> <td>x</td> <td>239.7.8.9</td> <td>84</td> <td>239.1.1.13</td> <td>22</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74647803, "author": "Dijkgraaf", "author_id": 2571021, "author_profile": "https://Stackoverflow.com/users/2571021", "pm_score": -1, "selected": false, "text": "Create table config (\n Id serial NOT NULL,\n IP text,\n Port integer,\n OtherConfigID integer NULL)\n" }, { "answer_id": 74647852, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 1, "selected": false, "text": "create table devices (\n id serial primary key\n);\n\ncreate table device_addresses (\n device_id int not null references devices(id),\n ip inet not null,\n port integer not null check(port > 0),\n\n unique(ip, port)\n);\n string_agg select\n name,\n string_agg(ip || ':' || port, ', ') as addresses\nfrom devices d\nleft join device_addresses da on d.id = da.device_id\ngroup by d.id\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659873/" ]
74,647,677
<p>I have a React application. I have installed the packages with <code>yarn</code> and ran it with <code>yarn start</code>. But, the app is not opening in the browser. The console shows me the following:</p> <pre><code>Compiled successfully! You can now view extension in the browser. http://localhost:3000 Note that the development build is not optimized. To create a production build, use yarn build. webpack compiled successfully Files successfully emitted, waiting for typecheck results... Issues checking in progress... No issues found. </code></pre> <p>But when I open the browser at <code>localhost:3000</code> and it shows nothing, but:</p> <pre><code>This site can’t be reached localhost refused to connect. </code></pre> <p>Did anyone have this kind of issue? Any kind of help would be appreciated.</p> <p>PS: I tried to remove <code>node_modules</code> and install packages again, <code>npx clear-npx-cache</code> as well, but nothing worked.</p> <p><strong>Update</strong> After I build the app with <code>yarn build</code> and run <code>serve -s build</code> then I can access the app on <code>localhost:3000</code>. Why this happens?</p>
[ { "answer_id": 74647803, "author": "Dijkgraaf", "author_id": 2571021, "author_profile": "https://Stackoverflow.com/users/2571021", "pm_score": -1, "selected": false, "text": "Create table config (\n Id serial NOT NULL,\n IP text,\n Port integer,\n OtherConfigID integer NULL)\n" }, { "answer_id": 74647852, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 1, "selected": false, "text": "create table devices (\n id serial primary key\n);\n\ncreate table device_addresses (\n device_id int not null references devices(id),\n ip inet not null,\n port integer not null check(port > 0),\n\n unique(ip, port)\n);\n string_agg select\n name,\n string_agg(ip || ':' || port, ', ') as addresses\nfrom devices d\nleft join device_addresses da on d.id = da.device_id\ngroup by d.id\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12743692/" ]
74,647,681
<p>This would be useful for me because I have a bunch of constants that are different when I test my program locally vs when I run it on the server that it's supposed to run on.</p> <p>I assumed an if-else expression would work:</p> <pre><code>const val FOO = false const val BAR = if (FOO) 1L else 2L </code></pre> <p>However, the compiler considers this an error because for some reason, this if-else expression is not considered to be constant even though it really should be in my opinion, just like arithmetic expressions with constant values can also be assigned to constants.</p> <p>My first question is, why does this not work, and secondly and more importantly, <strong>is there a way to do this?</strong> Or am I just forced to make these fields not constant?</p>
[ { "answer_id": 74647818, "author": "radof", "author_id": 20349343, "author_profile": "https://Stackoverflow.com/users/20349343", "pm_score": 0, "selected": false, "text": "const const final final val var val const val" }, { "answer_id": 74648121, "author": "Joffrey", "author_id": 1540818, "author_profile": "https://Stackoverflow.com/users/1540818", "pm_score": 3, "selected": true, "text": "if const val" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6514834/" ]
74,647,685
<p>I'm unable to get any information about the parameter when using <code>typing.Union</code>:</p> <pre class="lang-py prettyprint-override"><code>import typing x = typing.Union[str,int] print(typing.get_args(x)) </code></pre> <p>Output: <code>(&lt;class 'str'&gt;, &lt;class 'int'&gt;)</code></p> <pre class="lang-py prettyprint-override"><code>def f(y: typing.Union[str,int]): print(typing.get_args(y)) f(1) </code></pre> <p>Output: <code>()</code></p>
[ { "answer_id": 74648460, "author": "Daniil Fajnberg", "author_id": 19770795, "author_profile": "https://Stackoverflow.com/users/19770795", "pm_score": 1, "selected": false, "text": "x y int str print(type(x)) print(type(y)) y str int get_args int 1 x from typing import Union\n\nx = Union[str, int]\n\ndef f(y: x):\n ...\n from typing import Union\n\ndef f(y: Union[str, int]):\n ...\n" }, { "answer_id": 74652977, "author": "Paweł Rubin", "author_id": 8091093, "author_profile": "https://Stackoverflow.com/users/8091093", "pm_score": 0, "selected": false, "text": "typing.get_type_hints() f def f(y: typing.Union[str,int]):\n print(typing.get_type_hints(f))\n\nf(1)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617657/" ]
74,647,695
<p>I have an array with Questions. Each question has options to pick from and the correct answer. I am trying to add true/false if the option is correct. How should I best do this? I tried <code>.map()</code> and <code>.forEach</code> but I don't know how to access <code>correct_answer</code> and use that to add the <code>true/false</code> values under options.</p> <pre><code>const data = [ { &quot;question&quot;: &quot;What is the approximate value of mathematical constant e?&quot;, &quot;options&quot;: [ { &quot;option&quot;: &quot;1.41&quot;, }, { &quot;option&quot;: &quot;1.62&quot;, }, { &quot;option&quot;: &quot;2.72&quot;, }, { &quot;option&quot;: &quot;3.14&quot;, } ], &quot;correct_answer&quot;: &quot;2.72&quot; }, { &quot;question&quot;: &quot;What is the name of the main character of the anime &amp;quot;One-Punch Man&amp;quot;?&quot;, &quot;options&quot;: [ { &quot;option&quot;: &quot;Genos&quot;, }, { &quot;option&quot;: &quot;King&quot;, }, { &quot;option&quot;: &quot;Saitama&quot;, }, { &quot;option&quot;: &quot;Sonic&quot;, } ], &quot;correct_answer&quot;: &quot;Saitama&quot; } ] </code></pre> <p>Desired result</p> <pre><code>const data = [ { &quot;question&quot;: &quot;What is the approximate value of mathematical constant e?&quot;, &quot;options&quot;: [ { &quot;option&quot;: &quot;1.41&quot;, &quot;correct_answer&quot;: false, }, { &quot;option&quot;: &quot;1.62&quot;, &quot;correct_answer&quot;: false, }, { &quot;option&quot;: &quot;2.72&quot;, &quot;correct_answer&quot;: true, }, { &quot;option&quot;: &quot;3.14&quot;, &quot;correct_answer&quot;: false, } ], &quot;correct_answer&quot;: &quot;2.72&quot; }, { &quot;question&quot;: &quot;What is the name of the main character of the anime &amp;quot;One-Punch Man&amp;quot;?&quot;, &quot;options&quot;: [ { &quot;option&quot;: &quot;Genos&quot;, &quot;correct_answer&quot;: false, }, { &quot;option&quot;: &quot;King&quot;, &quot;correct_answer&quot;: false, }, { &quot;option&quot;: &quot;Saitama&quot;, &quot;correct_answer&quot;: true, }, { &quot;option&quot;: &quot;Sonic&quot;, &quot;correct_answer&quot;: false, } ], &quot;correct_answer&quot;: &quot;Saitama&quot; } ] </code></pre>
[ { "answer_id": 74647717, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const data = [{\n \"question\": \"What is the approximate value of mathematical constant e?\",\n \"options\": [{\n \"option\": \"1.41\",\n },\n {\n \"option\": \"1.62\",\n },\n {\n \"option\": \"2.72\",\n },\n {\n \"option\": \"3.14\",\n }\n ],\n \"correct_answer\": \"2.72\"\n },\n {\n \"question\": \"What is the name of the main character of the anime &quot;One-Punch Man&quot;?\",\n \"options\": [{\n \"option\": \"Genos\",\n },\n {\n \"option\": \"King\",\n },\n {\n \"option\": \"Saitama\",\n },\n {\n \"option\": \"Sonic\",\n }\n ],\n \"correct_answer\": \"Saitama\"\n }\n]\n\ndata.forEach(question => {\n question.options.forEach(option => {\n option.correct_answer = option.option === question.correct_answer\n })\n})\n\nconsole.log(data)" }, { "answer_id": 74647733, "author": "geekySRM", "author_id": 7636285, "author_profile": "https://Stackoverflow.com/users/7636285", "pm_score": 0, "selected": false, "text": "map() forEach() forEach() const data = [\n {\n \"question\": \"What is the approximate value of mathematical constant e?\",\n \"options\": [\n {\n \"option\": \"1.41\",\n },\n {\n \"option\": \"1.62\",\n },\n {\n \"option\": \"2.72\",\n },\n {\n \"option\": \"3.14\",\n }\n ],\n \"correct_answer\": \"2.72\"\n },\n {\n \"question\": \"What is the name of the main character of the anime &quot;One-Punch Man&quot;?\",\n \"options\": [\n {\n \"option\": \"Genos\",\n },\n {\n \"option\": \"King\",\n },\n {\n \"option\": \"Saitama\",\n },\n {\n \"option\": \"Sonic\",\n }\n ],\n \"correct_answer\": \"Saitama\"\n }\n];\n\nconst updatedData = data.map(datum => {\n const options = datum.options.map(option => {\n if (option.option === datum.correct_answer) {\n return {...option, correct_answer: true};\n } else {\n return {...option, correct_answer: false};\n }\n });\n\n return {...datum, options};\n});\n\nconsole.log(updatedData);\n map() map() map() map()" }, { "answer_id": 74647781, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 2, "selected": true, "text": "Array.map spread let newdata = data.map(d => ({ ...d,\n options: d.options.map(m => ({ ...m,\n correct_answer: m.option == d.correct_answer ? true : false\n }))\n}))\n const data = [{\n \"question\": \"What is the approximate value of mathematical constant e?\",\n \"options\": [{\n \"option\": \"1.41\",\n },\n {\n \"option\": \"1.62\",\n },\n {\n \"option\": \"2.72\",\n },\n {\n \"option\": \"3.14\",\n }\n ],\n \"correct_answer\": \"2.72\"\n },\n {\n \"question\": \"What is the name of the main character of the anime &quot;One-Punch Man&quot;?\",\n \"options\": [{\n \"option\": \"Genos\",\n },\n {\n \"option\": \"King\",\n },\n {\n \"option\": \"Saitama\",\n },\n {\n \"option\": \"Sonic\",\n }\n ],\n \"correct_answer\": \"Saitama\"\n }\n]\n\nlet newdata = data.map(d => ({ ...d,\n options: d.options.map(m => ({ ...m,\n correct_answer: m.option == d.correct_answer ? true : false\n }))\n}))\n\nconsole.log(newdata)" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9710121/" ]
74,647,704
<p>I am making a tick tack toe cli game that takes user imput and prints an updated board. One of the features i want it to have is that it can recognise that there already is a character in the slot that you want to put your piece. right now i have a switch case with the default not changing anything. can i refer back to it or if i should just copy paste it into each case.</p> <pre><code>import java.util.Scanner; public class TickTack { String[][] tickTackToe = {{&quot; &quot;,&quot;|&quot;,&quot; &quot;,&quot;|&quot;,&quot; &quot;}, {&quot;-&quot;,&quot;-&quot;,&quot;-&quot;,&quot;-&quot;,&quot;-&quot;}, {&quot; &quot;,&quot;|&quot;,&quot; &quot;,&quot;|&quot;,&quot; &quot;}, {&quot;-&quot;,&quot;-&quot;,&quot;-&quot;,&quot;-&quot;,&quot;-&quot;}, {&quot; &quot;,&quot;|&quot;,&quot; &quot;,&quot;|&quot;,&quot; &quot;}}; int xCoor = 0, yCoor = 0, counter = 1; //ignore this they do not matter yet int rOne = 0,rTwo = 0, rThree = 0; int cOne = 0, cTwo = 0, cThree = 0; int dOne = 0, dTwo = 0; String x = &quot;&quot;; Scanner in = new Scanner(System.in); public void play() { while (!x.equals(&quot;win&quot;)){ for (int fila = 0; fila &lt; 5; fila++) { for (int columna = 0; columna &lt; 5; columna++) { System.out.print(tickTackToe[fila][columna]); } System.out.println(); } boolean checker = false; while (!checker) { x = in.next(); switch (x) { //first row case &quot;1,1&quot; -&gt; { xCoor = 0; yCoor = 0; checker = true; } case &quot;1,2&quot; -&gt; { xCoor = 0; yCoor = 2; checker = true; } case &quot;1,3&quot; -&gt; { xCoor = 0; yCoor = 4; checker = true; } //second row case &quot;2,1&quot; -&gt; { xCoor = 2; yCoor = 0; checker = true; } case &quot;2,2&quot; -&gt; { xCoor = 2; yCoor = 2; checker = true; } case &quot;2,3&quot; -&gt; { xCoor = 2; yCoor = 4; checker = true; } //third row case &quot;3,1&quot; -&gt; { xCoor = 4; yCoor = 0; checker = true; } case &quot;3,2&quot; -&gt; { xCoor = 4; yCoor = 2; checker = true; } case &quot;3,3&quot; -&gt; { xCoor = 4; yCoor = 4; checker = true; } default -&gt; System.out.println(&quot;that is not a valid option&quot;); } } //check whose turn is it and alocate the piece counter ++; if (counter % 2 == 0){ tickTackToe[yCoor][xCoor] = &quot;x&quot;; }else{ tickTackToe[yCoor][xCoor] = &quot;o&quot;; } } } } </code></pre> <p>i looked at a bunch of switch statement tutorials(w3 schools, geeks for geeks, javapoint) but i didnt find anything</p>
[ { "answer_id": 74648013, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 2, "selected": true, "text": "field already occupied break that is not a valid option" }, { "answer_id": 74649206, "author": "swpalmer", "author_id": 1165724, "author_profile": "https://Stackoverflow.com/users/1165724", "pm_score": 0, "selected": false, "text": "switch (x) {\n//first row\ncase \"1,1\" -> {\n xCoor = 0;\n yCoor = 0;\n checker = true;\n}\ncase \"1,2\" -> {\n xCoor = 0;\n yCoor = 2;\n checker = true;\n}...\n boolean checker = false;\nwhile (!checker) {\n x = in.next().trim();\n String [] parts = x.split(\",\");\n try {\n xCoor = (Integer.parseInt(parts[0]) - 1) * 2;\n yCoor = (Integer.parseInt(parts[1]) - 1) * 2;\n checked = (xCoor >= 0 && xCoor <= 4\n && yCoor >= 0 && yCoor <= 4\n && tickTackToe[yCoor][xCoor].equals(\" \"));\n } catch(IndexOutOfBoundsException | NumberFormatException ex) {\n // fall through with checked still false\n assert checked == false;\n }\n\n if (!checker) {\n System.out.println(\"that is not a valid option\");\n }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573680/" ]
74,647,706
<p>I have some json objects, i want to join all of the objects only in one</p> <p>i have this input</p> <pre><code>a:[{h:1, i:2}] b:[{j:1, k:2}] c:[{l:1, m:2}] </code></pre> <p>i need this output</p> <pre><code>[{type: a, h:1, i:2}, {type: a, o:1, p:2}, {type: b, j:1, k:2}, {type: c, l:1, m:2}] </code></pre> <p>i was trying:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const a = {"a":[{"h":1, "i":2}]} const b = {"b":[{"j":1, "k":2}]} const c = {"c":[{"l":1, "m":2}]} const result = {}; let key; for (key in a) { if(a.hasOwnProperty(key)){ result[key] = a[key]; } } for (key in b) { if(b.hasOwnProperty(key)){ result[key] = b[key]; } } console.log('b', result)</code></pre> </div> </div> </p>
[ { "answer_id": 74647763, "author": "Guido Carugati", "author_id": 13290792, "author_profile": "https://Stackoverflow.com/users/13290792", "pm_score": 1, "selected": false, "text": "const a = [{h: 1, i: 2}];\nconst b = [{j: 1, k: 2}];\nconst c = [{l: 1, m: 2}];\n\nconst result = [].concat(\n a.map(obj => Object.assign({type: \"a\"}, obj)),\n b.map(obj => Object.assign({type: \"b\"}, obj)),\n c.map(obj => Object.assign({type: \"c\"}, obj))\n);\n [\n {type: \"a\", h: 1, i: 2},\n {type: \"b\", j: 1, k: 2},\n {type: \"c\", l: 1, m: 2}\n]\n" }, { "answer_id": 74648560, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "const data = [\n {\"a\":[{\"h\":1, \"i\":2}]},\n {\"b\":[{\"j\":1, \"k\":2}]},\n {\"c\":[{\"l\":1, \"m\":2}]}\n];\n\nconst result = data.map((dataItem) => {\n const key = Object.keys(dataItem)[0];\n const valuesObject = dataItem[key][0];\n return {\n type: key,\n ...valuesObject\n };\n});\n\nconsole.log(result);" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20503335/" ]
74,647,708
<p>I want to create a Chrome extension to get the background image of an HTML element so I added an option in the right-click menu. It worked in Manifest v2 but when I tried to update to Manifest v3 my code did not longer worked. Is there a thing I missed?</p> <p>Here is my <code>manifest.json</code>:</p> <pre><code>{ &quot;description&quot;: &quot;Get background image of an HTML element&quot;, &quot;manifest_version&quot;: 2, &quot;name&quot;: &quot;BackgroundImage get&quot;, &quot;version&quot;: &quot;0.0.0.1&quot;, &quot;homepage_url&quot;: &quot;https://www.example.com&quot;, &quot;icons&quot;: { &quot;48&quot;: &quot;icons/icon48.png&quot; }, &quot;background&quot;: { &quot;scripts&quot;: [&quot;background.js&quot;] }, &quot;permissions&quot;: [ &quot;activeTab&quot;, &quot;contextMenus&quot; ], &quot;browser_action&quot;: { &quot;default_icon&quot;: { &quot;16&quot;: &quot;icons/icon16.png&quot;, &quot;32&quot;: &quot;icons/icon32.png&quot;, &quot;48&quot;: &quot;icons/icon48.png&quot;, &quot;128&quot;: &quot;icons/icon128.png&quot; } } } </code></pre> <p>And here is my <code>background.js</code> file:</p> <pre><code>chrome.contextMenus.create({ title: 'Get Background Image', onclick: function(e){ console.log(&quot;Example action&quot;) } }, function(){}) </code></pre> <p>I tried to edit my <code>manifest.json</code> like that:</p> <pre><code>{ &quot;manifest_version&quot;: 3, &quot;name&quot;: &quot;BackgroundImage get&quot;, &quot;description&quot;: &quot;Get background image of an HTML element&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;icons&quot;: { &quot;16&quot;: &quot;icons/icon16.png&quot;, &quot;32&quot;: &quot;icons/icon32.png&quot;, &quot;48&quot;: &quot;icons/icon48.png&quot;, &quot;128&quot;: &quot;icons/icon128.png&quot; }, &quot;action&quot;: { &quot;default_title&quot;: &quot;Background Image&quot;, &quot;default_popup&quot;: &quot;popup.html&quot; }, &quot;permissions&quot;: [ &quot;contextMenus&quot; ], &quot;background&quot;: { &quot;service_worker&quot;: &quot;background.js&quot; } } </code></pre> <p>But that doesn't work.</p>
[ { "answer_id": 74647830, "author": "geekySRM", "author_id": 7636285, "author_profile": "https://Stackoverflow.com/users/7636285", "pm_score": -1, "selected": false, "text": "background background browser_action background browser_action {\n \"manifest_version\": 3,\n \"name\": \"BackgroundImage get\",\n \"description\": \"Get background image of an HTML element\",\n \"version\": \"0.0.1\",\n \"icons\": {\n \"16\": \"icons/icon16.png\",\n \"32\": \"icons/icon32.png\",\n \"48\": \"icons/icon48.png\",\n \"128\": \"icons/icon128.png\"\n },\n \"action\": {\n \"default_title\": \"Background Image\",\n \"default_popup\": \"popup.html\"\n },\n \"permissions\": [\n \"contextMenus\"\n ],\n \"background\": {\n \"scripts\": [\"background.js\"]\n }\n}\n chrome.contextMenus.create id chrome.contextMenus.create({\n id: \"get-background-image\",\n title: \"Get Background Image\",\n contexts: [\"all\"],\n onclick: function(info, tab) {\n console.log(\"Example action\");\n }\n});\n" }, { "answer_id": 74648099, "author": "Norio Yamamoto", "author_id": 20074043, "author_profile": "https://Stackoverflow.com/users/20074043", "pm_score": 0, "selected": false, "text": "chrome.runtime.onInstalled.addListener(() => {\n chrome.contextMenus.create({\n id: 'hoge',\n title: 'Get Background Image',\n });\n});\n\nchrome.contextMenus.onClicked.addListener((info) => {\n console.log(\"Example action\")\n});\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18661194/" ]
74,647,711
<p>Grammarly is somehow able to put its button on the bottom right of text boxes, as shown in the gif. Moreover, the button moves when the textbox moves.</p> <p>I'm building a chrome extension that puts a similar button on text boxes (bottom-right). I can get hold of the textbox element by listening to <code>focusin</code> event, so this question is about placing a button on that. So far, I'm not able to find the right approach to do that. I'd also prefer to move my button on the left of any existing buttons like Grammarly to avoid overlapping.</p> <p><a href="https://i.stack.imgur.com/QM1QJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QM1QJ.gif" alt="enter image description here" /></a></p>
[ { "answer_id": 74647948, "author": "TrueStoryShort", "author_id": 20117831, "author_profile": "https://Stackoverflow.com/users/20117831", "pm_score": 0, "selected": false, "text": " <div class=\"wrapper\">\n <textarea></textarea>\n <button></button>\n</div>\n .wrapper {\n position: relative;\n width: max-content;\n }\n textarea {\n width: 15rem;\n height: 10rem;\n }\n button {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n width: 1rem;\n height: 1rem;\n }\n const textarea = document.querySelector(\"textarea\");\nconst button = document.querySelector(\"button\");\nfunction setPosition() {\n const left = textarea.offsetLeft;\n const top = textarea.offsetTop;\n const width = textarea.offsetWidth;\n const height = textarea.offsetHeight;\n\n button.setAttribute(\n \"style\",\n \"position: absolute; top:\" +\n (top + height - 30) +\n \"px; left: \" +\n (left + width - 30) +\n \"px;\"\n );\n}\nsetPosition();\n\nnew ResizeObserver(setPosition).observe(textarea);\n" }, { "answer_id": 74647949, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "div textarea #myScrollContainer {\n height: 150px;\n overflow: auto;\n}\n#myTextareaContainer {\n width: 300px;\n position: relative;\n}\n#myTextarea {\n width: 300px;\n}\n#myOverlay {\n position: absolute;\n right: 25px;\n bottom: 10px;\n} <div id=\"myScrollContainer\">\n<div id=\"myTextareaContainer\">\n<form>\n<textarea rows=\"5\" cols=\"50\" id=\"myTextarea\">\nLorem 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.\n</textarea>\n</form>\n<div id=\"myOverlay\">\n<button>Me!</button>\n</div>\n</div>\n.<br />\n(scroll down)<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\nThe end\n</div>" }, { "answer_id": 74648443, "author": "code", "author_id": 15359157, "author_profile": "https://Stackoverflow.com/users/15359157", "pm_score": 1, "selected": false, "text": "position: absolute; right: 8px; bottom: 8px; const OFFSET = 5;\n\nconst button = document.createElement(\"button\");\n\n[...document.getElementsByTagName(\"textarea\")].forEach(textarea => {\n // get the dimensions of each element, then position the buttons accordingly\n const { top, left, height, width } = textarea.getBoundingClientRect();\n const b = button.cloneNode(true);\n document.body.appendChild(b); // it's necessary to first append the element so CSS wil be applied, otherwise the dimensions will be 0\n \n const { width: bWidth, height: bHeight } = b.getBoundingClientRect();\n b.style.top = (\n (\n top + window.scrollY + height\n ) - OFFSET - bHeight\n ) + \"px\";\n b.style.left = (\n (\n left + window.scrollX + width\n ) - OFFSET - bWidth\n ) + \"px\";\n \n // if you want to do stuff with the button relative to that text area\n b.addEventListener(\"click\", () => doSomething(textarea));\n});\n\nfunction doSomething(textarea) {\n console.log(textarea.value);\n} /* just for the demo */\ntextarea {\n display: block;\n}\n\nbutton {\n color: white;\n background-color: lightgreen;\n width: 20px;\n height: 20px;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n box-shadow: 1px 1px 2px 0px rgba(0, 0, 0, 0.3);\n \n /* necessary button CSS: */\n position: absolute;\n}\n\nhtml {\n position: relative;\n} <textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3073272/" ]
74,647,782
<h1>The Question</h1> <p>I'm trying to make a command that shows you the schedule of your class, for that, the user first introduces as an argument its degree and then the class, but every degree has a different number of classes, so I can't show a generic list for all the degrees.</p> <p>The actual code:</p> <pre class="lang-py prettyprint-override"><code>class Ciclos(enum.Enum): ASIX = 1 DAM = 2 class ASIX(enum.Enum): _1A = 1 _1B = 2 _1C = 3 _2A = 4 _2B = 5 class DAM(enum.Enum): _1A = 1 _2A = 2 _2B = 3 @bot.tree.command(name=&quot;schedule&quot;, description=&quot;Shows the schedule of the selected class&quot;) @app_commands.describe(ciclo=&quot;Choose your degree&quot;) @app_commands.describe(clase=&quot;Choose your class&quot;) async def schedule(interaction: discord.Interaction, ciclo: Ciclos, clase: Ciclos.name): await interaction.response.send_message(file=discord.File(f'Media/schedules/schedule{ciclo.name}{clase.name}.png')) </code></pre> <p>This code doesn't work, but I hope it serves to illustrate what I am trying to accomplish. The problematic part is on the function parameters, specifically on <code>clase: Ciclos.name</code>, I don't know how to make it depend on what the user chooses on <code>ciclo: Ciclos</code>.</p> <h1>What I've tried</h1> <p>I've tried to put these expressions:</p> <p><code>clase: {Ciclos.name}</code> I get -&gt; AtributeError: name</p> <p><code>clase: Ciclos.name</code> I get -&gt; AtributeError: name</p> <p><code>clase: ciclo</code> I get -&gt; NameError: name 'ciclo' is not defined. Did you mean: 'Ciclos'?<br /> No, I didn't mean that.</p> <h1>Expected behavior</h1> <p>The expected result is this:<br /> <a href="https://i.stack.imgur.com/491V5.png" rel="nofollow noreferrer">class ASIX example</a><br /> <a href="https://i.stack.imgur.com/xkeN1.png" rel="nofollow noreferrer">class DAM example</a></p> <p>In order to send the schedule image corresponding to each class:</p> <pre class="lang-py prettyprint-override"><code>await interaction.response.send_message(file=discord.File(f'Media/schedules/schedule{ciclo.name}{clase.name}.png')) </code></pre> <p>So I get file names like: &quot;scheduleASIX_1A&quot; &quot;scheduleDAM_2A&quot;</p>
[ { "answer_id": 74647948, "author": "TrueStoryShort", "author_id": 20117831, "author_profile": "https://Stackoverflow.com/users/20117831", "pm_score": 0, "selected": false, "text": " <div class=\"wrapper\">\n <textarea></textarea>\n <button></button>\n</div>\n .wrapper {\n position: relative;\n width: max-content;\n }\n textarea {\n width: 15rem;\n height: 10rem;\n }\n button {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n width: 1rem;\n height: 1rem;\n }\n const textarea = document.querySelector(\"textarea\");\nconst button = document.querySelector(\"button\");\nfunction setPosition() {\n const left = textarea.offsetLeft;\n const top = textarea.offsetTop;\n const width = textarea.offsetWidth;\n const height = textarea.offsetHeight;\n\n button.setAttribute(\n \"style\",\n \"position: absolute; top:\" +\n (top + height - 30) +\n \"px; left: \" +\n (left + width - 30) +\n \"px;\"\n );\n}\nsetPosition();\n\nnew ResizeObserver(setPosition).observe(textarea);\n" }, { "answer_id": 74647949, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "div textarea #myScrollContainer {\n height: 150px;\n overflow: auto;\n}\n#myTextareaContainer {\n width: 300px;\n position: relative;\n}\n#myTextarea {\n width: 300px;\n}\n#myOverlay {\n position: absolute;\n right: 25px;\n bottom: 10px;\n} <div id=\"myScrollContainer\">\n<div id=\"myTextareaContainer\">\n<form>\n<textarea rows=\"5\" cols=\"50\" id=\"myTextarea\">\nLorem 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.\n</textarea>\n</form>\n<div id=\"myOverlay\">\n<button>Me!</button>\n</div>\n</div>\n.<br />\n(scroll down)<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\nThe end\n</div>" }, { "answer_id": 74648443, "author": "code", "author_id": 15359157, "author_profile": "https://Stackoverflow.com/users/15359157", "pm_score": 1, "selected": false, "text": "position: absolute; right: 8px; bottom: 8px; const OFFSET = 5;\n\nconst button = document.createElement(\"button\");\n\n[...document.getElementsByTagName(\"textarea\")].forEach(textarea => {\n // get the dimensions of each element, then position the buttons accordingly\n const { top, left, height, width } = textarea.getBoundingClientRect();\n const b = button.cloneNode(true);\n document.body.appendChild(b); // it's necessary to first append the element so CSS wil be applied, otherwise the dimensions will be 0\n \n const { width: bWidth, height: bHeight } = b.getBoundingClientRect();\n b.style.top = (\n (\n top + window.scrollY + height\n ) - OFFSET - bHeight\n ) + \"px\";\n b.style.left = (\n (\n left + window.scrollX + width\n ) - OFFSET - bWidth\n ) + \"px\";\n \n // if you want to do stuff with the button relative to that text area\n b.addEventListener(\"click\", () => doSomething(textarea));\n});\n\nfunction doSomething(textarea) {\n console.log(textarea.value);\n} /* just for the demo */\ntextarea {\n display: block;\n}\n\nbutton {\n color: white;\n background-color: lightgreen;\n width: 20px;\n height: 20px;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n box-shadow: 1px 1px 2px 0px rgba(0, 0, 0, 0.3);\n \n /* necessary button CSS: */\n position: absolute;\n}\n\nhtml {\n position: relative;\n} <textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659527/" ]
74,647,796
<p>Here's my contract.</p> <pre><code>// SPDX-License-Identifier: MIT pragma solidity &gt;= 0.7.3; contract terceiroTest { // We pass and old String, a new string and when this event is // broadcast everybody is able to see that the even happened. // and see the strings exposed too. event UpdatedMessages(string oldStr, string newStr); string public message; // When this contract is deployed we require an argument passed called initMessasge constructor (string memory initMessage) { message = initMessage; } function update(string memory newMessage) public { string memory oldMsg = message; message = newMessage; emit UpdatedMessages(oldMsg, newMessage); } } </code></pre> <p>and it gives me the error:</p> <p><a href="https://i.stack.imgur.com/K6nzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K6nzm.png" alt="" /></a></p> <p>I've tried to find any kind of description about this error, even changed solidity's version. I'm studying about smartcontracts still, if someone having or had the same error I would apretiate for enlighting me. Thanks.</p>
[ { "answer_id": 74647948, "author": "TrueStoryShort", "author_id": 20117831, "author_profile": "https://Stackoverflow.com/users/20117831", "pm_score": 0, "selected": false, "text": " <div class=\"wrapper\">\n <textarea></textarea>\n <button></button>\n</div>\n .wrapper {\n position: relative;\n width: max-content;\n }\n textarea {\n width: 15rem;\n height: 10rem;\n }\n button {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n width: 1rem;\n height: 1rem;\n }\n const textarea = document.querySelector(\"textarea\");\nconst button = document.querySelector(\"button\");\nfunction setPosition() {\n const left = textarea.offsetLeft;\n const top = textarea.offsetTop;\n const width = textarea.offsetWidth;\n const height = textarea.offsetHeight;\n\n button.setAttribute(\n \"style\",\n \"position: absolute; top:\" +\n (top + height - 30) +\n \"px; left: \" +\n (left + width - 30) +\n \"px;\"\n );\n}\nsetPosition();\n\nnew ResizeObserver(setPosition).observe(textarea);\n" }, { "answer_id": 74647949, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": "div textarea #myScrollContainer {\n height: 150px;\n overflow: auto;\n}\n#myTextareaContainer {\n width: 300px;\n position: relative;\n}\n#myTextarea {\n width: 300px;\n}\n#myOverlay {\n position: absolute;\n right: 25px;\n bottom: 10px;\n} <div id=\"myScrollContainer\">\n<div id=\"myTextareaContainer\">\n<form>\n<textarea rows=\"5\" cols=\"50\" id=\"myTextarea\">\nLorem 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.\n</textarea>\n</form>\n<div id=\"myOverlay\">\n<button>Me!</button>\n</div>\n</div>\n.<br />\n(scroll down)<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\n.<br />\nThe end\n</div>" }, { "answer_id": 74648443, "author": "code", "author_id": 15359157, "author_profile": "https://Stackoverflow.com/users/15359157", "pm_score": 1, "selected": false, "text": "position: absolute; right: 8px; bottom: 8px; const OFFSET = 5;\n\nconst button = document.createElement(\"button\");\n\n[...document.getElementsByTagName(\"textarea\")].forEach(textarea => {\n // get the dimensions of each element, then position the buttons accordingly\n const { top, left, height, width } = textarea.getBoundingClientRect();\n const b = button.cloneNode(true);\n document.body.appendChild(b); // it's necessary to first append the element so CSS wil be applied, otherwise the dimensions will be 0\n \n const { width: bWidth, height: bHeight } = b.getBoundingClientRect();\n b.style.top = (\n (\n top + window.scrollY + height\n ) - OFFSET - bHeight\n ) + \"px\";\n b.style.left = (\n (\n left + window.scrollX + width\n ) - OFFSET - bWidth\n ) + \"px\";\n \n // if you want to do stuff with the button relative to that text area\n b.addEventListener(\"click\", () => doSomething(textarea));\n});\n\nfunction doSomething(textarea) {\n console.log(textarea.value);\n} /* just for the demo */\ntextarea {\n display: block;\n}\n\nbutton {\n color: white;\n background-color: lightgreen;\n width: 20px;\n height: 20px;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n box-shadow: 1px 1px 2px 0px rgba(0, 0, 0, 0.3);\n \n /* necessary button CSS: */\n position: absolute;\n}\n\nhtml {\n position: relative;\n} <textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>\n<textarea>text...</textarea>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734496/" ]
74,647,815
<p>I have a multi-index data set with 100 cases, and each case has 5 questions. Each question was scored by 2 raters.</p> <pre><code>case question rater1 rater2 1 1 1 1 1 2 1 0 1 3 1 1 1 4 1 1 1 5 0 0 2 1 0 1 2 2 1 1 2 3 1 1 2 4 1 0 2 5 0 0 3 1 0 0 3 2 1 0 3 3 1 1 3 4 1 1 3 5 0 1 ... </code></pre> <p>I want to sum question 1, 2, 3 in each case as A, and question 4, 5 in each case as B. Then insert the value at the end of each case, such as</p> <pre><code>case question rater1 rater2 1 1 1 1 1 2 1 0 1 3 1 1 1 4 1 1 1 5 0 0 1 A 3 2 1 B 1 1 2 1 0 1 2 2 1 1 2 3 1 1 2 4 1 0 2 5 0 0 2 A 2 3 2 B 1 0 3 1 0 0 3 2 1 0 3 3 1 1 3 4 1 1 3 5 0 1 3 A 2 1 3 B 1 2 ... </code></pre> <p>I am unsure how to achieve it.</p>
[ { "answer_id": 74647926, "author": "MrFlick", "author_id": 2372064, "author_profile": "https://Stackoverflow.com/users/2372064", "pm_score": 3, "selected": true, "text": "library(dplyr)\ndd %>% \n group_by(case, grp = case_when(question %in% 1:3~\"A\", question %in% 4:5 ~ \"B\")) %>% \n summarize(across(-question, sum)) %>% \n ungroup() %>% \n rename(question = grp) %>% \n bind_rows(mutate(dd, question = as.character(question))) %>% \n arrange(case, question)\n" }, { "answer_id": 74648435, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 0, "selected": false, "text": "data.table library(data.table)\n\ndt[\n ,.(\n question = c(question, \"A\", \"B\"),\n rater1 = c(rater1, sum(rater1[1:3]), sum(rater1[4:5])),\n rater2 = c(rater2, sum(rater2[1:3]), sum(rater2[4:5]))\n ), case\n][1:15]\n#> case question rater1 rater2\n#> 1: 1 1 1 0\n#> 2: 1 2 1 1\n#> 3: 1 3 0 0\n#> 4: 1 4 0 0\n#> 5: 1 5 0 1\n#> 6: 1 A 2 1\n#> 7: 1 B 0 1\n#> 8: 2 1 0 0\n#> 9: 2 2 0 1\n#> 10: 2 3 0 1\n#> 11: 2 4 1 1\n#> 12: 2 5 0 0\n#> 13: 2 A 0 2\n#> 14: 2 B 1 1\n#> 15: 3 1 0 0\n dt <- data.table(\n case = rep(1:100, each = 5),\n question = rep(1:5, 100),\n rater1 = sample(0:1, 500, 1),\n rater2 = sample(0:1, 500, 1)\n)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20081864/" ]
74,647,839
<p>I am trying to make a smooth animation of lines that move over time. Here is some example data <strong>edited to add <code>x</code> for completeness as I forgot that initially, apologies</strong>:</p> <pre><code>x &lt;- c( 0, 10, 19, 27, 35, 41, 48, 52, 55, 56 ) test.data &lt;- data.frame( depth = rep( seq( 1, 10 ), 10 ), time = rep( 1:10, times = 1, each = 10 ), temp = rep( x, 10 ) + rep( 0:9, each = length( x ) ) ) </code></pre> <p>Now arrange the data so that <code>geom_path</code> links the data correctly</p> <pre><code> arrange( test.data, depth, time ) ## arrange by depth for plotting </code></pre> <p>Now make the static plot with all the data shown:</p> <pre><code>ggplot( test.data, aes( x = temp, y = depth, group = time ) ) + ylim( 10, 0 ) + labs( y = &quot;Depth (km)&quot;, x = &quot;Temp (C)&quot;, color = &quot;Time&quot;) + geom_path( aes( color = time ) ) </code></pre> <p>Here is the static plot: <a href="https://i.stack.imgur.com/f7EXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f7EXm.png" alt="enter image description here" /></a></p> <p>Now do the animation using <code>gganimate</code></p> <pre><code>library(gganimate) plot.for.gif &lt;- test.data %&gt;% ggplot( aes( x = temp, y = depth, group = time ) ) + ylim( 10, 0 ) + labs( y = &quot;Depth (km)&quot;, x = &quot;Temp (C)&quot;, color = &quot;Time (Ma)&quot;) + geom_path( aes( color = time ) ) plot.animation = plot.for.gif + transition_time( time = time ) + labs( subtitle = &quot;Time (Ma): {frame_time}&quot; ) + shadow_mark( past = TRUE, future = FALSE, exclude_layer = NULL ) animate( plot.animation, height = 1400, width = 800, fps = 10, duration = 15, res = 150 ) </code></pre> <p>This is the resulting plot:</p> <p><a href="https://i.stack.imgur.com/Q72tq.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q72tq.gif" alt="enter image description here" /></a></p> <p>The problem is that the lines do not blend into one another, they jump from one frame to another. I'd like to get them to move smoothly between discrete frames.</p> <p>I've tried playing with <code>shadow_wake()</code> and <code>enter_fade()</code> but neither work. It seems like <code>gganimate()</code> doesn't smooth lines connecting datapoints well, but I am perhaps missing an easy fix.</p> <p>Any help would be appreciated!</p>
[ { "answer_id": 74647926, "author": "MrFlick", "author_id": 2372064, "author_profile": "https://Stackoverflow.com/users/2372064", "pm_score": 3, "selected": true, "text": "library(dplyr)\ndd %>% \n group_by(case, grp = case_when(question %in% 1:3~\"A\", question %in% 4:5 ~ \"B\")) %>% \n summarize(across(-question, sum)) %>% \n ungroup() %>% \n rename(question = grp) %>% \n bind_rows(mutate(dd, question = as.character(question))) %>% \n arrange(case, question)\n" }, { "answer_id": 74648435, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 0, "selected": false, "text": "data.table library(data.table)\n\ndt[\n ,.(\n question = c(question, \"A\", \"B\"),\n rater1 = c(rater1, sum(rater1[1:3]), sum(rater1[4:5])),\n rater2 = c(rater2, sum(rater2[1:3]), sum(rater2[4:5]))\n ), case\n][1:15]\n#> case question rater1 rater2\n#> 1: 1 1 1 0\n#> 2: 1 2 1 1\n#> 3: 1 3 0 0\n#> 4: 1 4 0 0\n#> 5: 1 5 0 1\n#> 6: 1 A 2 1\n#> 7: 1 B 0 1\n#> 8: 2 1 0 0\n#> 9: 2 2 0 1\n#> 10: 2 3 0 1\n#> 11: 2 4 1 1\n#> 12: 2 5 0 0\n#> 13: 2 A 0 2\n#> 14: 2 B 1 1\n#> 15: 3 1 0 0\n dt <- data.table(\n case = rep(1:100, each = 5),\n question = rep(1:5, 100),\n rater1 = sample(0:1, 500, 1),\n rater2 = sample(0:1, 500, 1)\n)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4360613/" ]
74,647,845
<p>I need to have a template class where each object adds itself to a vector and based on the template type parameter(allowed only: string, int, float) add to the corresponding container. I need a way to have compile time checks for the type and based on the check add to the corresponding container and if the type is not one of the allowed types compile time error should be emitted. Example: code</p> <pre><code>vector&lt;myClass&lt;int&gt;*&gt; intVec; vector&lt;myClass&lt;float&gt;*&gt; floatVec; vector&lt;myClass&lt;string&gt;*&gt; stringVec; template&lt;typename T&gt; struct myClass { myClass() { /*pseudo code if(T == int) { intVec.push_back(this); } else if(T == float) { floatVec.push_back(this); } else if(T == string){ stringVec.push_back(this); } else { // error } */ } T value; } </code></pre> <p>How can I achieve this ?</p>
[ { "answer_id": 74648074, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "if constexpr std::is_same_v #include <type_traits>\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n if constexpr (std::is_same_v<T, int>) {\n m_intVec.push_back(this);\n }\n else if constexpr (std::is_same_v<T, float>) {\n m_floatVec.push_back(this);\n }\n else if constexpr (std::is_same_v<T, std::string>){\n m_stringVec.push_back(this);\n }\n else {\n // error\n }\n }\n \n T value;\n};\n // via specialization\n\ntemplate<typename T>\nstruct myClass\n{\n};\n\ntemplate<>\nstruct myClass<int>\n{\n myClass()\n {\n m_intVec.push_back(this);\n }\n\n int value;\n};\n\ntemplate<>\nstruct myClass<float>\n{\n myClass()\n {\n m_floatVec.push_back(this);\n }\n\n float value;\n};\n\ntemplate<>\nstruct myClass<std::string>\n{\n myClass()\n {\n m_stringVec.push_back(this);\n }\n\n std::string value;\n};\n // via SFINAE\n\n#include <type_traits>\n\ntemplate<typename T>\nstruct myClass\n{\n template<typename U = T, std::enable_if<std::is_same<U, int>::value, int>::type = 0>\n myClass()\n {\n m_intVec.push_back(this);\n }\n\n template<typename U = T, std::enable_if<std::is_same<U, float>::value, int>::type = 0>\n myClass()\n {\n m_floatVec.push_back(this);\n }\n\n template<typename U = T, std::enable_if<std::is_same<U, std::string>::value, int>::type = 0>\n myClass()\n {\n m_stringVec.push_back(this);\n }\n\n T value;\n};\n" }, { "answer_id": 74648132, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 2, "selected": true, "text": "template<typename T>\nstruct myClass;\n\ninline std::vector<myClass<int>*> intVec;\ninline std::vector<myClass<float>*> floatVec;\ninline std::vector<myClass<std::string>*> stringVec;\n\ntemplate<typename T>\nvoid add(myClass<T>*);\n\ntemplate<>\nvoid add(myClass<int>* p) {\n intVec.push_back(p);\n}\n\ntemplate<>\nvoid add(myClass<float>* p) {\n floatVec.push_back(p);\n}\n\ntemplate<>\nvoid add(myClass<std::string>* p) {\n stringVec.push_back(p);\n}\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n add(this);\n }\n\n T value;\n};\n" }, { "answer_id": 74648727, "author": "apple apple", "author_id": 5980430, "author_profile": "https://Stackoverflow.com/users/5980430", "pm_score": 1, "selected": false, "text": "template<typename T>\nstruct myClass;\n\ninline std::vector<myClass<int>*> intVec;\ninline std::vector<myClass<float>*> floatVec;\ninline std::vector<myClass<std::string>*> stringVec;\n\n/* optional\ntemplate<typename T>\nconstexpr bool always_false = false;\n\ntemplate<typename T>\nvoid add(myClass<T>*) {\n static_assert(always_false<T>,\"unsupported T\");\n}\n*/\n\nvoid add(myClass<int>* p) {\n intVec.push_back(p);\n}\n\nvoid add(myClass<float>* p) {\n floatVec.push_back(p);\n}\n\nvoid add(myClass<std::string>* p) {\n stringVec.push_back(p);\n}\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n add(this);\n }\n\n T value;\n};\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11340026/" ]
74,647,864
<p>I am creating a scheduled delivery system.</p> <p>I put together the following script that counts the quantity of specific days of the week between two dates in dd/mm/yyyy format (UK).</p> <pre><code>var date0 = &quot;01/02/2021&quot;; var date1 = &quot;31/01/2022&quot;; var dayList = [1]; // Monday based on Sunday being 0 var test = countDays(dayList,parseDate(date0),parseDate(date1)); alert(test); function parseDate(str) { var dmy = str.split('/'); return new Date(+dmy[2],dmy[1] - 1,+dmy[0]); } function countDays(days,fromDate,toDate) { var ndays = 1 + Math.round((toDate-fromDate)/(24*3600*1000)); var sum = function(a,b) { return a + Math.floor((ndays+(fromDate.getDay()+6-b)%7)/7); }; return days.reduce(sum,0); } </code></pre> <p>I this particular instance the <code>dayList=[1]</code> is 'Monday'. The script counts the number of Monday's between the two dates and we get the result 53 (because it happens that 01/02/2021 falls on a Monday).</p> <p>This would works great if I want to find out how many Mondays were between two dates based on a rolling week.</p> <p>How can I modify this to allow for a rolling fortnight?</p> <p>For example I might want to find out how many weekly Mondays and alternate Fridays there are based on a rolling fortnight, not a rolling week. I have to allow for a mixture of weekly and fortnightly deliveries.</p> <p>For example: In this case the client wants a delivery every Monday and an extra delivery every other Friday.</p> <pre><code>Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri x x x </code></pre> <p>Schedules vary enormously. The rolling fortnight starts on the start date provided by the user.</p> <p>What I am looking for is the total number of days between a start and end date but I am struggling with factoring the 'rolling fortnight' aspect of this.</p>
[ { "answer_id": 74648074, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": false, "text": "if constexpr std::is_same_v #include <type_traits>\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n if constexpr (std::is_same_v<T, int>) {\n m_intVec.push_back(this);\n }\n else if constexpr (std::is_same_v<T, float>) {\n m_floatVec.push_back(this);\n }\n else if constexpr (std::is_same_v<T, std::string>){\n m_stringVec.push_back(this);\n }\n else {\n // error\n }\n }\n \n T value;\n};\n // via specialization\n\ntemplate<typename T>\nstruct myClass\n{\n};\n\ntemplate<>\nstruct myClass<int>\n{\n myClass()\n {\n m_intVec.push_back(this);\n }\n\n int value;\n};\n\ntemplate<>\nstruct myClass<float>\n{\n myClass()\n {\n m_floatVec.push_back(this);\n }\n\n float value;\n};\n\ntemplate<>\nstruct myClass<std::string>\n{\n myClass()\n {\n m_stringVec.push_back(this);\n }\n\n std::string value;\n};\n // via SFINAE\n\n#include <type_traits>\n\ntemplate<typename T>\nstruct myClass\n{\n template<typename U = T, std::enable_if<std::is_same<U, int>::value, int>::type = 0>\n myClass()\n {\n m_intVec.push_back(this);\n }\n\n template<typename U = T, std::enable_if<std::is_same<U, float>::value, int>::type = 0>\n myClass()\n {\n m_floatVec.push_back(this);\n }\n\n template<typename U = T, std::enable_if<std::is_same<U, std::string>::value, int>::type = 0>\n myClass()\n {\n m_stringVec.push_back(this);\n }\n\n T value;\n};\n" }, { "answer_id": 74648132, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 2, "selected": true, "text": "template<typename T>\nstruct myClass;\n\ninline std::vector<myClass<int>*> intVec;\ninline std::vector<myClass<float>*> floatVec;\ninline std::vector<myClass<std::string>*> stringVec;\n\ntemplate<typename T>\nvoid add(myClass<T>*);\n\ntemplate<>\nvoid add(myClass<int>* p) {\n intVec.push_back(p);\n}\n\ntemplate<>\nvoid add(myClass<float>* p) {\n floatVec.push_back(p);\n}\n\ntemplate<>\nvoid add(myClass<std::string>* p) {\n stringVec.push_back(p);\n}\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n add(this);\n }\n\n T value;\n};\n" }, { "answer_id": 74648727, "author": "apple apple", "author_id": 5980430, "author_profile": "https://Stackoverflow.com/users/5980430", "pm_score": 1, "selected": false, "text": "template<typename T>\nstruct myClass;\n\ninline std::vector<myClass<int>*> intVec;\ninline std::vector<myClass<float>*> floatVec;\ninline std::vector<myClass<std::string>*> stringVec;\n\n/* optional\ntemplate<typename T>\nconstexpr bool always_false = false;\n\ntemplate<typename T>\nvoid add(myClass<T>*) {\n static_assert(always_false<T>,\"unsupported T\");\n}\n*/\n\nvoid add(myClass<int>* p) {\n intVec.push_back(p);\n}\n\nvoid add(myClass<float>* p) {\n floatVec.push_back(p);\n}\n\nvoid add(myClass<std::string>* p) {\n stringVec.push_back(p);\n}\n\ntemplate<typename T>\nstruct myClass\n{\n myClass()\n {\n add(this);\n }\n\n T value;\n};\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18745848/" ]
74,647,866
<p>I need my code to stop and wait until the next day. The time does not matter, I just need it to continue when the date changes.</p> <pre><code>currentDate = datetime.datetime.now() future = datetime.datetime(currentDate.year, currentDate.month, (currentDate.day + 1)) time.sleep((future-currentDate).total_seconds()) </code></pre> <p>The code pauses but does not continue after</p>
[ { "answer_id": 74647993, "author": "Lewis Morris", "author_id": 3348264, "author_profile": "https://Stackoverflow.com/users/3348264", "pm_score": 2, "selected": false, "text": "import datetime\nimport time\n def loop_until_tomorrow():\n \"\"\" Will use a while loop to iterate until tomorrow \"\"\"\n\n #get current date\n currentDate = datetime.datetime.now().date()\n # loop attempts \n times = 0 \n # this will loop infiniatly if condition is never met \n while True:\n # increment by one each iteration\n times += 1\n #get date now\n now = datetime.datetime.now().date()\n if currentDate != now:\n # return when condition met \n print(\"\\nDay has changed\")\n return \n else: \n # print attempts and sleep here to avoid program hanging \n print(f\"Attempt: {times}\".ljust(13) + \" - Not tomorrow yet!\", end=\"\\r\")\n time.sleep(5)\n def sleep_until_tomorrow():\n\n \"\"\"wait till tomorrow using time.sleep\"\"\"\n \n #get date now\n now = datetime.datetime.now()\n #get tomorrows date \n tomorrow_date = now.date() + datetime.timedelta(days=1)\n #set to datetime\n tomorrow_datetime = datetime.datetime(year=tomorrow_date.year, month=tomorrow_date.month, day=tomorrow_date.day, hour=0, minute=0, second=0)\n #get seconds\n seconds_til_tomorrow = (tomorrow_datetime-now).total_seconds()\n #sleep\n time.sleep(seconds_til_tomorrow)\n" }, { "answer_id": 74648469, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "from schedule import every, repeat, run_pending\nimport time\n\n#just to give you the idea on how to implement the module. \n@repeat(every().day.at(\"7:15\"))\ndef remind_me_its_a_new_day():\n print(\"Hey there it's a new day! \")\n\nwhile True:\n run_pending()\n time.sleep(1)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20079494/" ]
74,647,873
<p>I am doing <code>printf(&quot;\t%d&quot;, i)</code> in a for-loop to print column labels for a table.</p> <p>Before the loop, I do <code>printf(&quot;some string ===&gt;&quot;)</code>.</p> <p>An issue I notice is that for example, if I do <code>printf(&quot;some string===&gt;&quot;</code> (one character less), the first tab from the loop doesn't display correctly in my Ubuntu 20.04 terminal.</p> <p>Why is this?</p> <pre><code>#include &lt;stdio.h&gt; int main() { printf(&quot;some string ===&gt;&quot;); for (int j = 1; j &lt;= 9; ++j) printf(&quot;\t%d&quot;, j); printf(&quot;\n&quot;); printf(&quot;some string===&gt;&quot;); for (int j = 1; j &lt;= 9; ++j) printf(&quot;\t%d&quot;, j); printf(&quot;\n&quot;); } </code></pre> <p>Output in my Ubuntu 20.04 terminal <a href="https://i.stack.imgur.com/9hw8V.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9hw8V.jpg" alt="Output in my Ubuntu 20.04 terminal" /></a></p>
[ { "answer_id": 74647993, "author": "Lewis Morris", "author_id": 3348264, "author_profile": "https://Stackoverflow.com/users/3348264", "pm_score": 2, "selected": false, "text": "import datetime\nimport time\n def loop_until_tomorrow():\n \"\"\" Will use a while loop to iterate until tomorrow \"\"\"\n\n #get current date\n currentDate = datetime.datetime.now().date()\n # loop attempts \n times = 0 \n # this will loop infiniatly if condition is never met \n while True:\n # increment by one each iteration\n times += 1\n #get date now\n now = datetime.datetime.now().date()\n if currentDate != now:\n # return when condition met \n print(\"\\nDay has changed\")\n return \n else: \n # print attempts and sleep here to avoid program hanging \n print(f\"Attempt: {times}\".ljust(13) + \" - Not tomorrow yet!\", end=\"\\r\")\n time.sleep(5)\n def sleep_until_tomorrow():\n\n \"\"\"wait till tomorrow using time.sleep\"\"\"\n \n #get date now\n now = datetime.datetime.now()\n #get tomorrows date \n tomorrow_date = now.date() + datetime.timedelta(days=1)\n #set to datetime\n tomorrow_datetime = datetime.datetime(year=tomorrow_date.year, month=tomorrow_date.month, day=tomorrow_date.day, hour=0, minute=0, second=0)\n #get seconds\n seconds_til_tomorrow = (tomorrow_datetime-now).total_seconds()\n #sleep\n time.sleep(seconds_til_tomorrow)\n" }, { "answer_id": 74648469, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "from schedule import every, repeat, run_pending\nimport time\n\n#just to give you the idea on how to implement the module. \n@repeat(every().day.at(\"7:15\"))\ndef remind_me_its_a_new_day():\n print(\"Hey there it's a new day! \")\n\nwhile True:\n run_pending()\n time.sleep(1)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17576954/" ]
74,647,878
<p>i have an array <code>[&quot;academy&quot;]</code> and i need count chars from the string in the array.</p> <p>output:</p> <pre><code>a:2 c:1 d:1 e:1 m:1 y:1 </code></pre> <p>like this</p> <p>i tried two for loops</p> <pre><code>function sumChar(arr){ let alph=&quot;abcdefghijklmnopqrstuvxyz&quot;; let count=0; for (const iterator of arr) { for(let i=0; i&lt;alph.length; i++){ if(iterator.charAt(i)==alph[i]){ count++; console.log(`${iterator[i]} : ${count}`); count=0; } } } } console.log(sumChar([&quot;abdulloh&quot;])); </code></pre> <p>it works wrong</p> <p>Output:</p> <pre><code>a : 1 b : 1 h : 1 undefined </code></pre>
[ { "answer_id": 74648048, "author": "st3phhays", "author_id": 10430540, "author_profile": "https://Stackoverflow.com/users/10430540", "pm_score": 1, "selected": false, "text": "// create an empty object to store the character counts\nvar charCounts = {};\n\n// get the string from the array\nvar str = [\"academy\"][0];\n\n// iterate through the string and count the occurrences of each character\nfor (var i = 0; i < str.length; i++) {\n var char = str[i];\n if (charCounts[char] === undefined) {\n // if the character has not been encountered before, set its count to 1\n charCounts[char] = 1;\n } else {\n // if the character has been encountered before, increment its count by 1\n charCounts[char]++;\n }\n}\n\n// print the character counts\nfor (var char in charCounts) {\n console.log(char + \": \" + charCounts[char]);\n}" }, { "answer_id": 74648207, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 0, "selected": false, "text": "[...new Set(word.split(''))] .map ({ [m]: word.split(m).length - 1 }) object key word.split(m).length - 1 const countLetters = word => (\n [...new Set(word.split(''))].map(m => ({\n [m]: word.split(m).length - 1\n })))\n\nconsole.log(countLetters(\"academy\"))" }, { "answer_id": 74648464, "author": "Sufiyan Siraj", "author_id": 8185592, "author_profile": "https://Stackoverflow.com/users/8185592", "pm_score": 0, "selected": false, "text": "word: string = 'abcdefghijklkmnopqrstuvwxyzgg';\ncharsArrayWithCount = {};\nCheckWordCount(): void {\n for(var i = 0;i < this.word.length; i++){\n if(this.charsArrayWithCount[this.word[i]] === undefined){\n this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);\n }\n }\n console.log(this.charsArrayWithCount);\n}\ncharCount(string, char) {\n let expression = new RegExp(char, \"g\");\n return string.match(expression).length;\n}\n" }, { "answer_id": 74657220, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "Array.reduce() const arr = [\"academy\"];\n\nconst res = arr.map(word => {\n return word.split('').reduce((obj, cur) => {\n obj[cur] = obj[cur] ? obj[cur] + 1 : 1\n return obj;\n }, {});\n});\n\nconsole.log(res);" }, { "answer_id": 74660173, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 0, "selected": false, "text": "const input = 'academy';\n\nconst res = {};\n\ninput.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);\n\nconsole.log(res);" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660069/" ]
74,647,892
<p>I have a SQL table containing timestamps of the following format:</p> <p><code>2022-02-07 12:57:45.000</code></p> <p>In SQL Server, you can convert this to a floating point date serial number (days since 1900-01-01):</p> <pre class="lang-sql prettyprint-override"><code>select convert(float, my_timestamp_field) as float_serial_number </code></pre> <p>which yields an output of:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>float_serial_number</th> </tr> </thead> <tbody> <tr> <td>44597.5401041667</td> </tr> </tbody> </table> </div> <p>I am trying to get the same output in Snowflake, but cant figure out how to return a float. This is as close as I have gotten:</p> <pre class="lang-sql prettyprint-override"><code>select datediff(day, '1900-01-01', '2022-02-07 12:57:45.000') as integer_only, timestampdiff(day, '1900-01-01', '2022-02-07 12:57:45.000') as same_as_above </code></pre> <p>which yields an output of:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>integer_only</th> <th>same_as_above</th> </tr> </thead> <tbody> <tr> <td>44,597</td> <td>44,597</td> </tr> </tbody> </table> </div> <p>The output I need in Snowflake (this takes the time into account where 12pm = 0.5):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>desired_Snowflake_output</th> </tr> </thead> <tbody> <tr> <td>44597.5401041667</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74648562, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 2, "selected": false, "text": "datediff set mydate='2022-02-07 12:57:45.000'::timestamp;\n\nselect datediff(seconds, '1900-01-01', $mydate)::float/86400\n" }, { "answer_id": 74658309, "author": "John", "author_id": 3833426, "author_profile": "https://Stackoverflow.com/users/3833426", "pm_score": 1, "selected": false, "text": "create or replace function dayfloat_ts(ts TIMESTAMP)\nreturns float\nlanguage sql\nas\n$$\n (datediff(day, '1900-01-01', TS)::float +\n (datediff(nanoseconds, '1900-01-01', TS)::float -\n datediff(nanoseconds, '1900-01-01', date_trunc(day, TS)))::float / 86400000000000::float)\n$$;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15417368/" ]
74,647,915
<p>I am using a printer d11 and trying to connect it to my device using Bluetooth. But I am encountering this error: Need android. permission.BLUETOOTH_SCAN permission for AttributionSource.</p> <p>I have already added the permissions and all but I'm still having errors, it points me out that the problem is here.</p> <pre><code>@SuppressLint(&quot;MissingPermission&quot;) private fun searchForPrinters() { val bluetoothManager = requireActivity().getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothAdapter = bluetoothManager.adapter if (bluetoothAdapter == null) { AlertsUtil.showBaseOkWarningDialog( requireActivity(), getString(R.string.bluetooth_not_available), &quot;&quot; ) return } else if (!bluetoothAdapter!!.isEnabled) { askToEnableBluetooth() return } // The line that causes the problem if (bluetoothAdapter?.isDiscovering == true) { Logger.log(TAG, &quot;cancel start discovery&quot;) bluetoothAdapter?.cancelDiscovery() } initBluetoothScanBroadcastReceiver() bluetoothAdapter?.startDiscovery() } </code></pre>
[ { "answer_id": 74648562, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 2, "selected": false, "text": "datediff set mydate='2022-02-07 12:57:45.000'::timestamp;\n\nselect datediff(seconds, '1900-01-01', $mydate)::float/86400\n" }, { "answer_id": 74658309, "author": "John", "author_id": 3833426, "author_profile": "https://Stackoverflow.com/users/3833426", "pm_score": 1, "selected": false, "text": "create or replace function dayfloat_ts(ts TIMESTAMP)\nreturns float\nlanguage sql\nas\n$$\n (datediff(day, '1900-01-01', TS)::float +\n (datediff(nanoseconds, '1900-01-01', TS)::float -\n datediff(nanoseconds, '1900-01-01', date_trunc(day, TS)))::float / 86400000000000::float)\n$$;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16588587/" ]
74,647,937
<p>I'm trying to render an infinite scroll component and update its data with newly fetched news upon scrolling to the end of it. It works on the first scroll, but gets stuck at <code>Loading...</code> after that. I don't understand what is going on that makes it stop fetching after first scroll.</p> <p>Code that's supposed to get new data looks like this:</p> <pre><code> const [latestNews, setLatestNews] = useState&lt;any[]&gt;([]); const [page, setPage] = useState&lt;number&gt;(1); const getLatestNews = async (page: number) =&gt; { let url = `https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=${API_KEY}&amp;page=${page}`; const response = await fetch(url); const data = await response.json(); setLatestNews(data.response.docs); setPage(page + 1); } </code></pre> <p>And my infinite scroll component looks like this</p> <pre><code> &lt;InfiniteScroll dataLength={latestNews.length} next={() =&gt; getLatestNews(page)} hasMore={true} loader={&lt;h4&gt;Loading...&lt;/h4&gt;} scrollableTarget=&quot;scrollableDiv&quot;&gt; { latestNews.map((article, index) =&gt; ( &lt;div className=&quot;latest-news-article flex flex-col gap-3 mb-4&quot; key={index}&gt; &lt;p className=&quot;latest-news-article-date&quot;&gt; {article.pub_date.slice(11, 16)} &lt;/p&gt; &lt;h1&gt; {article.headline.main} &lt;/h1&gt; &lt;/div&gt; )) } &lt;/InfiniteScroll&gt; </code></pre>
[ { "answer_id": 74648562, "author": "Rajat", "author_id": 9947159, "author_profile": "https://Stackoverflow.com/users/9947159", "pm_score": 2, "selected": false, "text": "datediff set mydate='2022-02-07 12:57:45.000'::timestamp;\n\nselect datediff(seconds, '1900-01-01', $mydate)::float/86400\n" }, { "answer_id": 74658309, "author": "John", "author_id": 3833426, "author_profile": "https://Stackoverflow.com/users/3833426", "pm_score": 1, "selected": false, "text": "create or replace function dayfloat_ts(ts TIMESTAMP)\nreturns float\nlanguage sql\nas\n$$\n (datediff(day, '1900-01-01', TS)::float +\n (datediff(nanoseconds, '1900-01-01', TS)::float -\n datediff(nanoseconds, '1900-01-01', date_trunc(day, TS)))::float / 86400000000000::float)\n$$;\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14510980/" ]
74,647,951
<p><a href="https://jsbin.com/hakuzozari/edit?html,css,output" rel="nofollow noreferrer">https://jsbin.com/hakuzozari/edit?html,css,output</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt; &lt;title&gt;JS Bin&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;page&quot;&gt; &lt;div=&quot;header-page&quot;&gt; &lt;div id=&quot;header&quot; class =&quot;container&quot;&gt; &lt;div id=&quot;logo&quot;&gt; &lt;h1&gt;Header Logo&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;conntent&quot;&gt; &lt;img src=&quot;https://pbs.twimg.com/profile_banners/1351534443165528067/1637702650/1500x500&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;threeColumns&quot;&gt; &lt;div id=&quot;column1&quot;&gt; &lt;h2&gt; Column 1&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;column2&quot;&gt; &lt;h2&gt; Column 2&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;column3&quot;&gt; &lt;h2&gt; Column 3&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>hi{ font-family: &quot;impact; } won't change me size off Header Logo .. somebody can help me ? thanks</p>
[ { "answer_id": 74648008, "author": "FreddyNoNose", "author_id": 10525306, "author_profile": "https://Stackoverflow.com/users/10525306", "pm_score": 0, "selected": false, "text": " h1{\n font-weight: normal;\n font-family: \"impact\"\n}\n" }, { "answer_id": 74648095, "author": "001", "author_id": 14559436, "author_profile": "https://Stackoverflow.com/users/14559436", "pm_score": 1, "selected": false, "text": "class id attribute <div id=\"header-page\">\n<!-- or -->\n<div class=\"header-page\">\n<!-- or any other attribute -->\n hi h1 font-weiht font-weight h1 {\n font-weight: normal;\n}\n semicolon (;) property: value; font-family: \"impact\"; <- Complete this by adding ; to allow the style \nfont-weight: normal; <- \n body{\n background: #FFFFFF;\n font-family: 'Abel', sans-serif;\n font-size: 20px;\n color: #3B3B3B;\n}\n\nh1 {\n font-family: \"impact\";\n font-weight: normal;\n} <!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>JS Bin</title>\n</head>\n<body>\n<div id=\"page\">\n<div id=\"header-page\">\n <div id=\"header\" class =\"container\">\n <div id=\"logo\">\n <h1>Header Logo</h1>\n </div>\n </div> \n <div class=\"conntent\">\n <img src=\"https://pbs.twimg.com/profile_banners/1351534443165528067/1637702650/1500x500\" />\n </div>\n </div>\n \n <div id=\"threeColumns\">\n <div id=\"column1\">\n <h2> Column 1</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.</p> \n </div>\n <div id=\"column2\">\n <h2> Column 2</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.</p> \n </div>\n <div id=\"column3\">\n <h2> Column 3</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras vulputate et libero at scelerisque. Suspendisse rhoncus tincidunt metus, ut cursus ipsum placerat venenatis. Nullam neque nisl, rhoncus at est quis, faucibus faucibus neque.</p> \n </div>\n </div>\n </div>\n</body>\n</html>" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17544244/" ]
74,647,975
<p>Kindly assist me in cleaning my date types in python.</p> <p>My sample data is as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>INITIATION DATE</th> <th>DATE CUT</th> <th>DATE GIVEN</th> </tr> </thead> <tbody> <tr> <td>1/July/2022</td> <td>21 July 2022</td> <td>11-July-2022</td> </tr> <tr> <td>17-July-2022</td> <td>16/July/2022</td> <td>21/July/2022</td> </tr> <tr> <td>16-July-2022</td> <td>01-July-2022</td> <td>09/July/2022</td> </tr> <tr> <td>19-July-2022</td> <td>31 July 2022</td> <td>27 July 2022</td> </tr> </tbody> </table> </div> <p>How do I remove all dashes/slashes/hyphens from dates in the different columns? I have 8 columns and 300 rows.</p> <p><strong>What i tried:</strong></p> <pre><code>df[['INITIATION DATE', 'DATE CUT', 'DATE GIVEN']]= df[['INITIATION DATE', 'DATE CUT', 'DATE GIVEN']].apply(pd.to_datetime, format = '%d%b%Y') </code></pre> <p>Desired output format for all: 1 July 2022</p> <p>ValueError I'm getting:</p> <blockquote> <p>time data '18 July 2022' does not match format '%d-%b-%Y' (match)</p> </blockquote>
[ { "answer_id": 74649334, "author": "Hannon qaoud", "author_id": 15678119, "author_profile": "https://Stackoverflow.com/users/15678119", "pm_score": 0, "selected": false, "text": "format df['INITIATION DATE'] = pd.to_datetime(df['INITIATION DATE'], format='%d-%B-%Y').dt.strftime('%d %B %Y')\ndf['DATE CUT'] = pd.to_datetime(df['DATE CUT'], format='%d %B %Y').dt.strftime('%d %B %Y')\ndf['DATE GIVEN'] = pd.to_datetime(df['DATE GIVEN'], format='%d/%B/%Y').dt.strftime('%d %B %Y')\n INITIATION DATE DATE CUT DATE GIVEN\n0 01 July 2022 21 July 2022 11 July 2022\n1 17 July 2022 16 July 2022 21 July 2022\n2 16 July 2022 01 July 2022 09 July 2022\n3 19 July 2022 31 July 2022 27 July 2022\n '18 July 2022' '%d-%b-%Y'" }, { "answer_id": 74653344, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "replace df.apply(lambda x: x.str.replace('[/-]',' ',regex=True))\n\n>>>\n'''\n INITIATION DATE DATE CUT DATE GIVEN\n0 1 July 2022 21 July 2022 11 July 2022\n1 17 July 2022 16 July 2022 21 July 2022\n2 16 July 2022 01 July 2022 09 July 2022\n3 19 July 2022 31 July 2022 27 July 2022\n df.apply(lambda x: pd.to_datetime(x.str.replace('[/-]',' ',regex=True)))\n\n>>>\n'''\n INITIATION DATE DATE CUT DATE GIVEN\n0 2022-07-01 2022-07-21 2022-07-11\n1 2022-07-17 2022-07-16 2022-07-21\n2 2022-07-16 2022-07-01 2022-07-09\n3 2022-07-19 2022-07-31 2022-07-27\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13384545/" ]
74,647,979
<p>I know this question has been asked before but I have tried to implement the answers to those forums but none have worked for me so far.</p> <p>Here is my html file:</p> <pre><code> {% include 'main.html' %} {% load static %} &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;projects.css&quot;/&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 style=&quot;text-align: center&quot;&gt;Projects&lt;/h1&gt; &lt;h1&gt;{{projects}}&lt;/h1&gt; {% for project in context %} {% with 'jweb/images/'|add:project.image as project_photo %} &lt;div class=&quot;card-wrap&quot;&gt; &lt;div class=&quot;card&quot;&gt; &lt;h2 class=&quot;card-header&quot;&gt;{{project.title}}&lt;/h2&gt; &lt;div class=&quot;card-image&quot;&gt; &lt;img src=&quot;{% static project_photo %}&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endwith %} {% endfor %} &lt;/body&gt; {% include 'pagebottom.html' %} </code></pre> <p>Here is my css:</p> <pre><code>.card-wrap{ width: auto; } .card{ background: blue; padding:3rem; border:none; box-shadow: 0 2px 5px 0 rgb(0,0,.2); border-radius: .25rem; } .card-image{ min-width: 0; min-width: 0; } .card-image &gt; img{ height:100%; width:100%; object-fit:contain; } </code></pre> <p>Here is my settings.py:</p> <pre><code>import os import mimetypes mimetypes.add_type(&quot;text/css&quot;, &quot;.css&quot;, True) from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ &quot;django.contrib.admin&quot;, &quot;django.contrib.auth&quot;, &quot;django.contrib.contenttypes&quot;, &quot;django.contrib.sessions&quot;, &quot;django.contrib.messages&quot;, &quot;django.contrib.staticfiles&quot;, &quot;blog&quot; ] MIDDLEWARE = [ &quot;django.middleware.security.SecurityMiddleware&quot;, &quot;django.contrib.sessions.middleware.SessionMiddleware&quot;, &quot;django.middleware.common.CommonMiddleware&quot;, &quot;django.middleware.csrf.CsrfViewMiddleware&quot;, &quot;django.contrib.auth.middleware.AuthenticationMiddleware&quot;, &quot;django.contrib.messages.middleware.MessageMiddleware&quot;, &quot;django.middleware.clickjacking.XFrameOptionsMiddleware&quot;, ] ROOT_URLCONF = &quot;jweb.urls&quot; TEMPLATES = [ { &quot;BACKEND&quot;: &quot;django.template.backends.django.DjangoTemplates&quot;, &quot;DIRS&quot;: [ BASE_DIR / 'templates' ], &quot;APP_DIRS&quot;: True, &quot;OPTIONS&quot;: { &quot;context_processors&quot;: [ &quot;django.template.context_processors.debug&quot;, &quot;django.template.context_processors.request&quot;, &quot;django.contrib.auth.context_processors.auth&quot;, &quot;django.contrib.messages.context_processors.messages&quot;, ], }, }, ] WSGI_APPLICATION = &quot;jweb.wsgi.application&quot; DATABASES = { &quot;default&quot;: { &quot;ENGINE&quot;: &quot;django.db.backends.sqlite3&quot;, &quot;NAME&quot;: BASE_DIR / &quot;db.sqlite3&quot;, } } STATIC_URL = &quot;static/&quot; STATICFILES_DIRS = [ BASE_DIR / 'static' ] </code></pre> <p>Here is my folder:</p> <p><img src="https://i.stack.imgur.com/mprjF.png" alt="Files" /></p> <p>I keep getting a 404 error: Refused to apply style from 'http://127.0.0.1:8000/projects/projects.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. It seems like I had the correct link statement in my html file and have tried to add text/css mimetypes but it keeps spitting the error.</p>
[ { "answer_id": 74649334, "author": "Hannon qaoud", "author_id": 15678119, "author_profile": "https://Stackoverflow.com/users/15678119", "pm_score": 0, "selected": false, "text": "format df['INITIATION DATE'] = pd.to_datetime(df['INITIATION DATE'], format='%d-%B-%Y').dt.strftime('%d %B %Y')\ndf['DATE CUT'] = pd.to_datetime(df['DATE CUT'], format='%d %B %Y').dt.strftime('%d %B %Y')\ndf['DATE GIVEN'] = pd.to_datetime(df['DATE GIVEN'], format='%d/%B/%Y').dt.strftime('%d %B %Y')\n INITIATION DATE DATE CUT DATE GIVEN\n0 01 July 2022 21 July 2022 11 July 2022\n1 17 July 2022 16 July 2022 21 July 2022\n2 16 July 2022 01 July 2022 09 July 2022\n3 19 July 2022 31 July 2022 27 July 2022\n '18 July 2022' '%d-%b-%Y'" }, { "answer_id": 74653344, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "replace df.apply(lambda x: x.str.replace('[/-]',' ',regex=True))\n\n>>>\n'''\n INITIATION DATE DATE CUT DATE GIVEN\n0 1 July 2022 21 July 2022 11 July 2022\n1 17 July 2022 16 July 2022 21 July 2022\n2 16 July 2022 01 July 2022 09 July 2022\n3 19 July 2022 31 July 2022 27 July 2022\n df.apply(lambda x: pd.to_datetime(x.str.replace('[/-]',' ',regex=True)))\n\n>>>\n'''\n INITIATION DATE DATE CUT DATE GIVEN\n0 2022-07-01 2022-07-21 2022-07-11\n1 2022-07-17 2022-07-16 2022-07-21\n2 2022-07-16 2022-07-01 2022-07-09\n3 2022-07-19 2022-07-31 2022-07-27\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74647979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13149562/" ]
74,648,020
<pre><code>//Method for Strip HTML public static String stripHtml(String inStr) { boolean inTag = false; char c; StringBuffer outStr = new StringBuffer(); int len = inStr.length(); for (int i = 0; i &lt; len; i++) { c = inStr.charAt(i); if (c == '&lt;') { inTag = true; } if (!inTag) { outStr.append(c); } if (c == '&gt;') { inTag = false; } } //Print to show that the this method is removing the necessary characters System.out.println(outStr); return outStr.toString(); } </code></pre> <p>So I need all outputs containing &lt;&gt; to be cleansed and everything in between it, and it should still print out the remaining characters. for instance</p> <pre><code>input:app&lt;html&gt;le expected:apple </code></pre> <p>however it should also remove if it finds just &quot;&lt;&quot; or &quot;&gt;&quot; but my method isn't doing so.</p> <pre><code>input:app&lt;le output:app&lt;le expected:apple </code></pre> <p>please let me know what to fix.</p>
[ { "answer_id": 74648078, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 2, "selected": false, "text": "getTextContent()" }, { "answer_id": 74648410, "author": "モキャデ", "author_id": 20607467, "author_profile": "https://Stackoverflow.com/users/20607467", "pm_score": 0, "selected": false, "text": "String input = \"app<html>le\";\nDocument doc = Jsoup.parse(input);\nSystem.out.println(doc.wholeText()); // or doc.text()\n apple\n public static String stripHtml(String inStr) {\n boolean inTag = false;\n StringBuffer outStr = new StringBuffer();\n int len = inStr.length();\n for (int i = 0; i < len; i++) {\n char c = inStr.charAt(i);\n if (c == '<') {\n inTag = true;\n } else if (c == '>') {\n inTag = false;\n } else if (!inTag) {\n outStr.append(c);\n }\n }\n return outStr.toString();\n}\n String input = \"app<html>le\";\nSystem.out.println(stripHtml(input));\n apple\n" }, { "answer_id": 74648704, "author": "Joop Eggen", "author_id": 984823, "author_profile": "https://Stackoverflow.com/users/984823", "pm_score": 0, "selected": false, "text": "<...> < > ìnt i2 = inStr.indexOf('>', i+1); > < public static String stripHtml(String s) {\n return s.replaceAll(\"<[^>]*>\", \"\");\n}\n < > * >" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660181/" ]
74,648,047
<p>Have a string as follows:</p> <pre><code>files=&quot;applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml&quot; </code></pre> <p>Want to extract the first two directories and save it as another string like this:</p> <pre><code>&quot;applications/dbt applications/dbt applications/dataform pplications/dataform&quot; </code></pre> <p>But while filling up the second string, its being saved as</p> <pre><code>applications/dbtapplications/dbtapplications/dataformapplications/dataform </code></pre> <p>What i tried:</p> <pre><code>files=&quot;applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml&quot; arr=($files) #extracting the first two directories and saving it to a new string for i in ${arr[@]}; do files2+=$(echo &quot;$i&quot; | cut -d/ -f 1-2); done echo $files2 </code></pre> <p>files2 echoes the following</p> <pre><code>applications/dbtapplications/dbtapplications/dataformapplications/dataform </code></pre>
[ { "answer_id": 74648126, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 1, "selected": false, "text": "arr=( applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml )\n#extracting the first two directories and saving it to a new string\nfor file in \"${arr[@]}\"; do\n files2+=\"${file%/*} \"\ndone\n echo \"$files2\"\napplications/dbt applications/dbt applications/dataform\n" }, { "answer_id": 74648321, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 0, "selected": false, "text": "for loop for dir in ${files}; \n do file2+=$(printf '%s ' \"${dir%/*}\")\ndone\n $ echo \"$file2\"\napplications/dbt applications/dbt applications/dataform applications/dataform\n sed $ sed -E 's~([^/]*/[^/]*)[^ ]*~\\1~g' <<< $files\napplications/dbt applications/dbt applications/dataform applications/dataform\n" }, { "answer_id": 74651308, "author": "Jetchisel", "author_id": 4452265, "author_profile": "https://Stackoverflow.com/users/4452265", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env bash\n\nfiles=\"applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml\"\n\nmapfile -t array <<< \"${files// /$'\\n'}\"\n array declare -p array\n declare -a array=([0]=\"applications/dbt/Dockerfile\" [1]=\"applications/dbt/cloudbuild.yaml\" [2]=\"applications/dataform/Dockerfile\" [3]=\"applications/dataform/cloudbuild.yaml\")\n / new_array=(\"${array[@]%/*}\")\n declare -p new_array\n declare -a new_array=([0]=\"applications/dbt\" [1]=\"applications/dbt\" [2]=\"applications/dataform\" [3]=\"applications/dataform\")\n new_var=\"${new_array[@]::2}\"\n declare -p new_var\n declare -- new_var=\"applications/dbt applications/dbt\"\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19329929/" ]
74,648,054
<p>how can call from OfferteService.cs to get a StateHasChanged function in detailsOfferta.razor?</p> <p>hello how can I call the StateHasChanged function from a service to update the detailsOfferta.razor page by the function statehaschanged?</p> <p>Thank you very much</p> <p>I tried invokeasync but it does not work</p>
[ { "answer_id": 74648126, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 1, "selected": false, "text": "arr=( applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml )\n#extracting the first two directories and saving it to a new string\nfor file in \"${arr[@]}\"; do\n files2+=\"${file%/*} \"\ndone\n echo \"$files2\"\napplications/dbt applications/dbt applications/dataform\n" }, { "answer_id": 74648321, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 0, "selected": false, "text": "for loop for dir in ${files}; \n do file2+=$(printf '%s ' \"${dir%/*}\")\ndone\n $ echo \"$file2\"\napplications/dbt applications/dbt applications/dataform applications/dataform\n sed $ sed -E 's~([^/]*/[^/]*)[^ ]*~\\1~g' <<< $files\napplications/dbt applications/dbt applications/dataform applications/dataform\n" }, { "answer_id": 74651308, "author": "Jetchisel", "author_id": 4452265, "author_profile": "https://Stackoverflow.com/users/4452265", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env bash\n\nfiles=\"applications/dbt/Dockerfile applications/dbt/cloudbuild.yaml applications/dataform/Dockerfile applications/dataform/cloudbuild.yaml\"\n\nmapfile -t array <<< \"${files// /$'\\n'}\"\n array declare -p array\n declare -a array=([0]=\"applications/dbt/Dockerfile\" [1]=\"applications/dbt/cloudbuild.yaml\" [2]=\"applications/dataform/Dockerfile\" [3]=\"applications/dataform/cloudbuild.yaml\")\n / new_array=(\"${array[@]%/*}\")\n declare -p new_array\n declare -a new_array=([0]=\"applications/dbt\" [1]=\"applications/dbt\" [2]=\"applications/dataform\" [3]=\"applications/dataform\")\n new_var=\"${new_array[@]::2}\"\n declare -p new_var\n declare -- new_var=\"applications/dbt applications/dbt\"\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660196/" ]
74,648,059
<p>I have a piece of text similar to this and it is basically a string of HTML code.</p> <pre><code>hello &lt;span dir=&quot;auto&quot; class=&quot;aDTYNe snByac OvPDhc OIC90c&quot;&gt;Professional Referee&lt;/span&gt; &lt;div&gt;....&lt;/div&gt; &lt;span dir=&quot;auto&quot; class=&quot;aDTYNe snByac OvPDhc OIC90c&quot;&gt;Professional Referee&lt;/span&gt; &lt;div&gt;....&lt;/div&gt; &lt;div&gt; &lt;span dir=&quot;auto&quot; class=&quot;aDTYNe snByac OvPDhc OIC90c&quot;&gt;Professional Referee&lt;/span&gt; &lt;/div&gt; &lt;span dir=&quot;auto&quot; class=&quot;aDTYNe snByac OvPDhc OIC90c&quot;&gt;Professional Referee&lt;/span&gt; &lt;span dir=&quot;auto&quot; class=&quot;aDTYNe snByac OvPDhc OIC90c&quot;&gt;Professional Referee&lt;/span&gt; </code></pre> <p>What I would like is to capture all of the span tags innerText (so in the example below, it would be Professional Referee) and store the results in an array.</p> <p>The Regex - I am thinking this would be the way to go - I have is like this:</p> <pre><code>^/(&lt;span)([\a-zA-Z0-9\s]*)(&lt;\/span&gt;)/$ </code></pre> <p>I am not flash on regex, and the additional issues is that each span tag may have some attributes that are not equal to the other tags.</p> <p>I think if I can get the full span tags from here in an array then I can manage to remove the left over stuff.</p> <p>I got a regex101 link here: <a href="https://regex101.com/r/9K90pa/1" rel="nofollow noreferrer">https://regex101.com/r/9K90pa/1</a></p> <p>Can someone help me select on the right way?</p>
[ { "answer_id": 74648119, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": true, "text": "const html = `hello\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<div>....</div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<div>....</div>\n<div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n</div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>`;\n\nconst doc = new DOMParser().parseFromString(html, \"text/html\");\nconst spanTexts = Array.from(doc.querySelectorAll(\"span\"), span => span.textContent);\n\nconsole.log(spanTexts);" }, { "answer_id": 74648297, "author": "Hannon qaoud", "author_id": 15678119, "author_profile": "https://Stackoverflow.com/users/15678119", "pm_score": 0, "selected": false, "text": "const regexp = \"<span.*?>(.*?)<\\/span>\";\n\nconst html = `hello\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<div>....</div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<div>....</div>\n<div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n</div>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\n<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>`;\nconst array = [...html.matchAll(regexp)];\n\nconsole.log(array);\n > Array [Array [\"<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\", \"Professional Referee\"], Array [\"<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\", \"Professional Referee\"], Array [\"<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\", \"Professional Referee\"], Array [\"<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\", \"Professional Referee\"], Array [\"<span dir=\"auto\" class=\"aDTYNe snByac OvPDhc OIC90c\">Professional Referee</span>\", \"Professional Referee\"]]\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892628/" ]
74,648,072
<p>I am trying to create a function that will use the query method to filter through a data frame based on multiple conditions and create a new series with the values applicable.</p> <p>Here is an example of the df that I am working with:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Week</th> <th style="text-align: center;">Treatment</th> <th style="text-align: right;">Value</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">0</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">100</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">150</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">149</td> </tr> <tr> <td style="text-align: left;">0</td> <td style="text-align: center;">XYZ</td> <td style="text-align: right;">350</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">XYZ</td> <td style="text-align: right;">500</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">XYZ</td> <td style="text-align: right;">600</td> </tr> <tr> <td style="text-align: left;">0</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">101</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">130</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">ABC</td> <td style="text-align: right;">147</td> </tr> </tbody> </table> </div> <p>I have been able to successfully filter my data for a given 'Week' and 'Treatment' using the .query method like this:</p> <pre><code>test = df.query('Week == 1 &amp; Treatment.str.startswith(&quot;A&quot;).values')['value'] </code></pre> <p>I am only interested in extracting the 'values' column.</p> <p>This is great, but I don't want to have to copy and paste this line of code for every 'week' and 'treatment' in my df. Therefore, I want to create a function that will let me identify the desired week and treatment (or first letter of treatment) as arguments and have it return an object with my desired values for further analysis.</p> <p>Here is what I have so far:</p> <pre><code>def sorter(df,week): return df.query('Week == 0 &amp; Treatment.str.startswith(&quot;A&quot;).values')['value'] </code></pre> <p>I know that as I have it, my function does not return my values as an object. I will work on that. Where I am stuck is how to have one of the arguments for my function be a week (like '0') when in the query method the week is written as part of a string.</p> <p>I tried this:</p> <pre><code>def sorter(df,week): return df.query('Week == week &amp; Treatment.str.startswith(&quot;A&quot;).values')['value'] </code></pre> <p>But I got an error saying week was undefined.</p>
[ { "answer_id": 74648319, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": true, "text": "f strings def sorter(df,week):\n return df.query(f'Week == {week} & Treatment.str.startswith(\"A\").values')['Value']\n" }, { "answer_id": 74648331, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "def sorter(df,week):\n return df.query('Week == @week & Treatment.str.startswith(\"A\").values')['value']\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17101266/" ]
74,648,077
<p>I have this method that I want to pass <em>into</em> another function.</p> <pre class="lang-py prettyprint-override"><code>def get_service_enums(context, enum): svc = Service(context) return svc.get_enum(enum) </code></pre> <p>I want to pass this function is as a parameter to another class.</p> <pre><code>ColumnDef(enum_values=my_func) </code></pre> <p>Ideally, <code>my_func</code> is <code>get_service_enums</code>. However <code>get_service_enums</code> has a second parameter, <code>enum</code> that I want to pass in at same time I pass in <code>get_service_enums</code>. How can I do this without actually invoking <code>get_service_enums</code> with parenthesis?</p>
[ { "answer_id": 74648319, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": true, "text": "f strings def sorter(df,week):\n return df.query(f'Week == {week} & Treatment.str.startswith(\"A\").values')['Value']\n" }, { "answer_id": 74648331, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "def sorter(df,week):\n return df.query('Week == @week & Treatment.str.startswith(\"A\").values')['value']\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330107/" ]
74,648,137
<p>I am working on implementing a search bar for a notes app I have been working on, I put an input inside a <code>SideBar</code> component, which is nested inside the main <code>App</code> component. The issue is that whenever I input a character, the input unfocuses.</p> <p>My code:</p> <pre><code>function App() { const [searchTerm, setSearchTerm] = useState(&quot;&quot;); function SideBarNotes() { return ( &lt;section className='search'&gt; &lt;input type=&quot;text&quot; value={searchTerm} onChange={(e) =&gt; setSearchTerm(e.target.value)} placeholder='Search...'/&gt; &lt;/section&gt; ) } return ( &lt;div className=&quot;App&quot;&gt; &lt;SideBarNotes /&gt; &lt;/div&gt; ) } </code></pre> <p>I would expect that the input would function as a regular controlled input, but instead, it reloads. <strong>I need the input to be &quot;global&quot;, as I want to use it inside the App component as well.</strong></p> <p>I have also tried the use-between hook which result was the same.</p>
[ { "answer_id": 74648319, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 2, "selected": true, "text": "f strings def sorter(df,week):\n return df.query(f'Week == {week} & Treatment.str.startswith(\"A\").values')['Value']\n" }, { "answer_id": 74648331, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "def sorter(df,week):\n return df.query('Week == @week & Treatment.str.startswith(\"A\").values')['value']\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20480501/" ]
74,648,144
<p>I have a function in my UI where I want to be able to collapse/make visible a text message depending on the value of a custom property in my window object.</p> <p>Using online references, I have come up with this code-behind to register the property:</p> <pre><code>public bool ValidInterval { get { return pValidInterval; } } private bool pValidInterval = true; public static readonly DependencyProperty ValidIntervalProperty = DependencyProperty.Register(&quot;ValidInterval&quot;, typeof(bool), typeof(Settings), new UIPropertyMetadata(true)); </code></pre> <p>And this corresponding XAML for the label:</p> <pre><code>&lt;Label Name=&quot;DynamicWarning&quot; Content=&quot;Time interval must be a valid positive integer.&quot;&gt; &lt;Label.Style&gt; &lt;Style TargetType=&quot;Label&quot;&gt; &lt;Setter Property=&quot;Visibility&quot; Value=&quot;Collapsed&quot; /&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding=&quot;{Binding ValidInterval}&quot; Value=&quot;true&quot;&gt; &lt;Setter Property=&quot;Visibility&quot; Value=&quot;Collapsed&quot; /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding=&quot;{Binding ValidInterval}&quot; Value=&quot;false&quot;&gt; &lt;Setter Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/Label.Style&gt; &lt;/Label&gt; </code></pre> <p>Unfortunately, this does not work. I can get it to set the parameter depending on the initial value of the property, but doesn't update the visibility dynamically like I want. I have been looking at this for an hour and what I have seems consistent with examples I am finding online for similar operations. Am I doing something wrong, or can you not update the visibility on the fly? If the latter, how do I achieve an equivalent effect?</p>
[ { "answer_id": 74648540, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 1, "selected": false, "text": "class" }, { "answer_id": 74648623, "author": "Tarazed", "author_id": 12705028, "author_profile": "https://Stackoverflow.com/users/12705028", "pm_score": 3, "selected": true, "text": "public bool ValidInterval\n{\n get { return (bool)GetValue(ValidIntervalProperty); }\n set { SetValue(ValidIntervalProperty, value); }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11552497/" ]
74,648,235
<p>So basically, I have this command that runs in Gitlab CI to update a field in YAML configuration before packaging and pushing a Helm chart.</p> <pre><code>yq -i -y &quot;.pod.image.imageTag=&quot;${CI_COMMIT_SHORT_SHA}&quot;&quot; deployment/values.yaml </code></pre> <p>values.yaml</p> <pre><code>pod: image: repository: my.private.repo/my-project imageTag: 'latest' nodegroupName: &quot;nessie-nodegroup&quot; </code></pre> <p>But I keep getting this error.</p> <pre><code>jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) .pod.image.imageTag=4c0118bf </code></pre> <p>The variable is actually read but it looks like I'm doing something wrong in the yq command. Any ideas where that error is coming from ? Trying with only one quote doesn't read the environment variable obviously. I already tried it.</p> <p>Update:</p> <p>Trying with :</p> <pre><code>yq -i -y '.pod.image.imageTag=&quot;${CI_COMMIT_SHORT_SHA}&quot;' deployment/values.yaml </code></pre> <p>and</p> <pre><code>yq -i -y .pod.image.imageTag=&quot;${CI_COMMIT_SHORT_SHA}&quot; deployment/values.yaml </code></pre> <p>didn't work either.</p>
[ { "answer_id": 74648540, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 1, "selected": false, "text": "class" }, { "answer_id": 74648623, "author": "Tarazed", "author_id": 12705028, "author_profile": "https://Stackoverflow.com/users/12705028", "pm_score": 3, "selected": true, "text": "public bool ValidInterval\n{\n get { return (bool)GetValue(ValidIntervalProperty); }\n set { SetValue(ValidIntervalProperty, value); }\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15333232/" ]
74,648,253
<h1>Question:</h1> <p>Below works, but is there a better &quot;R way&quot; of achieving similar result? I am essentially trying to create / distribute groups into individual line items according to a user defined function (currently just using a loop).</p> <h1>Example:</h1> <pre class="lang-r prettyprint-override"><code>df1 &lt;- data.frame(group = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), volume = c(200L, 45L, 104L) ) print(df1) #&gt; group volume #&gt; 1 A 200 #&gt; 2 B 45 #&gt; 3 C 104 </code></pre> <p>I want the <code>volume</code> to be broken across multiple rows according to group so that the final result is a dataframe where the new volume (<code>vol2</code> in the below) would add up to original volume above. In this example, I'm applying integer math with a divisor of 52, so my final result should be:</p> <pre class="lang-r prettyprint-override"><code>print(df3) #&gt; group vol2 #&gt; 1 A 52 #&gt; 2 A 52 #&gt; 3 A 52 #&gt; 4 A 44 #&gt; 21 B 45 #&gt; 31 C 52 #&gt; 32 C 52 </code></pre> <h2>This works</h2> <p>The code below <strong>DOES</strong> get me to the desired result shown above:</p> <pre class="lang-r prettyprint-override"><code>div &lt;- 52L df1$intgr &lt;- df1$volume %/% div df1$remainder &lt;- df1$volume %% div print(df1) #&gt; group volume intgr remainder #&gt; 1 A 200 3 44 #&gt; 2 B 45 0 45 #&gt; 3 C 104 2 0 df2 &lt;- data.frame() for (r in 1:nrow(df1)){ if(df1[r,&quot;intgr&quot;] &gt; 0){ for (k in 1:as.integer(df1[r,&quot;intgr&quot;])){ df1[r,&quot;vol2&quot;] &lt;- div df2 &lt;- rbind(df2, df1[r,]) } } if(df1[r,&quot;remainder&quot;]&gt;0){ df1[r, &quot;vol2&quot;] &lt;- as.integer(df1[r, &quot;remainder&quot;]) df2 &lt;- rbind(df2, df1[r,]) } } print(df2) #&gt; group volume intgr remainder vol2 #&gt; 1 A 200 3 44 52 #&gt; 2 A 200 3 44 52 #&gt; 3 A 200 3 44 52 #&gt; 4 A 200 3 44 44 #&gt; 21 B 45 0 45 45 #&gt; 31 C 104 2 0 52 #&gt; 32 C 104 2 0 52 df3 &lt;- subset(df2, select = c(&quot;group&quot;, &quot;vol2&quot;)) print(df3) #&gt; group vol2 #&gt; 1 A 52 #&gt; 2 A 52 #&gt; 3 A 52 #&gt; 4 A 44 #&gt; 21 B 45 #&gt; 31 C 52 #&gt; 32 C 52 </code></pre> <p>Being still relatively new to R, I'm just curious if someone knows a better way / function / method that gets to the same place. Seems like there might be. I could potentially have a more complex way of breaking up the rows and I was thinking maybe there's a method that applies a UDF to the dataframe to do something like this. I was searching for &quot;expand group/groups&quot; but was finding mostly &quot;expand.grid&quot; which isn't what I'm doing here.</p> <p>Thank you for any suggestions!</p>
[ { "answer_id": 74648512, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "tidyverse purrr::pmap tidyr::unnest_longer library(dplyr, w = FALSE)\nlibrary(tidyr)\nlibrary(purrr)\n\ndiv <- 52\n\ndf1 |> \n mutate(intgr = volume %/% div, remainder = volume %% div, intgr1 = +(remainder > 0)) |> \n mutate(vol2 = purrr::pmap(list(intgr, intgr1, remainder), ~ c(rep(div, ..1), rep(..3, ..2)))) |> \n tidyr::unnest_longer(vol2) |> \n select(-intgr1)\n#> # A tibble: 7 × 5\n#> group volume intgr remainder vol2\n#> <chr> <int> <dbl> <dbl> <dbl>\n#> 1 A 200 3 44 52\n#> 2 A 200 3 44 52\n#> 3 A 200 3 44 52\n#> 4 A 200 3 44 44\n#> 5 B 45 0 45 45\n#> 6 C 104 2 0 52\n#> 7 C 104 2 0 52\n" }, { "answer_id": 74648531, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 2, "selected": false, "text": "data.table rep library(data.table)\n\nsetDT(df1)[, .(vol2 = c(rep(52, volume%/%52), (volume%%52)[sign(volume%%52)])), group]\n#> group vol2\n#> 1: A 52\n#> 2: A 52\n#> 3: A 52\n#> 4: A 44\n#> 5: B 45\n#> 6: C 52\n#> 7: C 52\n setDT(df1)[, .(vol2 = c(rep(52, volume%/%52), volume%%52)), group][vol2 != 0]\n#> group vol2\n#> 1: A 52\n#> 2: A 52\n#> 3: A 52\n#> 4: A 44\n#> 5: B 45\n#> 6: C 52\n#> 7: C 52\n" }, { "answer_id": 74648538, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 4, "selected": true, "text": "fun <- function(num, mod) c(rep(mod, floor(num / mod)), (num-1) %% mod + 1)\nfun(200, 52)\n# [1] 52 52 52 44\nfun(45, 52)\n# [1] 45\nfun(104, 52)\n# [1] 52 52\n library(dplyr)\ndf1 %>%\n group_by(group) %>%\n summarize(vol2 = fun(volume, 52), .groups = \"drop\")\n# # A tibble: 7 x 2\n# group vol2\n# <chr> <dbl>\n# 1 A 52\n# 2 A 52\n# 3 A 52\n# 4 A 44\n# 5 B 45\n# 6 C 52\n# 7 C 52\n do.call(rbind, by(df1, seq(nrow(df1)),\n FUN = function(z) data.frame(group = z$group, vol2 = fun(z$volume, 52))))\n library(data.table)\nsetDT(df1)\ndf1[, .(vol2 = fun(volume, 52)), by = group]\n" }, { "answer_id": 74648754, "author": "thelatemail", "author_id": 496803, "author_profile": "https://Stackoverflow.com/users/496803", "pm_score": 2, "selected": false, "text": "df1 <- data.frame(group = c(\"A\", \"B\", \"C\"),\n volume = c(200L, 45L, 104L))\n\nn <- 52\nidx <- df1$volume %/% n + ((sel <- df1$volume %% n) != 0)\nout <- df1[rep(seq_len(nrow(df1)), idx),]\nout$volume <- n\nout$volume[cumsum(idx)[sel != 0]] <- sel[sel != 0]\n## group volume\n##1 A 52\n##1.1 A 52\n##1.2 A 52\n##1.3 A 44\n##2 B 45\n##3 C 52\n##3.1 C 52\n" }, { "answer_id": 74672349, "author": "user12256545", "author_id": 12256545, "author_profile": "https://Stackoverflow.com/users/12256545", "pm_score": 1, "selected": false, "text": "aggregate aggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1))\n\n group volume\n1 A 52, 52, 52, 44\n2 B 45\n3 C 52, 52, 52\n stack \nwith(\n aggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)),\n setNames(stack(setNames(volume,group))[2:1],names(df1))\n )\n\n group volume\n1 A 52\n2 A 52\n3 A 52\n4 A 44\n5 B 45\n6 C 52\n7 C 52\n8 C 52\n\n\n unnest tidyr library(tidyr)\n\naggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)) %>% unnest(volume)\n\n# A tibble: 8 × 2\n group volume\n <chr> <dbl>\n1 A 52\n2 A 52\n3 A 52\n4 A 44\n5 B 45\n6 C 52\n7 C 52\n8 C 52\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3601357/" ]
74,648,264
<p>I am studying the pointers and this question became interesting. I want it to be like this: we have two arrays of integers. Determine the value and number of the largest element of the first array that is not part of the second but I don't know how to make the second part of the code that will check if the largest number is not included in the second array</p> <pre><code>#include &lt;stdio.h&gt; int main() { long array[100], * maximum, size, c, location = 1; printf(&quot;Enter the number of elements in array\n&quot;); scanf_s(&quot;%ld&quot;, &amp;size); printf(&quot;Enter %ld integers\n&quot;, size); for (c = 0; c &lt; size; c++) scanf_s(&quot;%ld&quot;, &amp;array[c]); maximum = array; *maximum = *array; for (c = 1; c &lt; size; c++) { if (*(array + c) &gt; *maximum) { *maximum = *(array + c); location = c + 1; } } printf(&quot;Maximum element is present at location number %ld and it's value is %ld.\n&quot;, location, *maximum); return 0; } </code></pre>
[ { "answer_id": 74648384, "author": "Jason", "author_id": 635822, "author_profile": "https://Stackoverflow.com/users/635822", "pm_score": 0, "selected": false, "text": "LONG_MIN #include <limits.h>\n\nint i = 0;\nfor (; i < n; ++i) {\n int j = 0;\n for (; j < n; ++j) {\n /* in both arrays? */\n if (arr2[i] == arr1[j]) {\n arr1[j] = LONG_MIN;\n break;\n }\n }\n}\n arr1 arr2 LONG_MIN INT_MIN LONG_MIN long int" }, { "answer_id": 74648640, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 1, "selected": false, "text": "maximum = array;\n\n//...\n\n*maximum = *(array + c);\n #include <stdio.h>\n\nint find( const int a[], size_t n, int value )\n{\n const int *p = a;\n\n while (p != a + n && *p != value) ++p;\n\n return p != a + n;\n}\n\nint * max_exclusive_element( const int a1[], size_t n1, const int a2[], size_t n2 )\n{\n const int *max = a1;\n\n while (max < a1 + n1 && find( a2, n2, *max ) ) ++max;\n\n if (max < a1 + n1)\n {\n for ( const int *p = max; ++p < a1 + n1; )\n {\n if ( *max < *p && !find( a2, n2, *p ) )\n {\n max = p;\n }\n }\n }\n\n return ( int * )( max == a1 + n1 ? NULL : max );\n}\n\nint main( void )\n{\n int a1[] = { 1, 3, 5, 6, 7, 8, 9 };\n const size_t N1 = sizeof( a1 ) / sizeof( *a1 );\n int a2[] = { 1, 3, 5, 7, 9 };\n const size_t N2 = sizeof( a2 ) / sizeof( *a2 );\n\n int *max = max_exclusive_element( a1, N1, a2, N2 );\n\n if (max != NULL)\n {\n printf( \"Maximum element is present at location number %td and it's value is %d.\\n\", \n max - a1, *max );\n }\n}\n Maximum element is present at location number 5 and it's value is 8.\n find max_exclusive_element long int" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20380423/" ]
74,648,333
<p>making guessing game. I keep getting an attribute error trying to append my guess to the guesses list. following along in a course. I was prompted to say getting warmer if the current guess was closer than the last guess. i set guesses = 0 and and within the while loop i tried to append with (guesses.append(cg)) cg = current guess</p> <pre class="lang-py prettyprint-override"><code>import random correct = random.randint(1,100) print(correct) guesses = 0 cg = int(input('Welcome to GUESSER guess here: ')) while True: if cg &gt; 100 or cg &lt; 0: print('out of bounds') continue if cg == correct: print(f'It took {len(guesses)} to guess right. nice.') break if abs(cg - correct) &lt;= 10: #first guess print('warm.') else: print('cold.') guesses.append(cg) if guesses[-2]: #after first guess if abs(correct - guesses[-2]) &gt; abs(correct - cg): print('warmer') guesses.append(cg) else: print ('colder') guesses.append(cg) pass </code></pre>
[ { "answer_id": 74648384, "author": "Jason", "author_id": 635822, "author_profile": "https://Stackoverflow.com/users/635822", "pm_score": 0, "selected": false, "text": "LONG_MIN #include <limits.h>\n\nint i = 0;\nfor (; i < n; ++i) {\n int j = 0;\n for (; j < n; ++j) {\n /* in both arrays? */\n if (arr2[i] == arr1[j]) {\n arr1[j] = LONG_MIN;\n break;\n }\n }\n}\n arr1 arr2 LONG_MIN INT_MIN LONG_MIN long int" }, { "answer_id": 74648640, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 1, "selected": false, "text": "maximum = array;\n\n//...\n\n*maximum = *(array + c);\n #include <stdio.h>\n\nint find( const int a[], size_t n, int value )\n{\n const int *p = a;\n\n while (p != a + n && *p != value) ++p;\n\n return p != a + n;\n}\n\nint * max_exclusive_element( const int a1[], size_t n1, const int a2[], size_t n2 )\n{\n const int *max = a1;\n\n while (max < a1 + n1 && find( a2, n2, *max ) ) ++max;\n\n if (max < a1 + n1)\n {\n for ( const int *p = max; ++p < a1 + n1; )\n {\n if ( *max < *p && !find( a2, n2, *p ) )\n {\n max = p;\n }\n }\n }\n\n return ( int * )( max == a1 + n1 ? NULL : max );\n}\n\nint main( void )\n{\n int a1[] = { 1, 3, 5, 6, 7, 8, 9 };\n const size_t N1 = sizeof( a1 ) / sizeof( *a1 );\n int a2[] = { 1, 3, 5, 7, 9 };\n const size_t N2 = sizeof( a2 ) / sizeof( *a2 );\n\n int *max = max_exclusive_element( a1, N1, a2, N2 );\n\n if (max != NULL)\n {\n printf( \"Maximum element is present at location number %td and it's value is %d.\\n\", \n max - a1, *max );\n }\n}\n Maximum element is present at location number 5 and it's value is 8.\n find max_exclusive_element long int" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660336/" ]
74,648,335
<p>For example,</p> <p>Lets say I have a map:</p> <pre><code>Map&lt;string, dynamic&gt; myMap = {'zero': 0, 'one': 1, 'two': 2}; </code></pre> <p>How can I display these values in a text widget like what is depicted below:</p> <pre><code>Map key-value pairs: zero: 0 one: 1 two: 2 </code></pre>
[ { "answer_id": 74648439, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 3, "selected": true, "text": "Column(\n children: myMap.entries\n .map(\n (e) => Text(\"${e.key}: ${e.value}\"),\n )\n .toList(),\n);\n" }, { "answer_id": 74648461, "author": "Rohan Jariwala", "author_id": 13954519, "author_profile": "https://Stackoverflow.com/users/13954519", "pm_score": 1, "selected": false, "text": "ListView.builder(\n itemCount: myMap.entries.toList().length,\n itemBuilder: (cont, index) {\n return Text('${myMap.entries.toList()[index].key.toString()} : ${myMap.entries.toList()[index].value.toString()}');\n },\n )\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14868799/" ]
74,648,363
<p>I have a file that is essentially made up of rows of strings. I am trying to extract the sections of rows into individual files between rows of strings. The file looks like this:</p> <pre><code>**File Begins** &quot;Name: XXX_2&quot; &quot;Description: Object 1210 , 111&quot; &quot;Sampling_info: statexy=1346&quot; &quot;Num value: 15&quot; &quot;32 707; 33 71; 37 11; 38 3; 40 146; &quot; &quot;41 64; 42 36; 43 24; 44 69; 45 324; &quot; &quot;46 49; 47 52; 50 11; 51 90; 52 22; &quot; &quot;Name: XXX_3&quot; &quot;Description: Object 1341 , 111&quot; &quot;Sampling_info: statexy=1346&quot; &quot;Num value: 18&quot; &quot;32 999; 33 4; 34 17; 39 84; 41 84; &quot; &quot;42 4; 44 137; 45 102; 50 13; 52 22; &quot; &quot;53 4; 54 4; 55 84; 58 40; 59 13; &quot; &quot;65 57; 66 13; 67 173; &quot; &quot;Name: XXX_4&quot; &quot;Description: Object 1561 , 111&quot; &quot;Sampling_info: statexy=1346&quot; &quot;Num value: 21&quot; &quot;32 925; 34 5; 40 409; 41 55; 44 43; &quot; &quot;45 154; 46 5; 47 5; 50 38; 52 16; &quot; &quot;56 99; 58 5; 59 110; 61 5; 62 55; &quot; &quot;63 11; 68 5; 69 38; 70 22; 73 999; &quot; &quot;74 49; &quot; &quot;Name: XXX_5&quot; **And then the next entry begins** </code></pre> <p>I want to get the numbers between &quot;Num value: 15&quot; and &quot;Name: XXX_3&quot; while excluding those two rows and put it into it's own text file. Same for the next two entries. This will be implemented into a for loop or other to extract all the independent entries in the file to their own file.</p> <p>I tried str_match but it returns NA:</p> <pre><code>str_match(data, &quot;Name: UNK_1\\s*(.*?)\\s*Name: UNK_2&quot;) </code></pre> <p>I also tried gsub but it returned the whole file...:</p> <pre><code>gsub(&quot;.*Name: UNK_1 (.+) Name: UNK_2.*&quot;, &quot;\\1&quot;, data) </code></pre> <p>Is there something wring with my implementation of str_match and gsub?</p> <p>Thank you in advance!</p>
[ { "answer_id": 74649100, "author": "I_O ", "author_id": 20513099, "author_profile": "https://Stackoverflow.com/users/20513099", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf <- read.delim('path_to_input_file/your_file.txt',\n sep = ':', header = FALSE)\n\ndf %>%\n separate(V1, into = c('param', 'value'), sep = ' *: *') %>%\n filter(param == 'Name' | grepl(';', param)) %>%\n fill(value, .direction = 'down') %>%\n filter(param != 'Name') %>%\n separate_rows(param, sep = ' *; *')\n\n## follow up with blank removal, conversion to numeric as needed\n value # A tibble: 18 x 2\n param value \n <chr> <chr> \n 1 \"32 707\" \"XXX_2 \"\n 2 \"33 71\" \"XXX_2 \"\n 3 \"37 11\" \"XXX_2 \"\n 4 \"38 3\" \"XXX_2 \"\n 5 \"40 146\" \"XXX_2 \"\n 6 \"\" \"XXX_2 \"\n" }, { "answer_id": 74649258, "author": "Anthony Martinez", "author_id": 7470643, "author_profile": "https://Stackoverflow.com/users/7470643", "pm_score": 1, "selected": false, "text": "library(tidyverse)\n# Build dataset\ndf <- data.frame(\n col1 = c(\"Name: XXX_2\" ,\n \"Description: Object 1210 , 111\",\n \"Sampling_info: statexy=1346\",\n \"Num value: 15\",\n \"32 707; 33 71; 37 11; 38 3; 40 146; \" ,\n \"41 64; 42 36; 43 24; 44 69; 45 324; \" ,\n \"46 49; 47 52; 50 11; 51 90; 52 22; \" ,\n \"Name: XXX_3\" ,\n \"Shouldn't get this number: 8675309\")\n)\n\ndf %>%\n # Combine row into single string\n map_chr(paste, collapse = \" \") %>%\n # Remove everything before \"Num value:\"\n str_extract(\" Num value:.*\") %>%\n # Remove numbers after \"Num value:\n str_remove(\"Num value: \\\\d+\") %>%\n # Remove everything after \"Name:\"\n str_extract(\" .*Name:\") %>%\n # Extract digits\n str_extract_all(\"\\\\d+\") %>%\n unlist() %>%\n as.numeric()\n\n#[1] 32 707 33 71 37 11 38 3 40 146 41 64 42 36 43 24 44 69 45\n#[20] 324 46 49 47 52 50 11 51 90 52 22\n" }, { "answer_id": 74671369, "author": "Chris", "author_id": 794450, "author_profile": "https://Stackoverflow.com/users/794450", "pm_score": 0, "selected": false, "text": "base for library(stringr)\n# msp_list <- scan(file='', what = character()) #paste in 1:24 above <return>\n# dput(msp_list)\nmsp_list <- c(\"Name: XXX_2\", \"Description: Object 1210 , 111\", \"Sampling_info: statexy=1346\", \n\"Num value: 15\", \"32 707; 33 71; 37 11; 38 3; 40 146; \", \"41 64; 42 36; 43 24; 44 69; 45 324; \", \n\"46 49; 47 52; 50 11; 51 90; 52 22; \", \"Name: XXX_3\", \"Description: Object 1341 , 111\", \n\"Sampling_info: statexy=1346\", \"Num value: 18\", \"32 999; 33 4; 34 17; 39 84; 41 84; \", \n\"42 4; 44 137; 45 102; 50 13; 52 22; \", \"53 4; 54 4; 55 84; 58 40; 59 13; \", \n\"65 57; 66 13; 67 173; \", \"Name: XXX_4\", \"Description: Object 1561 , 111\", \n\"Sampling_info: statexy=1346\", \"Num value: 21\", \"32 925; 34 5; 40 409; 41 55; 44 43; \", \n\"45 154; 46 5; 47 5; 50 38; 52 16; \", \"56 99; 58 5; 59 110; 61 5; 62 55; \", \n\"63 11; 68 5; 69 38; 70 22; 73 999; \", \"74 49; \")\n# get rid of trailing whitespace that will be annoying later\nmsp_lst <- trimws(msp_list, 'r')\n msp_name_rle <- rle(str_starts(msp_list, 'Name'))$lengths\nmsp_rle_mtx<- matrix(msp_name_rle, nrow = length(msp_name_rle)/2, ncol = 2, byrow = TRUE)\nmsp_rowsums <-matrix(rowSums(msp_rle_mtx), ncol = 1)\nstarts <- which(str_starts(msp_list, 'Name') == TRUE)\nstarts\n[1] 1 8 16\nends <- as.vector(starts + msp_rowsums -1)\nends\n[1] 7 15 24\n\n# and then get names as they will be useful later\n> msp_names <- trimws(str_extract(msp_list[which(str_starts(msp_list, 'Name') == TRUE)], '\\\\s\\\\w+'))\n# a similar extract could be done on ? whatever is informative and applied to attributes later (not done here)\n# initialize an object to receive output from the `for` loop\nmany_msp <- list()\n i,j # first checking that the indexing is working\nfor(i in 1:length(starts)) {\n many_msp[[i]] <- df3[starts[i]:ends[i], ]\n}\nmany_msp[[3]]\n[[3]]\n[1] \"Name: XXX_4\" \n[2] \"Description: Object 1561 , 111\" \n[3] \"Sampling_info: statexy=1346\" \n[4] \"Num value: 21\" \n[5] \"32 925; 34 5; 40 409; 41 55; 44 43; \"\n[6] \"45 154; 46 5; 47 5; 50 38; 52 16; \" \n[7] \"56 99; 58 5; 59 110; 61 5; 62 55; \" \n[8] \"63 11; 68 5; 69 38; 70 22; 73 999; \" \n[9] \"74 49; \" \n# OK. Now, we can either make another `for`, or extend what happens within this one.\n for(i in 1:length(starts)) {\nmany_msp[[i]] <- msp_list[starts[i]:ends[i]]\n#return only values\nmany_msp[[i]] <- many_msp[[i]][5:lengths(many_msp)[i]]\n#take to vector, after a bunch of tidying up\nmany_msp[[i]] <- as.numeric(strsplit(trimws(paste(gsub(';', '', many_msp[[i]]), collapse = ''), 'r'), ' ')[[1]])\n#take to data.frame\nmany_msp[[i]] <- data.frame(col1 = many_msp[[i]][seq(1, length(many_msp[[i]]), 2)], col2 = many_msp[[i]][seq(2, length(many_msp[[i]]), 2)])\n# name the data.frames\nnames(many_msp)[i] <- msp_names[[i]]\n}\n\nnames(many_msp)\n[1] \"XXX_2\" \"XXX_3\" \"XXX_4\"\n\n\nmany_msp$XXX_4\n col1 col2\n1 32 925\n2 34 5\n3 40 409\n4 41 55\n5 44 43\n6 45 154\n7 46 5\n8 47 5\n9 50 38\n10 52 16\n11 56 99\n12 58 5\n13 59 110\n14 61 5\n15 62 55\n16 63 11\n17 68 5\n18 69 38\n19 70 22\n20 73 999\n21 74 49\n for many_msp$XXX_4$col1\n [1] 32 34 40 41 44 45 46 47 50 52 56 58 59 61 62 63 68 69 70 73 74\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13709409/" ]
74,648,370
<p>I'm wanting to rename</p> <pre><code>123/1/ -&gt; 123/v1/ foo/1/ -&gt; foo/v1/ bar/1/ -&gt; bar/v1/ 345/1/ -&gt; 345/v1/ </code></pre> <p>I've searched and found a few related solutions, but not quite sure what is best in this instance. e.g.,</p> <pre><code>find . -wholename &quot;*/1&quot; -exec echo '{}' \; </code></pre> <p>successfully prints out all the paths relative to <code>.</code>, but <code>{}</code> expands to <code>./foo/1/</code>, so I can't move from <code>{}</code> to <code>{}/v1</code> for instance. I also tried</p> <pre><code>find . -wholename &quot;*/1&quot; -exec mv '{}' $(echo '{}' | sed 's/1/v1/') \; </code></pre> <p>with the idea that I would be invoking <code>mv ./foo/1 ./foo/v1</code>, but apparently it tries to move <code>.foo/1/</code> to a subdirectory of itself.</p> <p>Anyhow, just looking for the simplest way to do this bulk renaming. To be clear, I'm trying to move the literal subdirectory <code>1</code> to <code>v1</code>, not also <code>2</code> to <code>v2</code>.</p>
[ { "answer_id": 74648408, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "while IFS= read -r old; do\n new=\"${old##*/}v1\"\n echo mv -- \"$old\" $new\"\ndone < <(find . -type d -name 1)\n echo" }, { "answer_id": 74648423, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 3, "selected": true, "text": "rename rename --version rename -n 's|([^/]+/)(1)|$1v$2|' */1/ \n -n globstar" }, { "answer_id": 74648590, "author": "ridiculous_fish", "author_id": 1441328, "author_profile": "https://Stackoverflow.com/users/1441328", "pm_score": 2, "selected": false, "text": "for file in **/1/; mv $file (dirname $file)/v1; end\n" }, { "answer_id": 74649034, "author": "pjh", "author_id": 4154375, "author_profile": "https://Stackoverflow.com/users/4154375", "pm_score": 0, "selected": false, "text": "find . -depth -type d -name 1 -execdir mv 1 v1 \\;\n -execdir find find find -exec -execdir -depth foo/1/1/1 find 1" }, { "answer_id": 74661121, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "$ tree .\n.\n├── 123\n│   └── 1\n├── 345\n│   └── 1\n│   └── 1 # this is a file named '1'\n├── bar\n│   └── 1\n└── foo\n └── 1\n └── file\n8 directories, 2 files\n #!/bin/bash\n\nshopt -s globstar\nnew_1=\"v1\"\n\nfor src in **/*/1; do # will RECURSIVELY find any directory '1'\n # if just next level (as in example)\n # you can just do */1\n [ -d \"$src\" ] || continue \n tgt=\"${src%%/1}/$new_1\"\n echo \"./$src/ => ./$tgt/\"\n mv \"./$src\" \"./$tgt/\"\ndone \n $ tree .\n.\n├── 123\n│   └── v1\n├── 345\n│   └── v1\n│   └── 1\n├── bar\n│   └── v1\n└── foo\n └── v1\n └── file\n 8 directories, 2 files\n shopt -s globstar\nnew_1=\"a parent/v1\" # the replacement path has a parent\n\nfor src in **/*/1; do \n [ -d \"$src\" ] || continue \n tgt=\"${src%%/1}/$new_1\"\n [[ \"/\" == *\"$new_1\"* ]] || mkdir -p \"${tgt%/*}\" # create parents if any\n echo \"./$src/ => ./$tgt/\"\n mv \"./$src\" \"./$tgt/\"\ndone \n $ tree .\n.\n├── 123\n│   └── a parent\n│   └── v1\n├── 345\n│   └── a parent\n│   └── v1\n│   └── 1\n├── bar\n│   └── a parent\n│   └── v1\n└── foo\n └── a parent\n └── v1\n └── file\n 12 directories, 2 files\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954986/" ]
74,648,374
<p>I have an array of objects and some of those objects has groups which is an array,</p> <p>i want all those objects from all groups and put it into one array of object, any idea how this could be done ?</p> <p>what i want to have is this : <code>GroupData= [ { id: &quot;679d8044&quot;, name: &quot;group 3&quot; }, { id: &quot;b9342eb8&quot;, name: &quot;group 1&quot; } ]; </code></p> <p>any idea ? english is not my mother language so could be mistakes.</p> <p>you can try it here: <a href="https://codesandbox.io/s/react-list-array-of-objects-forked-rk34fj?file=/src/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/react-list-array-of-objects-forked-rk34fj?file=/src/index.js</a></p> <p>my code:</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>import React from "react"; import { render } from "react-dom"; const mydata = [ { name: "living room", groups: "" }, { groups: [ { id: "679d8044", name: "group 3" } ], name: "Area 1" }, { groups: [ { id: "b9342eb8", name: "group 1" } ], name: "Area 2" } ]; const GroupData = mydata.find((grup) =&gt; grup.groups); console.log(GroupData); const App = () =&gt; &lt;div&gt;&lt;/div&gt;; render(&lt;App /&gt;, document.getElementById("root"));</code></pre> </div> </div> </p>
[ { "answer_id": 74648488, "author": "Dennis Martinez", "author_id": 613932, "author_profile": "https://Stackoverflow.com/users/613932", "pm_score": 1, "selected": false, "text": "const mydata = [\n {\n name: \"living room\",\n groups: \"\"\n },\n {\n groups: [\n {\n id: \"679d8044\",\n name: \"group 3\"\n }\n ],\n name: \"Area 1\"\n },\n {\n groups: [\n {\n id: \"b9342eb8\",\n name: \"group 1\"\n }\n ],\n name: \"Area 2\"\n }\n];\n\nconst GroupData = mydata.flatMap((grup) => grup.groups);\n\nconsole.log(GroupData) groups: \"\" groups: [] const mydata = [\n {\n name: \"living room\",\n groups: []\n },\n {\n groups: [\n {\n id: \"679d8044\",\n name: \"group 3\"\n }\n ],\n name: \"Area 1\"\n },\n {\n groups: [\n {\n id: \"b9342eb8\",\n name: \"group 1\"\n }\n ],\n name: \"Area 2\"\n }\n];\n\nconst GroupData = mydata.flatMap((grup) => grup.groups);\n\nconsole.log(GroupData)" }, { "answer_id": 74648520, "author": "Edward Motloung", "author_id": 6413849, "author_profile": "https://Stackoverflow.com/users/6413849", "pm_score": 0, "selected": false, "text": "const mydata = [\n {\n name: \"living room\",\n groups: \"\"\n },\n {\n groups: [\n {\n id: \"679d8044\",\n name: \"group 3\"\n }\n ],\n name: \"Area 1\"\n },\n {\n groups: [\n {\n id: \"b9342eb8\",\n name: \"group 1\"\n }\n ],\n name: \"Area 2\"\n }\n];\n\nlet groupData = [];\n\nmydata.map((d) => {\n if (Array.isArray(d.groups)) {\n d.groups.map((group) => {\n groupData.push(group)\n })\n console.log(groupData)\n }\n})\n" }, { "answer_id": 74648551, "author": "Guido Carugati", "author_id": 13290792, "author_profile": "https://Stackoverflow.com/users/13290792", "pm_score": 0, "selected": false, "text": "const GroupData = mydata.flatMap((item) => item.groups);\n [\n { id: \"679d8044\", name: \"group 3\" },\n { id: \"b9342eb8\", name: \"group 1\" }\n]\n" }, { "answer_id": 74651501, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 0, "selected": false, "text": ".flatmap() group group [] flatmap const mydata = [{ name: \"living room\", groups: \"\" }, { groups: [ { id: \"679d8044\", name: \"group 3\" } ], name: \"Area 1\" }, { groups: [ { id: \"b9342eb8\", name: \"group 1\" } ], name: \"Area 2\" }];\n\nconst isArr = (arr) => Array.isArray(arr);\nconst res = mydata.flatMap(({groups}) => (isArr(groups) && groups) || []);\nconsole.log(res);" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17292277/" ]
74,648,391
<p>I am trying to use MongoDb with SpringBoot using docker-compose, but I can't seem to connect to the database using the username and password that i set in the <code>docker-compose.yaml</code> and <code>application.properties</code></p> <p>Below is the <code>docker-compose.yaml</code>.</p> <pre><code>version: &quot;3.8&quot; services: mongodb: image: mongo container_name: mongodb ports: - 27017:27017 volumes: - ./001_users.js:/docker-entrypoint-initdb.d/001_users.js:ro - data:/data environment: - MONGO_INITDB_ROOT_USERNAME=rootuser - MONGO_INITDB_ROOT_PASSWORD=rootpass mongo-express: image: mongo-express container_name: mongo-express restart: always ports: - 8081:8081 environment: - ME_CONFIG_MONGODB_ADMINUSERNAME=rootuser - ME_CONFIG_MONGODB_ADMINPASSWORD=rootpass - ME_CONFIG_MONGODB_SERVER=mongodb volumes: data: {} networks: default: name: mongodb_network </code></pre> <p><code>application.properties</code>:</p> <pre><code>spring.data.mongodb.authentication-database=admin spring.data.mongodb.username=rootuser spring.data.mongodb.password=rootpass spring.data.mongodb.database=foober spring.data.mongodb.port=27017 spring.data.mongodb.host=localhost spring.data.mongodb.auto-index-creation=true </code></pre> <p>I tried adding the docker-entrypoint file (001_users.js) with the code below but it didn't fix the problem.</p> <pre><code>db.createUser( { user: &quot;rootuser&quot;, pwd: &quot;rootpass&quot;, roles:[ { role: &quot;readWrite&quot;, db: &quot;foober&quot; } ] } ); </code></pre> <p>Also the mongodb logs show that the rootuser can't be found in admin database, but when I go to the mongo express the user is present in the admin database.</p>
[ { "answer_id": 74648578, "author": "Steve Storck", "author_id": 8031498, "author_profile": "https://Stackoverflow.com/users/8031498", "pm_score": 1, "selected": false, "text": "spring.data.mongodb.host mongodb data" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20100274/" ]
74,648,412
<p>I have currently one dict with key-value and one list with values. e.g.</p> <pre class="lang-py prettyprint-override"><code>data = { 'total': { '06724': 0, '06725': 0, '06726': 0, '06727': 0, '06712': 22, '06713': 35, '06714': 108, '06715': 70, '06716': 0, '06717': 24, '06718': 0, '06719': 0, '06720': 0, '06709': 75, '06710': 123, '06711': 224, '06708': 28, '06723': 0, '06721': 0, '06722': 0 }, 'item_number': ['1', '2', '3', '4', '5', '6', '7', '8', '9'] } for Index, value in enumerate(data['total'].values()): if value and value != '0': print(data['item_number'][Index], value) </code></pre> <p>What I am trying to do is that I want to remove all values in 'total' that has the value 0 meaning that it would only end up being 9 numbers which adds up to the <code>item_number</code> amount.</p> <p>What I am trying to achieve is that I want print out:</p> <p><strong>Expected</strong>:</p> <pre class="lang-py prettyprint-override"><code>{ '1': 22, '2': 35, '3': 108, '4': 70, '5': 24, '6': 75, '7': 123, '8': 224, '9': 28 } </code></pre> <p>where key is the <code>item_number</code> and the value is <code>total</code>.</p> <p>However the code I am currently trying gives me the error:</p> <pre class="lang-none prettyprint-override"><code> print(data['item_number'][Index], value) IndexError: list index out of range </code></pre> <p>which I believe is due to the <code>Index</code> increasing for each loop. I wonder how can I skip the counting increase if the value is 0?</p>
[ { "answer_id": 74648578, "author": "Steve Storck", "author_id": 8031498, "author_profile": "https://Stackoverflow.com/users/8031498", "pm_score": 1, "selected": false, "text": "spring.data.mongodb.host mongodb data" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13019246/" ]
74,648,487
<p>I have two Pandas dataframes. df1 is a time series with 6 columns of values, one of which is column 'name'. df2 is a list of rows each with a unique string in the 'name' column and a the same date in each row of the 'date' column---all rows have the same date value from an observation that occurred on same date.</p> <p>df1--&gt;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date</th> <th style="text-align: left;">name</th> <th style="text-align: left;">score</th> <th style="text-align: left;">stat1</th> <th style="text-align: left;">stat2</th> <th style="text-align: left;">pick</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2022-1-1</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">23.3</td> <td style="text-align: left;">0.234</td> <td style="text-align: left;">34</td> <td style="text-align: left;">NaN</td> </tr> <tr> <td style="text-align: left;">2022-1-2</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">21.1</td> <td style="text-align: left;">0.431</td> <td style="text-align: left;">14</td> <td style="text-align: left;">NaN</td> </tr> <tr> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">29.9</td> <td style="text-align: left;">1.310</td> <td style="text-align: left;">4</td> <td style="text-align: left;">NaN</td> </tr> <tr> <td style="text-align: left;">2022-1-4</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">11.3</td> <td style="text-align: left;">9.310</td> <td style="text-align: left;">3</td> <td style="text-align: left;">NaN</td> </tr> </tbody> </table> </div> <p>df1 Index is Date</p> <p>df2--&gt;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">index</th> <th style="text-align: left;">Date</th> <th style="text-align: left;">name</th> <th style="text-align: left;">pick</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">0</td> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">QRS</td> <td style="text-align: left;">23.3</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">21.1</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">DBA</td> <td style="text-align: left;">29.9</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">KLL</td> <td style="text-align: left;">11.3</td> </tr> </tbody> </table> </div> <p>I would like to merge / add the row from df2 to the row in df1 where 'name' and 'date' criteria are met.</p> <p>I've reviewed many articles here and elsewhere as well as trying .merge as follows:</p> <pre><code> df3['pick'] = pd.merge(df1, df2, how='outer', on=['name']) </code></pre> <p>Success is to get df2 or a new df3 to look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date</th> <th style="text-align: left;">name</th> <th style="text-align: left;">score</th> <th style="text-align: left;">stat1</th> <th style="text-align: left;">stat2</th> <th style="text-align: left;">pick</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2022-1-1</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">23.3</td> <td style="text-align: left;">0.234</td> <td style="text-align: left;">34</td> <td style="text-align: left;">NaN</td> </tr> <tr> <td style="text-align: left;">2022-1-2</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">21.1</td> <td style="text-align: left;">0.431</td> <td style="text-align: left;">14</td> <td style="text-align: left;">NaN</td> </tr> <tr> <td style="text-align: left;">2022-1-3</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">29.9</td> <td style="text-align: left;">1.310</td> <td style="text-align: left;">4</td> <td style="text-align: left;">21.1</td> </tr> <tr> <td style="text-align: left;">2022-1-4</td> <td style="text-align: left;">ABC</td> <td style="text-align: left;">11.3</td> <td style="text-align: left;">9.310</td> <td style="text-align: left;">3</td> <td style="text-align: left;">NaN</td> </tr> </tbody> </table> </div> <p>Where df1 is updated based on the relevant row from df2 OR a new df3 is the resulting combination of df1 and df2 where the 'pick' value of 21.1 is inserted to match the appropriate date and name.</p> <p>Guidance would be most appreciated.</p>
[ { "answer_id": 74648578, "author": "Steve Storck", "author_id": 8031498, "author_profile": "https://Stackoverflow.com/users/8031498", "pm_score": 1, "selected": false, "text": "spring.data.mongodb.host mongodb data" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176945/" ]
74,648,506
<p>I am trying to scrape data from <a href="https://www.onthesnow.com/alberta/lake-louise/historical-snowfall" rel="nofollow noreferrer">https://www.onthesnow.com/alberta/lake-louise/historical-snowfall</a> however the default script only shows the monthly totals and not the annual totals. There is a tab you have to select 'Annual' on the webpage to show the annual totals. <a href="https://i.stack.imgur.com/h8k4S.png" rel="nofollow noreferrer">website source code showing the table</a> I can successfully scrape the monthly totals but I am unsuccessful in returning the annual totals. <a href="https://i.stack.imgur.com/1KGvE.png" rel="nofollow noreferrer">Annual totals table</a></p> <pre><code>def historic_snowfall(): #Resort naming convetion on OpenSnow.com # Revelstoke, BC: british-columbia, revelstoke-mountain # Whistler, BC: british-columbia, whistler-blackcomb # Lake Louise, AB: alberta, lake-louise # Big Sky, MT: montana, big-sky-resort # Snowbird, UT: utah, snowbird # Palisades: califronia, squaw-valley-usa # Steamboat, CO: colorado, steamboat # Copper Mountain, CO: colorado, copper-mountain # Aspen, CO: colorado, aspen-snowmass # Jackson Hole, WY: wyoming, jackson-hole # Taos, NM: taos-ski-valley resort_table = ['alberta/lake-louise', 'montana/big-sky-resort', 'utah/snowbird', 'california/squaw-valley-usa', 'colorado/steamboat', 'colorado/copper-mountain', 'colorado/aspen-snowmass', 'wyoming/jackson-hole', 'new-mexico/taos-ski-valley' ] resort = (resort_table[1]) hsnow_url = 'https://www.onthesnow.com/' + resort + '/historical-snowfall' page = requests.get(hsnow_url) soup = BeautifulSoup(page.content, &quot;html.parser&quot;) data = [] table = soup.find('table') # Find table table_body = table.find('tbody') # Find body of table rows = table_body.find_all('tr') #find rows within table for row in rows: cols = row.find_all('td') # within rows pull column data cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Get rid of empty values return data #returns monthly averages not yearly results </code></pre>
[ { "answer_id": 74648578, "author": "Steve Storck", "author_id": 8031498, "author_profile": "https://Stackoverflow.com/users/8031498", "pm_score": 1, "selected": false, "text": "spring.data.mongodb.host mongodb data" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660440/" ]
74,648,573
<p>I will put in the code first.</p> <pre><code>{gameModes.map((gameMode, key) =&gt; { return ( &lt;&gt; &lt;div className={styles.gameMode} key={key} onClick={gameModeHandler}&gt; &lt;div className={styles.gameModeContent}&gt; &lt;img src={gameMode.gameModeArtwork} alt=&quot;&quot; /&gt; &lt;p className={styles.modeTitle}&gt;{gameMode.gameModeTitle}&lt;/p&gt; &lt;p className={styles.modeDesc}&gt; {gameMode.gameModeDesc} &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/&gt; ); })} </code></pre> <p><strong>The onClick function</strong></p> <pre><code>const gameModeHandler = (e) =&gt; { console.log(e.target.value) } </code></pre> <p>Basically what I want is, when the onClick takes effect it passes in the gameMode.title to the onClick to console.log it. I do not know how to pass the onClick in a way where it has access to that data in the loop.</p>
[ { "answer_id": 74648615, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "onClick={() => gameModeHandler(gameMode.title)}" }, { "answer_id": 74648752, "author": "Collins USHI", "author_id": 11718709, "author_profile": "https://Stackoverflow.com/users/11718709", "pm_score": 2, "selected": true, "text": "onClick={()=>gameModeHandler(gameMode.gameModeTitle)}\n const gameModeHandler = (gameModeTitle) => {\n console.log(gameModeTitle)\n }\n onClick={()=>gameModeHandler(gameMode)}\n const gameModeHandler = (gameMode) => {\n console.log(gameMode)\n }\n console.log(gameMode.gameModeTitle)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18549005/" ]
74,648,592
<p>I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm working with serializers for the first time and I'm trying to move past some issues I've been having.</p> <p>Functionality: the user enters in a friend's email address. For the purposes of this test, the email address needs to be at least 6 characters long. So something like &quot;a@a.co&quot; (6 char) would be acceptable, but &quot;a@a.c&quot; (5 char) would not be accepted. Users can enter up to 10 emails at a time.</p> <p>What I'm currently struggling with is what function to use for &quot;is_valid&quot;? I know Django forms has something for this, but I haven't found a satisfactory method for serializers.</p> <p>Here is what's currently in serializers.py.</p> <pre><code>from django.core.validators import MinValueValidator, MaxValueValidator from rest.framework.fields import ListField from rest.framework import serializers class EmailList(ListField): &quot;&quot;&quot;Will validate the email input&quot;&quot;&quot; def to_internal_value(self, data): # if the EmailList is not valid, then a ValidationError should be raised--here's where I'm wondering what to put raise serializers.ValidationError({&quot;invalid_email&quot;: &quot;Email is invalid, please recheck&quot;.}) class EmailListSerializer(serializers.Serializer): &quot;&quot;&quot;Serializer for the email list&quot;&quot;&quot; emails = EmailList( required=True child=Serializers.CharField( validators= [ MinLengthValidator(6, message=&quot;too short&quot;), MaxLengthValidator(50, message=&quot;too long&quot;), ], ), max_length=10, error_messages = ({&quot;invalid_email&quot;: &quot;Email is invalid, please recheck.&quot;} ) </code></pre> <p>Can anyone assist as to what function I should put in the to_internal_value method of the EmailList class to check that the emails are valid?</p>
[ { "answer_id": 74648615, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "onClick={() => gameModeHandler(gameMode.title)}" }, { "answer_id": 74648752, "author": "Collins USHI", "author_id": 11718709, "author_profile": "https://Stackoverflow.com/users/11718709", "pm_score": 2, "selected": true, "text": "onClick={()=>gameModeHandler(gameMode.gameModeTitle)}\n const gameModeHandler = (gameModeTitle) => {\n console.log(gameModeTitle)\n }\n onClick={()=>gameModeHandler(gameMode)}\n const gameModeHandler = (gameMode) => {\n console.log(gameMode)\n }\n console.log(gameMode.gameModeTitle)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5513336/" ]
74,648,642
<p>my name is Jan, I have to do a project for high school, the fact is that I have made a code to access an api, but I cannot display the results of an array that has the api on the screen. This is the code : `</p> <pre><code>document.querySelector(&quot;button&quot;).addEventListener(&quot;click&quot;, getCoin); function getCoin(){ let coin = document.querySelector(&quot;input&quot;).value.split(&quot; &quot;).join(&quot; &quot;) console.log(coin) fetch(&quot;https://open.er-api.com/v6/latest/&quot; + coin) .then (res =&gt; res.json()) .then (data =&gt; { console.log(data.rates) document.querySelector(&quot;#coinName&quot;).innerText = data.base_code document.querySelector(&quot;#coinRates&quot;).innerText = data.rates document.querySelector(&quot;#coinProvider&quot;).innerText = data.provider document.querySelector(&quot;#coinTime&quot;).innerText = data.time_last_update_utc document.querySelector(&quot;#coinProxTime&quot;).innerText = data.time_next_update_utc }) } </code></pre> <p>` It only works if I indicate a specific coin at document.querySelector(&quot;#coinRates&quot;).innerText = data.rates, and what I want is for it to show me all the values ​​on the screen. I would be very grateful if you could help me.</p> <p>I have tried with a querySelectALL, also with the for loop, although I think I have done it wrong</p>
[ { "answer_id": 74648615, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "onClick={() => gameModeHandler(gameMode.title)}" }, { "answer_id": 74648752, "author": "Collins USHI", "author_id": 11718709, "author_profile": "https://Stackoverflow.com/users/11718709", "pm_score": 2, "selected": true, "text": "onClick={()=>gameModeHandler(gameMode.gameModeTitle)}\n const gameModeHandler = (gameModeTitle) => {\n console.log(gameModeTitle)\n }\n onClick={()=>gameModeHandler(gameMode)}\n const gameModeHandler = (gameMode) => {\n console.log(gameMode)\n }\n console.log(gameMode.gameModeTitle)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20660545/" ]
74,648,666
<p>I am trying to use BeautifulSoup to scrape a particular download URL from a web page, based on a partial text match. There are many links on the page, and it changes frequently. The html I'm scraping is full of sections that look something like this:</p> <pre><code>&lt;section class=&quot;onecol habonecol&quot;&gt; &lt;a href=&quot;https://longGibberishDownloadURL&quot; title=&quot;Download&quot;&gt; &lt;img src=&quot;\azure_storage_blob\includes\download_for_windows.png&quot;/&gt; &lt;/a&gt; sentinel-3.2022335.1201.1507_1608C.ab.L3.FL3.v951T202211_1_3.CIcyano.LakeOkee.tif &lt;/section&gt; </code></pre> <p>The second to last line (sentinel-3.2022335...LakeOkee.tif) is the part I need to search using a partial string to pull out the correct download url. The code I have attempted so far looks something like this:</p> <pre><code>import requests, re from bs4 import BeautifulSoup reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'html.parser') result = soup.find('section', attrs={'class':'onecol habonecol'}, string=re.compile(?)) </code></pre> <p>I've been searching StackOverflow a long time now and while there are similar questions and answers, none of the proposed solutions have worked for me so far (re.compile, lambdas, etc.). I am able to pull up a section if I remove the string argument, but when I try to include a partial matching string I get None for my result. I'm unsure what to put for the string argument (? above) to find a match based on partial text, say if I wanted to find the filename that has &quot;CIcyano&quot; somewhere in it (see second to last line of html example at top).</p> <p>I've tried multiple methods using re.compile and lambdas, but I don't quite understand how either of those functions really work. I was able to pull up other sections from the html using these solutions, but something about this filename string with all the periods seems to be preventing it from working. Or maybe it's the way it is positioned within the section? Perhaps I'm going about this the wrong way entirely.</p> <p>Is this perhaps considered part of the section id, and so the string argument can't find it?? An example of a section on the page that I AM able to find has html like the one below, and I'm easily able to find it using the string argument and re.compile using &quot;Name&quot;, &quot;^N&quot;, etc.</p> <pre><code>&lt;section class=&quot;onecol habonecol&quot;&gt; &lt;h3&gt; Name &lt;/h3&gt; &lt;/section&gt; </code></pre> <p>Appreciate any advice on how to go about this! Once I get the correct section, I know how to pull out the URL via the a tag.</p> <p>Here is the <a href="https://view-source:https://products.coastalscience.noaa.gov/habs_explorer/index.php?path=ajZiOVoxaHZNdE5nNytEb3RZdU5iYjNnK3AvTWRrYmNWbXU0K0YvMlA1UlBtTWZlRFV3R1RicVRYb2pxeVJBUA==&amp;uri=VWtuM1UzbVNVN0RsZzJMeTJvNlNpM29OalF0WTFQQjVZVnpuS3o5bnh1Ym0vYWhtWEh4ck1hREVUamE4SDZ0M2tsd1M1OWg3UDJ0djIrNEkvbXliRUJ3WjkrKzdIcUYrN1JsZ1I5NFlsaHBZbUJWV0pHZ3NFZUVnQW56aTFIbEw=&amp;type=bllEUXA3TmhSK21RVDlqbFYxMmEwdz09" rel="nofollow noreferrer">full html</a> of the page I'm scraping, if that helps clarify the structure I'm working against.</p>
[ { "answer_id": 74648615, "author": "Zac Anger", "author_id": 5774952, "author_profile": "https://Stackoverflow.com/users/5774952", "pm_score": 0, "selected": false, "text": "onClick={() => gameModeHandler(gameMode.title)}" }, { "answer_id": 74648752, "author": "Collins USHI", "author_id": 11718709, "author_profile": "https://Stackoverflow.com/users/11718709", "pm_score": 2, "selected": true, "text": "onClick={()=>gameModeHandler(gameMode.gameModeTitle)}\n const gameModeHandler = (gameModeTitle) => {\n console.log(gameModeTitle)\n }\n onClick={()=>gameModeHandler(gameMode)}\n const gameModeHandler = (gameMode) => {\n console.log(gameMode)\n }\n console.log(gameMode.gameModeTitle)\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415819/" ]
74,648,678
<p>I'm writing a program to find genes in a large string of DNA.</p> <p>My output is correct on small input strings of DNA, but when I test it on their example DNA string (which is very large—too large to check manually if my output is correct) it says that my output is incorrect.</p> <p>Here's my code:</p> <pre class="lang-java prettyprint-override"><code>public class part1 { // find stop codon public int findStopCodon(String dna, int startIndex, String stopCodon) { int stopIndex = dna.indexOf(stopCodon, startIndex); if (stopIndex != -1) { if (dna.substring(startIndex, stopIndex + 3).length() % 3 == 0) { return stopIndex; } } return dna.length(); } // find gene public String findGene(String dna, int startIndex) { if ( startIndex != -1) { int taaIndex = findStopCodon(dna, startIndex, &quot;TAA&quot;); int tgaIndex = findStopCodon(dna, startIndex, &quot;TGA&quot;); int tagIndex = findStopCodon(dna, startIndex, &quot;TAG&quot;); int temp = Math.min(taaIndex, tgaIndex); int minIndex = Math.min(temp, tagIndex); if (minIndex &lt;= dna.length() - 3) { return dna.substring(startIndex, minIndex + 3); } } return &quot;&quot;; } // put all genes into a storage resource public StorageResource allGenes(String dna) { StorageResource geneList = new StorageResource(); int prevIndex = 0; while (prevIndex &lt;= dna.length()) { int startIndex = dna.indexOf(&quot;ATG&quot;, prevIndex); if (startIndex == -1) { return geneList; } String gene = findGene(dna, startIndex); if (gene.isEmpty() != true) { geneList.add(gene); } prevIndex = startIndex + gene.length() + 1; } return geneList; } } </code></pre> <p>When executed on this data: <a href="https://users.cs.duke.edu/%7Erodger/GRch38dnapart.fa" rel="nofollow noreferrer">https://users.cs.duke.edu/~rodger/GRch38dnapart.fa</a><br /> This is my output:</p> <pre><code>this many genes: 106 number of length \&gt; 60: 31 number of cgRatio \&gt; 0.35: 54 longest: 282 CTG appears: 224 times </code></pre>
[ { "answer_id": 74662092, "author": "isaiah paget", "author_id": 20434534, "author_profile": "https://Stackoverflow.com/users/20434534", "pm_score": -1, "selected": false, "text": "the problem with my code is that this function should have contained a loop, because in some cases where none of the nearest stop codons are multiples of 3 away from the start index, the function would return dna.length.\n // find stop codon\npublic int findStopCodon(String dna, int startIndex, String stopCodon)\n{\n int stopIndex = dna.indexOf(stopCodon, startIndex);\n if (stopIndex != -1)\n {\n if (dna.substring(startIndex, stopIndex + 3).length() % 3 == 0)\n {\n return stopIndex;\n }\n }\n return dna.length();\n}\n" } ]
2022/12/01
[ "https://Stackoverflow.com/questions/74648678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434534/" ]