qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,669,880
<p>I want to change the text of a button using the onclick property, but the value of the parameter 'text' it's appearing when i load the page. Also when i click the button it's text changes to 'undefined'.</p> <p>That's the code (I starded with Javascript like a week ago so it's probably really bad):</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>function changeText(text) { let btn = document.querySelector('button#btn') btn.innerHTML = text } changeText('new text')</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="btn" onclick="changeText()"&gt;&lt;/button&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74669945, "author": "Jesse Schoonveld", "author_id": 7774656, "author_profile": "https://Stackoverflow.com/users/7774656", "pm_score": 0, "selected": false, "text": "changeText('new text')\n <button id=\"btn\" onclick=\"changeText()\"></button>\n function changeText(text) {\n let btn = document.querySelector('button#btn')\n btn.textContent = text\n}\n<button id=\"btn\" onclick=\"changeText('new text')\"></button>\n" }, { "answer_id": 74669970, "author": "vanowm", "author_id": 2930038, "author_profile": "https://Stackoverflow.com/users/2930038", "pm_score": 1, "selected": false, "text": "changeText onclick changeText(\"new text\") onclick innerHTML textContent function changeText(text) {\n let btn = document.querySelector('button#btn')\n btn.textContent = text\n}\n// changeText('new text') //don't need this <button id=\"btn\" onclick=\"changeText('new text')\">my button</button> document.getElementById()" }, { "answer_id": 74669993, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 1, "selected": false, "text": "changeText('new text') textContent innerText innerHTML function changeText(text) {\n let btn = document.querySelector('button#btn');\n btn.textContent = text;\n} <button id=\"btn\" onclick=\"changeText('New text')\">Old text</button> addEventListener value const input = document.querySelector('input');\nconst button = document.querySelector('button');\n\nbutton.addEventListener('click', changeText);\n\nfunction changeText() {\n button.textContent = input.value;\n} <input type=\"text\">\n<button type=\"button\">Old text</button>" }, { "answer_id": 74670021, "author": "penguinpowers", "author_id": 18570186, "author_profile": "https://Stackoverflow.com/users/18570186", "pm_score": 1, "selected": false, "text": "function changetext(text) {\nvar btn = document.getElementById('btn');\nbtn.innerText = text;\n} <button id=\"btn\" onclick=\"changetext('Clicked')\">Click</button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676816/" ]
74,669,889
<p>My problem: I have a known root node that I'm starting with and a specific other target node that I'm trying to find the shortest path to. I'm trying to write Python code to implement the <a href="https://www.geeksforgeeks.org/iterative-deepening-searchids-iterative-deepening-depth-first-searchiddfs/" rel="nofollow noreferrer">Iterative Deepening Breadth-First Search</a> algo, up to some max depth (say, 5 vertices).</p> <p>However, there are two features that (I believe) make this problem unlike virtually all the other SO questions and/or online tutorials I've been able to find so far:</p> <ol> <li><p><strong>I do not yet know the structure of the tree at all</strong>: all I know is that both the root and target nodes exist, as do many other unknown nodes. The root and target nodes could be separated by one vertice, by 5, by 10, etc. Also, the tree is not binary: any node can have none, one, or many sibling nodes.</p> </li> <li><p>When I successfully find a path from the root node to the target node, I need to return the shortest path between them. (Most of the solutions I've seen involve returning the <strong>entire</strong> traversal order required to locate a node, which I don't need.)</p> </li> </ol> <p>How would I go about implementing this? My immediate thought was to try some form of recursion, but that seems much better-suited to Depth-First Search.</p> <p>TLDR: In the example tree below (apologies for ugly design), I want to traverse it from Root to Target in alphabetical order. (This should result in the algorithm skipping the letters K and L, since it will have found the Target node immediately after J.) I want the function to return:</p> <p><code>[Root, B, E, H, Target]</code></p> <p><a href="https://i.stack.imgur.com/syxt6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/syxt6.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74670471, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 2, "selected": true, "text": "class TreeNode:\n def __init__(self, value, children=None, parent=None):\n self.value = value\n self.parent = parent\n self.children = [] if children is None else children\n from queue import Queue\n\ndef path_root2target(root_node, target_value):\n def build_path(target_node):\n path = [target_node]\n while path[-1].parent is not None:\n path.append(path[-1].parent)\n return path[::-1]\n q = Queue()\n q.put(root_node)\n while not q.empty():\n node = q.get()\n if node.value == target_value:\n return build_path(node)\n for child in node.children:\n child.parent = node\n q.put(child)\n raise ValueError('Target node not found')\n >>> D = TreeNode('D')\n>>> A = TreeNode('A', [D])\n>>> B = TreeNode('B')\n>>> C = TreeNode('C')\n>>> R = TreeNode('R', [A, B, C])\n>>> path_root2target(R, 'E')\nValueError: Target node not found\n>>> [node.value for node in path_root2target(R, 'D')]\n['R', 'A', 'D']\n build_path" }, { "answer_id": 74671522, "author": "jayp", "author_id": 3593246, "author_profile": "https://Stackoverflow.com/users/3593246", "pm_score": 0, "selected": false, "text": "# Import the necessary modules\nimport queue\n\n# Define a TreeNode class to represent each node in the tree\nclass TreeNode:\n def __init__(self, value, children=[]):\n self.value = value\n self.children = children\n\n\n# Define a function to perform the search\ndef iterative_deepening_bfs(tree, target):\n # Set the initial depth to 0\n depth = 0\n\n # Create an infinite loop\n while True:\n # Create a queue to store the nodes at the current depth\n q = queue.Queue()\n\n # Add the root node to the queue\n q.put(tree)\n\n # Create a set to track which nodes have been visited\n visited = set()\n\n # Create a dictionary to store the paths to each visited node\n paths = {tree: [tree]}\n\n # Create a variable to track whether the target has been found\n found = False\n\n # Create a loop to process the nodes at the current depth\n while not q.empty():\n # Get the next node from the queue\n node = q.get()\n\n # If the node has not been visited yet, process it\n if node not in visited:\n # Check if the node is the target\n if node == target:\n # Set the found variable to a tuple containing the depth and path to the target, and break out of the loop\n found = (depth, paths[node])\n break\n\n # Add the node to the visited set\n visited.add(node)\n\n # Add the node's children to the queue\n for child in node.children:\n q.put(child)\n paths[child] = paths[node] + [child]\n\n # If the target was found, return the depth and path to the target\n if found:\n return found\n\n # Increment the depth and continue the loop\n depth += 1\n\n\nroot = TreeNode(\"Root\")\nnodeA = TreeNode(\"A\")\nnodeB = TreeNode(\"B\")\nnodeC = TreeNode(\"C\")\nnodeD = TreeNode(\"D\")\nnodeE = TreeNode(\"E\")\nnodeF = TreeNode(\"F\")\nnodeG = TreeNode(\"G\")\nnodeH = TreeNode(\"H\")\nnodeI = TreeNode(\"I\")\nnodeJ = TreeNode(\"J\")\nnodeK = TreeNode(\"K\")\nnodeL = TreeNode(\"L\")\ntarget = TreeNode(\"Target\")\n\nroot.children = [nodeA, nodeB, nodeC]\nnodeA.children = [nodeD]\nnodeB.children = [nodeE, nodeF]\nnodeC.children = [nodeG]\nnodeE.children = [nodeH]\nnodeF.children = [nodeI]\nnodeG.children = [nodeJ]\nnodeH.children = [target]\nnodeI.children = [nodeK]\nnodeJ.children = [nodeL]\n\n# Assign the root node to the tree variable\ntree = root\n\n\n\n# Call the iterative_deepening_bfs function to search for the target node\nresult = iterative_deepening_bfs(tree, target)\n\n# Print the depth and path to the target node\nprint(f\"The target was found at depth {result[0]} with path [{', '.join([str(node.value) for node in result[1]])}]\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3593246/" ]
74,669,890
<p>I've wrote the following implementation of a Barrier using atomics only:</p> <pre class="lang-rust prettyprint-override"><code>use std::sync::atomic::{AtomicUsize, Ordering}; pub struct Barrier { pub done: AtomicUsize, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -&gt; Barrier { Barrier { done: AtomicUsize::new(0), tids, } } pub fn wait(&amp;self) { let done = self.done.fetch_add(1, Ordering::SeqCst); if done + 1 == self.tids { self.done.store(0, Ordering::SeqCst); } else { while self.done.load(Ordering::SeqCst) != 0 {} } } } </code></pre> <p>It doesn't work as expected. For example,</p> <pre><code>// inside threads loop barrier.wait(); println!(&quot;a&quot;); barrier.wait(); println!(&quot;b&quot;); </code></pre> <p>Intuitively, it should work, since, once <code>.wait()</code> is called, it will hang on the <code>while</code> loop, breaking free from it after all the threads have called <code>.wait()</code>, and resetting the counter for the next <code>.wait()</code>. Instead, eventually it will hang. Below is an usage example:</p> <pre class="lang-rust prettyprint-override"><code>fn main() { println!(&quot;Hello, world!&quot;); let barrier = &amp;Barrier::new(10); std::thread::scope(|s| { for tid in 0 .. 10 { s.spawn(move || { loop { barrier.wait(); println!(&quot;{} a&quot;, tid); barrier.wait(); println!(&quot;{} b&quot;, tid); } }); } }); } </code></pre>
[ { "answer_id": 74670678, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "1 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};\n\npub struct Barrier {\n pub done: [AtomicUsize; 2],\n pub use_first_done: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: [AtomicUsize::new(0), AtomicUsize::new(0)],\n use_first_done: AtomicBool::new(true),\n tids,\n }\n }\n\n pub fn wait(&self) {\n let done = if self.use_first_done.load(Ordering::SeqCst) {\n &self.done[0]\n } else {\n &self.done[1]\n };\n\n let num_done = done.fetch_add(1, Ordering::SeqCst) + 1;\n if num_done == self.tids {\n self.use_first_done.fetch_xor(true, Ordering::SeqCst);\n done.store(0, Ordering::SeqCst);\n } else {\n while done.load(Ordering::SeqCst) != 0 {}\n }\n }\n}\n\nfn main() {\n println!(\"Hello, world!\");\n\n let barrier = &Barrier::new(10);\n\n std::thread::scope(|s| {\n for tid in 0..10 {\n s.spawn(move || loop {\n barrier.wait();\n println!(\"{} a\", tid);\n barrier.wait();\n println!(\"{} b\", tid);\n });\n }\n });\n}\n done use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};\n\npub struct Barrier {\n pub done: AtomicUsize,\n pub iteration: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: AtomicUsize::new(0),\n iteration: AtomicBool::new(false),\n tids,\n }\n }\n\n pub fn wait(&self) {\n let iteration = self.iteration.load(Ordering::SeqCst);\n let num_done = self.done.fetch_add(1, Ordering::SeqCst) + 1;\n if num_done == self.tids {\n self.done.store(0, Ordering::SeqCst);\n self.iteration.fetch_xor(true, Ordering::SeqCst);\n } else {\n while iteration == self.iteration.load(Ordering::SeqCst) {}\n }\n }\n}\n\nfn main() {\n println!(\"Hello, world!\");\n\n let barrier = &Barrier::new(10);\n\n std::thread::scope(|s| {\n for tid in 0..10 {\n s.spawn(move || loop {\n barrier.wait();\n println!(\"{} a\", tid);\n barrier.wait();\n println!(\"{} b\", tid);\n });\n }\n });\n}\n" }, { "answer_id": 74680794, "author": "Silvestr", "author_id": 3324341, "author_profile": "https://Stackoverflow.com/users/3324341", "pm_score": 1, "selected": false, "text": "pub struct Barrier {\n pub done: AtomicUsize,\n pub iteration: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: AtomicUsize::new(0),\n iteration: AtomicBool::new(false),\n tids,\n }\n }\n\n pub fn wait(&self) {\n┌-----┬ let iteration = self.iteration.load(Ordering::Relaxed);\n| | let num_done = self.done.fetch_add(1, Ordering::AcqRel) + 1;\n| | if num_done == self.tids {\n| └-> self.done.store(0, Ordering::Relaxed);\n| self.iteration.fetch_xor(true, Ordering::AcqRel);\nX return;\n| }\n|\n└-----> // let iteration = self.iteration.load(Ordering::Relaxed);\n // Instruction couldn't be moved here because we have a request to \n // see all memory changes self.iteration.fetch_xor with \n // AcqRel ordering. It's safe to use here Relaxed ordering.\n\n // For example, we could imagine that Acquire-Release ordering is \n // like a sandwich.\n ┌----- ...instructions, could be moved inside of a sandwich\n | Acquire\n ├-----> \n | Release\n └-X--> ...instructions, but not here.\n\n\n // Cares only for changes in self.iteration\n // Let's use here the lowest memory ordering\n while iteration == self.iteration.load(Ordering::Relaxed) {\n // I think that there could be saved a few CPU cycles if we give \n // a compiler a hint that it's a waiting loop.\n // Note: It's a Clippy suggestion.\n std::hint::spin_loop();\n\n // Also, could be used yield, but is better to use a hint\n // std::thread::yield_now();\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031791/" ]
74,669,901
<p>I've tried to create the simplest vertical line with a random x value between 0-5 at each vertex, and an increase in 10px in the y value at a time. Why is my line not showing?</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>function setup() { createCanvas(400, 400); noLoop(); } function draw() { background(220); var y = 10; var r = 0; beginShape(); vertex(0, 0); for (var i = 0; i &lt; height; i += 10) { r = random(0, 5); console.log(r + " " + y); vertex(r, y); translate(r, y); y += 10; } endShape(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74670201, "author": "neozero", "author_id": 18646425, "author_profile": "https://Stackoverflow.com/users/18646425", "pm_score": 2, "selected": false, "text": "function draw() {\n background(220);\n var y = 10;\n var r = 0;\n var random_old = 0;\n for (var i = 0; i < height; i += 10) {\n beginShape(LINES);\n r = random(0, 5);\n console.log(r + \" \" + y);\n vertex(r, y);\n y += 10;\n r = random(0, 5);\n vertex(r, y);\n endShape();\n translate((r - random_old) * 10, 0);\n random_old = r;\n y += 10;\n }\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>" }, { "answer_id": 74671500, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 3, "selected": true, "text": "translate() translate() beginShape() endShape() vertex() translate() function setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n vertex(r, y);\n //translate(r, y); // <-- only change\n y += 10;\n }\n endShape(CLOSE);\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script> function setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n push();\n translate(width / 2, 0);\n let lastX = 0;\n let lastY = 0;\n\n for (let y = 0; y <= height; y += 10) {\n const x = random(0, 5)\n line(lastX, lastY, x, y);\n lastX = x;\n lastY = y;\n }\n \n pop();\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script> function setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n \n for (let i = 0; i < width; i += 5) {\n push();\n translate(i, 0);\n let lastX = 0;\n let lastY = 0;\n\n for (let y = 0; y <= height; y += 10) {\n const x = random(0, 5)\n line(lastX, lastY, x, y);\n lastX = x;\n lastY = y;\n }\n\n pop();\n }\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>" }, { "answer_id": 74671595, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "draw() draw() function setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n console.log(r + \" \" + y);\n vertex(r, y);\n translate(r, y);\n y += 10;\n }\n endShape();\n}\n\ndraw();\n translate() vertex() translate() function setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n console.log\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3253373/" ]
74,669,902
<p>I'm implementing a Laravel API + React SPA with Sanctum authentication.</p> <p>With Sanctum, before requesting the actual login route, you need to send a request to /sanctum/csrf-cookie 'to initialize csrf protection'.</p> <p>Currently I have this RTK Query api:</p> <pre><code>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;; import { API_HOST } from &quot;./config&quot;; export const authApi = createApi({ reducerPath: &quot;authApi&quot;, baseQuery: fetchBaseQuery({ baseUrl: `${API_HOST}`, }), endpoints: (builder) =&gt; ({ initCsrf: builder.mutation&lt;void, void&gt;({ query() { return { url: &quot;sanctum/csrf-cookie&quot;, credentials: &quot;include&quot;, headers: { &quot;X-Requested-With&quot;: &quot;XMLHttpRequest&quot;, &quot;Content-Type&quot;: &quot;application/json&quot;, Accept: &quot;application/json&quot;, }, }; }, }), loginUser: builder.mutation&lt;{ access_token: string; status: string }, { username: string; password: string }&gt;({ query(data) { return { url: &quot;login&quot;, method: &quot;POST&quot;, body: data, credentials: &quot;include&quot;, headers: { &quot;X-Requested-With&quot;: &quot;XMLHttpRequest&quot;, &quot;Content-Type&quot;: &quot;application/json&quot;, Accept: &quot;application/json&quot;, }, }; }, async onQueryStarted(args, { dispatch, queryFulfilled }) { try { await queryFulfilled; } catch (err) { console.error(err); } }, }), logoutUser: builder.mutation&lt;void, void&gt;({ query() { return { url: &quot;logout&quot;, credentials: &quot;include&quot;, }; }, }), }), }); export const { useLoginUserMutation, useLogoutUserMutation, useInitCsrfMutation } = authApi; </code></pre> <p>Then in my login page, when the user clicks the login button, I call:</p> <pre><code>const onSubmitHandler: SubmitHandler&lt;LoginInput&gt; = (values) =&gt; { initCsrf() .then(() =&gt; { loginUser(values); }) .catch((err) =&gt; { console.error(err); }); }; </code></pre> <p>The first request is working and sets the cookie but the second returns with a 419 CSRF Token mismatch exception.</p> <p>Examining the requests, the login request contains the XSRF-TOKEN cookie with the token that I got in the first request so it should work ok.</p> <p>This worked before with Axios using the same structure (first request to establish the cookie and the second including the cookie).</p>
[ { "answer_id": 74669953, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 1, "selected": false, "text": "loginUser: builder.mutation<{ access_token: string; status: string }, { username: string; password: string }>({\n query(data) {\n return {\n url: \"login\",\n method: \"POST\",\n body: data,\n headers: {\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"X-XSRF-TOKEN\": document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1], // add this line\n },\n };\n },\n async onQueryStarted(args, { dispatch, queryFulfilled }) {\n try {\n await queryFulfilled;\n } catch (err) {\n console.error(err);\n }\n },\n }),\n" }, { "answer_id": 74671949, "author": "chuysbz", "author_id": 173299, "author_profile": "https://Stackoverflow.com/users/173299", "pm_score": 0, "selected": false, "text": "decodeURIComponent" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173299/" ]
74,669,923
<pre><code>s=0 for i in range(3,20,2): if i&gt;10: break else: s=s+i print(s) </code></pre> <p>how can i transform this code into a while loop?</p> <p>I don't know how to include the step.</p>
[ { "answer_id": 74669954, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 1, "selected": false, "text": "s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n" }, { "answer_id": 74669972, "author": "Vimal Vambaravelli", "author_id": 20660371, "author_profile": "https://Stackoverflow.com/users/20660371", "pm_score": 1, "selected": true, "text": "s,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n" }, { "answer_id": 74670045, "author": "Ruslan", "author_id": 11381688, "author_profile": "https://Stackoverflow.com/users/11381688", "pm_score": 0, "selected": false, "text": "s = 0\ni = 3\nwhile i < 20:\n if i > 10:\n break\n else:\n s = s + i\n i += 2\nprint(s)\n" }, { "answer_id": 74670263, "author": "Jab", "author_id": 225020, "author_profile": "https://Stackoverflow.com/users/225020", "pm_score": 0, "selected": false, "text": "range sum >>> sum(range(3,10, 2))\n24\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20666046/" ]
74,669,928
<p>Haven't program for a while, but I have this game project where I need to randomized who will be player 1 and player 2 and I need to use a user-defined function because it will be part of a bigger function. Player 1 and 2 should reflect whaat will be printed above. How can I improve my code? I also cannot use global variables.</p> <pre><code>#include&lt;stdio.h&gt; int randomColor(int nRandom, int nRed, int nBlue) { srand(time(NULL)); nRandom = (rand()%2); switch (nRandom) { case 0: nRed = 1; nBlue = 2; printf(&quot;\n\n\tPlayer %d = Red\n&quot;, nRed); printf(&quot;\tPlayer %d = Blue\n&quot;, nBlue); break; case 1: nRed = 2; nBlue = 1; printf(&quot;\n\n\tPlayer %d = Blue\n&quot;, nRed); printf(&quot;\tPlayer %d = Red\n&quot;, nBlue); break; } } int main() { int nRandom, nRed, nBlue; randomColor(nRandom, nRed, nBlue); printf(&quot;\nPlayer %d (R) turn&quot;, nRed); printf(&quot;\nPlayer %d (B) turn&quot;, nBlue); } </code></pre>
[ { "answer_id": 74669954, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 1, "selected": false, "text": "s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n" }, { "answer_id": 74669972, "author": "Vimal Vambaravelli", "author_id": 20660371, "author_profile": "https://Stackoverflow.com/users/20660371", "pm_score": 1, "selected": true, "text": "s,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n" }, { "answer_id": 74670045, "author": "Ruslan", "author_id": 11381688, "author_profile": "https://Stackoverflow.com/users/11381688", "pm_score": 0, "selected": false, "text": "s = 0\ni = 3\nwhile i < 20:\n if i > 10:\n break\n else:\n s = s + i\n i += 2\nprint(s)\n" }, { "answer_id": 74670263, "author": "Jab", "author_id": 225020, "author_profile": "https://Stackoverflow.com/users/225020", "pm_score": 0, "selected": false, "text": "range sum >>> sum(range(3,10, 2))\n24\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676860/" ]
74,669,931
<p>I want to create a Java UDF in a snowflake worksheet in order to query GeoIp2 library and get the ISO code of a given IP. I have '@AWS_CSV_STAGE/lib/geoip2-2.8.0.jar','@AWS_CSV_STAGE/geodata/GeoLite2-City.mmdb' already staged. How can i direct the function handler to the method that creates the Database Reader as explained here in the documentation for Java: <a href="https://dev.maxmind.com/geoip/geolocate-an-ip/databases?lang=en#1-install-the-geoip2-client-library" rel="nofollow noreferrer">https://dev.maxmind.com/geoip/geolocate-an-ip/databases?lang=en#1-install-the-geoip2-client-library</a> in general how can i achieve this whole thing below in my udf?</p> <pre><code>File database = new File(&quot;/path/to/maxmind-database.mmdb&quot;) DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName(&quot;128.101.101.101&quot;); CityResponse response = reader.city(ipAddress); Country country = response.getCountry(); </code></pre> <p>so far i wrote this but of course it's not working: anyway i couldn't find much material about how to tackle this kind of problem.</p> <pre><code>CREATE OR REPLACE FUNCTION GEO() returns varchar not null language java imports = ('@AWS_CSV_STAGE/lib/geoip2-2.8.0.jar','@AWS_CSV_STAGE/geodata/GeoLite2-City.mmdb') handler = 'DatabaseReader.Builder'; SELECT GEO(); </code></pre> <p>basically what i want to achieve is to call the UDF on a column of ip address table and get the country code in another column for each ip address.</p>
[ { "answer_id": 74669954, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 1, "selected": false, "text": "s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n" }, { "answer_id": 74669972, "author": "Vimal Vambaravelli", "author_id": 20660371, "author_profile": "https://Stackoverflow.com/users/20660371", "pm_score": 1, "selected": true, "text": "s,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n" }, { "answer_id": 74670045, "author": "Ruslan", "author_id": 11381688, "author_profile": "https://Stackoverflow.com/users/11381688", "pm_score": 0, "selected": false, "text": "s = 0\ni = 3\nwhile i < 20:\n if i > 10:\n break\n else:\n s = s + i\n i += 2\nprint(s)\n" }, { "answer_id": 74670263, "author": "Jab", "author_id": 225020, "author_profile": "https://Stackoverflow.com/users/225020", "pm_score": 0, "selected": false, "text": "range sum >>> sum(range(3,10, 2))\n24\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10192738/" ]
74,669,949
<p>my code:</p> <pre><code>temperature_f = input('Please enter the temperature :') print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade') </code></pre> <p>run code:</p> <pre><code>Please enter the temperature :50 Traceback (most recent call last): File &quot;c:\Users\Aryan\.vscode\py\test1.py&quot;, line 2, in &lt;module&gt; print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade') ~~~~~~~~~~~~~~^~~~ TypeError: unsupported operand type(s) for -: 'str' and 'int' </code></pre> <p>How can I fix this error?</p> <p>I want to write a code that will convert fahrenheit to celsius for me but i am getting this error Please tell me how I can fix this error</p>
[ { "answer_id": 74669954, "author": "islam abdelmoumen", "author_id": 19661530, "author_profile": "https://Stackoverflow.com/users/19661530", "pm_score": 1, "selected": false, "text": "s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n" }, { "answer_id": 74669972, "author": "Vimal Vambaravelli", "author_id": 20660371, "author_profile": "https://Stackoverflow.com/users/20660371", "pm_score": 1, "selected": true, "text": "s,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n" }, { "answer_id": 74670045, "author": "Ruslan", "author_id": 11381688, "author_profile": "https://Stackoverflow.com/users/11381688", "pm_score": 0, "selected": false, "text": "s = 0\ni = 3\nwhile i < 20:\n if i > 10:\n break\n else:\n s = s + i\n i += 2\nprint(s)\n" }, { "answer_id": 74670263, "author": "Jab", "author_id": 225020, "author_profile": "https://Stackoverflow.com/users/225020", "pm_score": 0, "selected": false, "text": "range sum >>> sum(range(3,10, 2))\n24\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676862/" ]
74,669,994
<p>I am using Firebase Auth and Firestore on my app and I using TextInputLayout for Login and Register screens but I got a problem it's like exception named &quot;<strong>The email address is badly formatted</strong>&quot; when I want to add new user from Register screen. I looked up but I can't find any Kotlin question about this problem I'll leave my codes below. I'm waiting your help. Have a good Codes :) .</p> <h1><em>LoginActivity.kt</em></h1> <pre><code>class LoginActivity : AppCompatActivity() { private val db = Firebase.firestore.collection(&quot;users&quot;) private val auth = Firebase.auth private lateinit var binding: ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_login) binding.tvRegister.setOnClickListener { val dialog = BottomSheetDialog(this@LoginActivity) val view = layoutInflater.inflate(R.layout.bottom_sheet_layout, null) dialog.setContentView(view) val etName = view.findViewById&lt;TextInputLayout&gt;(R.id.etName).toString() val etSurname = view.findViewById&lt;TextInputLayout&gt;(R.id.etSurname).toString() val etMail = view.findViewById&lt;TextInputLayout&gt;(R.id.etRegisterEmail).toString() val etPassword = view.findViewById&lt;TextInputLayout&gt;(R.id.etRegisterPassword).toString() val etHeight = view.findViewById&lt;TextInputLayout&gt;(R.id.etHeight).toString() val etWeight = view.findViewById&lt;TextInputLayout&gt;(R.id.etWeight).toString() val btnRegister = view.findViewById&lt;Button&gt;(R.id.btnRegister) btnRegister.setOnClickListener { val user = hashMapOf&lt;Any, String&gt;( &quot;name&quot; to etName, &quot;surname&quot; to etSurname, &quot;email&quot; to etMail, &quot;password&quot; to etPassword, &quot;height&quot; to etHeight, &quot;weight&quot; to etWeight ) if (etName.isNotEmpty() &amp;&amp; etSurname.isNotEmpty() &amp;&amp; etMail.isNotEmpty() &amp;&amp; etPassword.isNotEmpty()) { registerUser(etMail,etPassword,user) } else { Toast.makeText( this@LoginActivity, &quot;You have to fill blanks&quot;, Toast.LENGTH_SHORT ).show() } } dialog.show() } } private fun registerUser(email: String, password: String, user: HashMap&lt;Any, String&gt;) { CoroutineScope(Dispatchers.IO).launch { try { auth.createUserWithEmailAndPassword(email, password) .addOnSuccessListener { db.document(auth.currentUser?.email.toString()).set(user) .addOnSuccessListener { Toast.makeText(this@LoginActivity, &quot;Welcome&quot;, Toast.LENGTH_LONG) .show() checkLogged() } .addOnFailureListener { Toast.makeText(this@LoginActivity, it.message, Toast.LENGTH_LONG) .show() } }.await() } catch (e: java.lang.Exception) { withContext(Dispatchers.Main){ Toast.makeText(this@LoginActivity, e.message, Toast.LENGTH_LONG).show() } } } } private fun checkLogged() { if (auth.currentUser != null) { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() } else { auth.signOut() } } } </code></pre> <h1><em>bottom_sheet_layout.xml</em> (Register Screen)</h1> <pre><code>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot;&gt; &lt;TextView android:id=&quot;@+id/tvRegisterTitle&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;16dp&quot; android:fontFamily=&quot;monospace&quot; android:text=&quot;Register&quot; android:textColor=&quot;@color/primaryDarkColor&quot; android:textSize=&quot;36sp&quot; android:textStyle=&quot;bold&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etName&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginHorizontal=&quot;48dp&quot; android:layout_marginTop=&quot;24dp&quot; android:hint=&quot;@string/name&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/tvRegisterTitle&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;textPersonName&quot; android:textColorHint=&quot;@color/primaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etSurname&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginHorizontal=&quot;48dp&quot; android:layout_marginTop=&quot;8dp&quot; android:hint=&quot;@string/surname&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etName&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;textPersonName&quot; android:textColorHint=&quot;@color/primaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etRegisterEmail&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginHorizontal=&quot;48dp&quot; android:layout_marginTop=&quot;8dp&quot; android:hint=&quot;@string/e_mail&quot; app:endIconMode=&quot;clear_text&quot; app:endIconTint=&quot;@color/secondaryColor&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etSurname&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;textPersonName&quot; android:textColorHint=&quot;@color/secondaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etRegisterPassword&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginHorizontal=&quot;48dp&quot; android:layout_marginTop=&quot;8dp&quot; android:hint=&quot;@string/password&quot; app:endIconMode=&quot;password_toggle&quot; app:endIconTint=&quot;@color/secondaryColor&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etRegisterEmail&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;textPassword&quot; android:textColorHint=&quot;@color/secondaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etHeight&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;110dp&quot; android:layout_height=&quot;80dp&quot; android:layout_marginTop=&quot;8dp&quot; android:hint=&quot;@string/height&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toEndOf=&quot;@id/etWeight&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etRegisterPassword&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;number&quot; android:textColorHint=&quot;@color/secondaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;com.google.android.material.textfield.TextInputLayout android:id=&quot;@+id/etWeight&quot; style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot; android:layout_width=&quot;110dp&quot; android:layout_height=&quot;80dp&quot; android:layout_marginTop=&quot;8dp&quot; android:hint=&quot;@string/weight&quot; app:errorEnabled=&quot;true&quot; app:layout_constraintEnd_toStartOf=&quot;@id/etHeight&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etRegisterPassword&quot;&gt; &lt;com.google.android.material.textfield.TextInputEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:inputType=&quot;number&quot; android:textColorHint=&quot;@color/secondaryDarkColor&quot; /&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; &lt;Button android:id=&quot;@+id/btnRegister&quot; style=&quot;?attr/materialButtonOutlinedStyle&quot; android:layout_width=&quot;250dp&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginVertical=&quot;16sp&quot; android:backgroundTint=&quot;@color/primaryColor&quot; android:text=&quot;@string/register&quot; android:textColor=&quot;@color/secondaryTextColor&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/imageView2&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/etWeight&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView2&quot; android:layout_width=&quot;70dp&quot; android:layout_height=&quot;70dp&quot; android:rotation=&quot;26&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/imageView3&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:srcCompat=&quot;@drawable/broccoli_png&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView3&quot; android:layout_width=&quot;70dp&quot; android:layout_height=&quot;70dp&quot; android:rotation=&quot;26&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/imageView4&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView2&quot; app:srcCompat=&quot;@drawable/broccoli_png&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView4&quot; android:layout_width=&quot;70dp&quot; android:layout_height=&quot;70dp&quot; android:rotation=&quot;26&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView3&quot; app:srcCompat=&quot;@drawable/broccoli_png&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre>
[ { "answer_id": 74670247, "author": "Mokhtar Abdelhalim", "author_id": 11170352, "author_profile": "https://Stackoverflow.com/users/11170352", "pm_score": 1, "selected": false, "text": "auth.currentUser?.email.toString().trim()\n trim()" }, { "answer_id": 74674424, "author": "Mert Ozan", "author_id": 19023704, "author_profile": "https://Stackoverflow.com/users/19023704", "pm_score": 0, "selected": false, "text": "val etMail =view.findViewById<TextInputLayout>(R.id.etRegisterEmail).editText?.text.toString()\n class LoginActivity : AppCompatActivity() {\n\n private val db = Firebase.firestore.collection(\"users\")\n private val auth = Firebase.auth\n private lateinit var binding: ActivityLoginBinding\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n binding = DataBindingUtil.setContentView(this, R.layout.activity_login)\n\n binding.tvRegister.setOnClickListener {\n val dialog = BottomSheetDialog(this@LoginActivity)\n val view = layoutInflater.inflate(R.layout.bottom_sheet_layout, null)\n\n dialog.setContentView(view)\n val btnRegister = view.findViewById<Button>(R.id.btnRegister)\n\n btnRegister.setOnClickListener {\n\n val etName =\n view.findViewById<TextInputLayout>(R.id.etName).editText?.text.toString()\n val etSurname =\n view.findViewById<TextInputLayout>(R.id.etSurname).editText?.text.toString()\n val etMail =\n view.findViewById<TextInputLayout>(R.id.etRegisterEmail).editText?.text.toString()\n val etPassword =\n view.findViewById<TextInputLayout>(R.id.etRegisterPassword).editText?.text.toString()\n val etHeight =\n view.findViewById<TextInputLayout>(R.id.etHeight).editText?.text.toString()\n val etWeight =\n view.findViewById<TextInputLayout>(R.id.etWeight).editText?.text.toString()\n\n val user = User(etName, etSurname, etMail, etHeight, etWeight)\n\n registerUser(etMail, etPassword, user)\n }\n dialog.show()\n }\n }\n\n private fun registerUser(email: String, password: String, user: User) {\n if(email.isNotEmpty()&&password.isNotEmpty()){\n CoroutineScope(Dispatchers.IO).launch {\n try {\n auth.createUserWithEmailAndPassword(email, password)\n .addOnSuccessListener {\n db.document(auth.currentUser?.uid.toString()).set(user)\n checkLogged()\n Toast.makeText(this@LoginActivity,\"Welcome\",Toast.LENGTH_SHORT).show()\n }.await()\n } catch (e: java.lang.Exception) {\n withContext(Dispatchers.Main) {\n Toast.makeText(this@LoginActivity, e.message, Toast.LENGTH_LONG).show()\n }\n }\n }\n }\n }\n\n private fun checkLogged() {\n if (auth.currentUser != null) {\n startActivity(Intent(this@LoginActivity, MainActivity::class.java))\n finish()\n } else {\n auth.signOut()\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19023704/" ]
74,670,016
<p>I've tried to do it using something like:</p> <pre><code>=UNIQUE(query(J2:L,&quot;select J, K, MAX(L) where K matches 'Pending' or K matches 'Finished' group by J, K, L&quot;)) </code></pre> <p>but it doesn't get the unique values, as the expected result shows:</p> <p><a href="https://i.stack.imgur.com/ThnYI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ThnYI.png" alt="enter image description here" /></a></p> <p>Here is a test <a href="https://docs.google.com/spreadsheets/d/1gh5w0czg2JuoA3i5wPu8_eOpC4Q4TXIRhmUrg53nKMU/edit?usp=sharing" rel="nofollow noreferrer">file</a>.</p>
[ { "answer_id": 74670245, "author": "rockinfreakshow", "author_id": 5479575, "author_profile": "https://Stackoverflow.com/users/5479575", "pm_score": 1, "selected": false, "text": "=ARRAYFORMULA(MAP(SORT(UNIQUE(FILTER(J3:J,J3:J<>\"\")),1,1),LAMBDA(jx,vlookup(jx,{SORT(J:L,3,0)},{1,2,3},))))" }, { "answer_id": 74670276, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 1, "selected": true, "text": "=filter({unique(J3:J),byrow(unique(J3:J),LAMBDA(each,query(J3:L,\"Select K,L where J = \"&each&\" order by L desc limit 1\",0)))},unique(J3:J)<>\"\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11832197/" ]
74,670,025
<p>Here's the following code.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class B { private: int a=1; protected: int b=2; public: int c=3; }; class D : protected B { // clause 1 }; class D2 : public D { // clause 2 void x() { c=2; } }; int main() { D d; D2 d2; cout &lt;&lt; d2.c; // clause 3 Error due to c being protected return 0; } </code></pre> <p>Note:</p> <ol> <li>Clause 1 would make c to be protected.</li> <li>Clause 2 would make c (protected in clause 1) to be public again.</li> <li>Why clause 3 failed?</li> </ol>
[ { "answer_id": 74670085, "author": "DeiDei", "author_id": 5212827, "author_profile": "https://Stackoverflow.com/users/5212827", "pm_score": 2, "selected": false, "text": "private public protected private private protected public protected protected private private public c protected D protected D2 public" }, { "answer_id": 74670087, "author": "skybaks", "author_id": 19788693, "author_profile": "https://Stackoverflow.com/users/19788693", "pm_score": 1, "selected": true, "text": "class D : protected B class D\n{\nprotected:\n int b=2;\n int c=3;\n};\n class D2 : public D class D2\n{\nprotected:\n int b=2;\n int c=3;\n};\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
74,670,036
<p>This code is supposed to provide contrasting fg and bg color codes, However there's a bug:</p> <pre class="lang-js prettyprint-override"><code>function randomColorPair() { const bg = '#' + Math.floor(Math.random() * 16777215).toString(16); let fg = '#' + Math.floor(Math.random() * 16777215).toString(16); while (Math.abs(parseInt(bg.substring(1), 16) - parseInt(fg.substring(1), 16)) &lt; 0x777777) { fg = '#' + Math.floor(Math.random() * 16777215).toString(16); } return [bg, fg]; } console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); console.log(randomColorPair()); </code></pre> <p>So this function works great, except occassionaly either the bg or fg will only be 4 or 5 characters. Something buggy but it needs to always be six characters for a hex color code.</p>
[ { "answer_id": 74670069, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 2, "selected": true, "text": "function randomColorPair() {\n var bg = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');\n var fg = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');\n\n while (Math.abs(parseInt(bg.substring(1), 16) - parseInt(fg.substring(1), 16)) < 0x777777) {\n fg = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');\n }\n\n return [bg, fg];\n}\n\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\nconsole.log(randomColorPair());\n" }, { "answer_id": 74670073, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 0, "selected": false, "text": ".toString(16) const randomColor = () => (\n '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(0, 6)\n);\nfunction randomColorPair() {\n const bg = randomColor();\n let fg = randomColor();\n \n while (Math.abs(parseInt(bg.substring(1), 16) - parseInt(fg.substring(1), 16)) < 0x777777) {\n fg = randomColor();\n }\n\n return [bg, fg];\n}\nfor (let i = 0; i < 5; i++) {\n console.log(randomColorPair());\n}" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33522/" ]
74,670,039
<p>I have a calculation someting like the following:</p> <pre class="lang-clj prettyprint-override"><code>;; for sake of simplicity we use round numbers (def data [{:a 1} {:a 10} {:a 100}]) (reduce - 0.0 (map :a data)) </code></pre> <p>And it evaluates to <code>-111.0</code>. I want to do the transformation with a transducer to speed it up a bit by preventing unnecessary allocations:</p> <pre><code>(transduce (map :a) - 0.0 data) </code></pre> <p>However, the signum of the result changed to positive! Apparently it does not matter if I use <code>+</code> or <code>-</code> as the reducer in the expression, as the form will evaluate to <code>+111.0</code> in both cases.</p> <p>This is surprising to me, why did the introduction of <code>transduce</code> change the semantics, what am I missing here?</p> <p>(the strange behaviour happens with <code>*</code> and <code>/</code> too!)</p>
[ { "answer_id": 74670096, "author": "erdos", "author_id": 1062189, "author_profile": "https://Stackoverflow.com/users/1062189", "pm_score": 0, "selected": false, "text": "transduce - (transduce (completing -) 0.0 (map :a data))\n (- (transduce + 0.0 (map :a data)))\n" }, { "answer_id": 74671097, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 1, "selected": false, "text": "{:a 1} (reduce - 0.0 (map :a data)) (- (- (- 0.0 1) 10) 100)\n -111.0 - (transduce (map :a) - 0.0 data) (- (- (- (- 0.0 1) 10) 100))\n +111.0 (transduce (completing -) 0.0 (map :a data))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1062189/" ]
74,670,052
<p>I am currently looking at something similar to <code>df</code> what I would like to be able to do is produce soemthing that looks like <code>df2</code>. Where the specified column values are compared next to eachother, the number of specific occurences are counted, and the count is places into a new column in a new dataframe.</p> <p>For example: in <code>df</code> the combination 1, 5, and 9 occur 3 times.</p> <pre><code>df &lt;- data.frame( col1 = c(1,2,3,4,1,2,3,4,1), col2 = c(5,6,7,8,5,6,7,8,5), col3 = c(9,10,11,12,9,10,11,13,9)) </code></pre> <pre><code>df2 &lt;- data.frame( col1 = c(1,2,3,4,4), col2 = c(5,6,7,8,8), col3 = c(9,10,11,12,13), count = c(3,2,2,1,1)) </code></pre> <p>I tried using dplyr</p> <pre><code>df2 &lt;- df %&gt;% distinct(col1,col2, col3) %&gt;% group_by(col3) %&gt;% summarize(&quot;count&quot; = n()) </code></pre> <p>with no success</p>
[ { "answer_id": 74670096, "author": "erdos", "author_id": 1062189, "author_profile": "https://Stackoverflow.com/users/1062189", "pm_score": 0, "selected": false, "text": "transduce - (transduce (completing -) 0.0 (map :a data))\n (- (transduce + 0.0 (map :a data)))\n" }, { "answer_id": 74671097, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 1, "selected": false, "text": "{:a 1} (reduce - 0.0 (map :a data)) (- (- (- 0.0 1) 10) 100)\n -111.0 - (transduce (map :a) - 0.0 data) (- (- (- (- 0.0 1) 10) 100))\n +111.0 (transduce (completing -) 0.0 (map :a data))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10682814/" ]
74,670,080
<p>I am python newbie and have read countless answers here and in other sources, on how to create folders if they do not exist and move files there. However, still I cannot bring it to work.</p> <p>So what I want to do is the following: Keep my downloads folder clean. I want to run the script, it is supposed to move all files to matching extension name folders. If the folder already exists, it does not have to create it.</p> <p>Problems: I want to be able to run the script as often as I want while keeping the newly created folders there. However, then the whole os.listdir part does not work because folders have no file extensions. I tried to solve this by leaving out folders but it does not work as well.</p> <p>I would appreciate any help!</p> <pre><code>from os import scandir import os import shutil basepath = r&quot;C:\Users\me\Downloads\test&quot; for entry in scandir(basepath):     if entry.is_dir():         continue     files = os.listdir(r&quot;C:\Users\me\Downloads\test&quot;)     ext = [f.rsplit(&quot;.&quot;)[1] for f in files]     ext_final = set(ext) try:     [os.makedirs(e) for e in ext_final] except:     print(&quot;Folder already exists!&quot;) for file in files:     for e in ext_final:         if file.rsplit(&quot;.&quot;)[1]==e:             shutil.move(file,e) </code></pre>
[ { "answer_id": 74670096, "author": "erdos", "author_id": 1062189, "author_profile": "https://Stackoverflow.com/users/1062189", "pm_score": 0, "selected": false, "text": "transduce - (transduce (completing -) 0.0 (map :a data))\n (- (transduce + 0.0 (map :a data)))\n" }, { "answer_id": 74671097, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 1, "selected": false, "text": "{:a 1} (reduce - 0.0 (map :a data)) (- (- (- 0.0 1) 10) 100)\n -111.0 - (transduce (map :a) - 0.0 data) (- (- (- (- 0.0 1) 10) 100))\n +111.0 (transduce (completing -) 0.0 (map :a data))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20484264/" ]
74,670,082
<p>Let's say I have an array of variables:</p> <pre><code>let fruits = [apple, orange, banana]; </code></pre> <p>These variables target specific DOM elements</p> <pre><code>apple = document.getElementById(&quot;apple&quot;); orange = document.getElementById(&quot;orange&quot;); banana = document.getElementById(&quot;banana&quot;); </code></pre> <p>I also happen to have another set of variables that basically have &quot;Rot&quot; added to them</p> <pre><code>appleRot = document.getElementById(&quot;appleRot&quot;); orangeRot = document.getElementById(&quot;appleRot&quot;); bananaRot = document.getElementById(&quot;appleRot&quot;); </code></pre> <p>Is it possible to loop through the existing array and add &quot;Rot&quot; to each element so they target the other set of existing variables?</p> <pre><code>let fruits = [apple, orange, banana]; let fruitsRot = fruits.map((x) =&gt; x + &quot;Rot&quot;); </code></pre> <p>is something like this possible without the result being a string but an array of elements that happen to target the second set of variables?</p>
[ { "answer_id": 74670096, "author": "erdos", "author_id": 1062189, "author_profile": "https://Stackoverflow.com/users/1062189", "pm_score": 0, "selected": false, "text": "transduce - (transduce (completing -) 0.0 (map :a data))\n (- (transduce + 0.0 (map :a data)))\n" }, { "answer_id": 74671097, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 1, "selected": false, "text": "{:a 1} (reduce - 0.0 (map :a data)) (- (- (- 0.0 1) 10) 100)\n -111.0 - (transduce (map :a) - 0.0 data) (- (- (- (- 0.0 1) 10) 100))\n +111.0 (transduce (completing -) 0.0 (map :a data))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12976605/" ]
74,670,147
<p>I have an api with details of a farm and I want to show them in different components using an id. Like the data is used in many components and I want to use Context API to display the data in the components.</p> <p>So here is the code that fetches the data</p> <pre><code>let navigate = useNavigate(); const [farm, setFarm] = useState(''); const { username } = useParams(); const { farmId } = useParams(); const [isLoading, setIsLoading] = useState(true); const user = React.useContext(UserContext); useEffect(() =&gt; { let isMounted = true; axios.get(`/api/farm/${username}/${farmId}`).then(res =&gt; { if (isMounted) { if (res.data.status === 200) { setFarm(res.data.farm); setIsLoading(false); console.warn(res.data.farm) } else if (res.data.status === 404) { navigate('/'); toast.error(res.data.message, &quot;error&quot;); } } }); return () =&gt; { isMounted = false }; }, []); </code></pre> <p>The username is okay because I will use the user context to get the user details. Now, how do Use this from a context into the components, because I have tried, and it is not working.</p>
[ { "answer_id": 74670193, "author": "Edwin Dijas Chiwona", "author_id": 2756931, "author_profile": "https://Stackoverflow.com/users/2756931", "pm_score": -1, "selected": false, "text": "useEffect(() => {\n ....\n\n}, [ setIsLoading, setFarm]);\n" }, { "answer_id": 74670512, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "export const FarmContext = React.createContext();\n\nexport function FarmProvider({ children }) {\n const [farm, setFarm] = useState();\n\n return (\n <FarmContext.Provider value={{farm, setFarm}}>\n { children }\n </FarmContext.Provider>\n )\n}\n const [farm, setFarm] = useState();\n const { farm, setFarm } = useContext(FarmContext);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20490773/" ]
74,670,186
<p>The code I have for my button in HTML is this simple</p> <p>What causes the button to not be able to be clicked, even though it is of type button?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.menubutton { background-color: orange; color: black; text-align: center; font-size: 20px; padding: 20px 50px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button class="menubutton" style="position:absolute;left:10%" type="button"&gt;&lt;b&gt;Home&lt;/b&gt;&lt;/button&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74670231, "author": "TechStudent10", "author_id": 20616402, "author_profile": "https://Stackoverflow.com/users/20616402", "pm_score": -1, "selected": false, "text": "type=button <style> <button class=\"menubutton\">\n <b>Home</b>\n</button>\n <style>\n .menubutton {\n position: absolute;\n left: 10%;\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n }\n</style>\n" }, { "answer_id": 74670283, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 2, "selected": false, "text": "document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button> document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n \n /* pointer on hover */\n cursor: pointer;\n /* transition */\n transition: 0.2s ease;\n}\n\n/* hover event */\n.menubutton:hover {\n background-color: lightgrey;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19093112/" ]
74,670,199
<p>I have the following script in a Google Sheet:</p> <pre><code>/** * Create CSV file of Sheet2 * Modified script written by Tanaike * https://stackoverflow.com/users/7108653/tanaike * * Additional Script by AdamD.PE * version 13.11.2022.1 * https://support.google.com/docs/thread/188230855 */ /** Date extraction added by Tyrone */ const date = new Date(); /** Extract today's date */ let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); if (day &lt; 10) { day = '0' + day; } if (month &lt; 10) { month = `0${month}`; } /** Show today's date */ let currentDate = `${day}-${month}-${year}`; /** Date extraction added by Tyrone */ function sheetToCsvModelo0101() { var filename = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetName() + &quot;-01&quot; + &quot; - &quot; + currentDate; // CSV file name filename = filename + '.csv'; var ssid = SpreadsheetApp.getActiveSpreadsheet().getId(); var folders = DriveApp.getFileById(ssid).getParents(); var folder; if (folders.hasNext()) { folder = folders.next(); var user = Session.getEffectiveUser().getEmail(); if (!(folder.getOwner().getEmail() == user || folder.getEditors().some(e =&gt; e.getEmail() == user))) { throw new Error(&quot;This user has no write permission for the folder.&quot;); } } else { throw new Error(&quot;This user has no write permission for the folder.&quot;); } var SelectedRange = &quot;A2:AB3&quot;; var csv = &quot;&quot;; var v = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).getValues(); v.forEach(function (e) { csv += e.join(&quot;,&quot;) + &quot;\n&quot;; }); var newDoc = folder.createFile(filename, csv, MimeType.CSV); console.log(newDoc.getId()); // You can see the file ID. } </code></pre> <p>This script basically creates a <code>.CSV</code> file in the same folder where the worksheet is, using the range defined in <code>var SelectedRange</code>.</p> <p>This script is applied to a button on the worksheet.</p> <p>The question is: how do I make every comma typed in this spreadsheet be converted into another sign, like <code>#</code> before generating the <code>.CSV</code> file in the folder?</p> <p>I would also like to know if instead of generating 1 file in the folder it is possible to generate 2 files, each with a name.</p>
[ { "answer_id": 74670231, "author": "TechStudent10", "author_id": 20616402, "author_profile": "https://Stackoverflow.com/users/20616402", "pm_score": -1, "selected": false, "text": "type=button <style> <button class=\"menubutton\">\n <b>Home</b>\n</button>\n <style>\n .menubutton {\n position: absolute;\n left: 10%;\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n }\n</style>\n" }, { "answer_id": 74670283, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 2, "selected": false, "text": "document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button> document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n \n /* pointer on hover */\n cursor: pointer;\n /* transition */\n transition: 0.2s ease;\n}\n\n/* hover event */\n.menubutton:hover {\n background-color: lightgrey;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19538465/" ]
74,670,208
<p>I have a project management application built with React and GraphQL for which the Github repo can be found <a href="https://github.com/jevoncochran/managr" rel="nofollow noreferrer">here</a>. One of the functionalities allows for deleting a project.</p> <p><a href="https://i.stack.imgur.com/l0Sl2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l0Sl2.png" alt="enter image description here" /></a></p> <p>I am trying to update the cache when I delete an individual project.</p> <pre><code>const [deleteProject] = useMutation(DELETE_PROJECT, { variables: { id: projectId }, update(cache, { data: { deleteProject } }) { const { projects } = cache.readQuery({ query: GET_PROJECTS }); cache.writeQuery({ query: GET_PROJECTS, data: { projects: projects.filter( (project) =&gt; project.id !== deleteProject.id ), }, }); }, onCompleted: () =&gt; navigate(&quot;/&quot;), }); </code></pre> <p>However, when I attempt to do so, I am getting the following error: <code>Error: Cannot destructure property 'projects' of 'cache.readQuery(...)' as it is null</code></p> <p>Can someone help me figure out what's going on? This is what the getProjects query looks like:</p> <pre><code>const GET_PROJECTS = gql` query getProjects { projects { id name description status } } `; </code></pre> <p>Here is the root query:</p> <pre><code>const RootQuery = new GraphQLObjectType({ name: &quot;RootQueryType&quot;, fields: { projects: { type: new GraphQLList(ProjectType), resolve(parent, args) { return Project.find(); }, }, project: { type: ProjectType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Project.findById(args.id); }, }, clients: { type: new GraphQLList(ClientType), resolve(parent, args) { return Client.find(); }, }, client: { type: ClientType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Client.findById(args.id); }, }, }, }); </code></pre>
[ { "answer_id": 74670231, "author": "TechStudent10", "author_id": 20616402, "author_profile": "https://Stackoverflow.com/users/20616402", "pm_score": -1, "selected": false, "text": "type=button <style> <button class=\"menubutton\">\n <b>Home</b>\n</button>\n <style>\n .menubutton {\n position: absolute;\n left: 10%;\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n }\n</style>\n" }, { "answer_id": 74670283, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": 2, "selected": false, "text": "document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button> document.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n}) .menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n \n /* pointer on hover */\n cursor: pointer;\n /* transition */\n transition: 0.2s ease;\n}\n\n/* hover event */\n.menubutton:hover {\n background-color: lightgrey;\n} <button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10521235/" ]
74,670,210
<p>While developing my personal portfolio using Next.js, I ran into an error where the prop &quot;children&quot; was not working. I am using tsx.</p> <p>Layout.tsx</p> <pre><code>import styles from &quot;./layout.module.css&quot;; export default function Layout({ children, ...props }) { return ( &lt;&gt; &lt;main className={styles.main} {...props}&gt;{children}&lt;/main&gt; &lt;/&gt; ); } </code></pre> <p>I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(</p>
[ { "answer_id": 74670243, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": -1, "selected": false, "text": "import styles from \"./layout.module.css\";\n\nexport default function Layout({ children, ...props }) {\nreturn (\n<>\n<main className={styles.main} {...props} {...{children}}>{children}</main>\n</>\n);\n}\n import styles from \"./layout.module.css\";\n\nexport default function Layout({ children, ...props }) {\nreturn (\n<>\n<main className={styles.main} {...props}>{children}</main>\n</>\n);\n}\n" }, { "answer_id": 74670264, "author": "ddblair", "author_id": 12026911, "author_profile": "https://Stackoverflow.com/users/12026911", "pm_score": 3, "selected": true, "text": "import { ReactNode } from \"react\";\nimport styles from \"./layout.module.css\";\n\nconst type LayoutProps = {\n children: ReactNode;\n // Your other props here.\n}\n\nexport default function Layout({ children, ...props }: LayoutProps) {\n return (\n <>\n <main className={styles.main} {...props}>{children}</main>\n </>\n );\n}\n type any any export default function Layout({ children, ...props }: any) {\n return (\n <>\n <main className={styles.main} {...props}>{children}</main>\n </>\n );\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15144389/" ]
74,670,252
<p>Instead of images, I want to place colors in those spots.</p> <p><a href="https://jsfiddle.net/rza8v51x/" rel="nofollow noreferrer">https://jsfiddle.net/rza8v51x/</a></p> <p>The images are set in a grid layout, and I want to remove them and add colors.</p> <p>In place of the images I want to add colors in those spots.</p> <p>That is all I am trying to do in the code.</p> <p>Replace the images with colors.</p> <p>How would this be done?</p> <pre><code>.channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"&gt; &lt;img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;amp;quality=100 3x" class="responsive-image-component"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74670338, "author": "Zach Jensz", "author_id": 14190543, "author_profile": "https://Stackoverflow.com/users/14190543", "pm_score": 1, "selected": false, "text": ".channel-browser__channels {\n border-top: 1px solid rgba(86, 95, 115, 0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.horizontal-content-browser__content-item {\n padding-top: 100%;\n}\n\n.content-item--channel {\n height: 280px;\n}\n\n.responsive-image-component {\n position: relative;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color: red;\n}\n\n.content-item--channel::after {\n content: '';\n display: block;\n position: absolute;\n bottom: 20px;\n width: 100%;\n aspect-ratio: 1;\n background-color: black;\n} <div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n</div>" }, { "answer_id": 74670383, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 0, "selected": false, "text": "::after /* Added this */\n.channel-browser__channel-grid-item::after {\n content: \"\";\n position: absolute;\n inset: 0;\n /* Edit color here */\n background-color: pink;\n}\n /* Added this */\n .channel-browser__channel-grid-item::after {\n content: \"\"; \n position: absolute;\n inset: 0;\n /* Edit color here */\n background-color: pink;\n}\n\n.channel-browser__channels {\n border-top: 1px solid rgba(86,95,115,0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item{\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color:red;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n\n} <div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n</div>" }, { "answer_id": 74670404, "author": "KnightTheLion", "author_id": 20432259, "author_profile": "https://Stackoverflow.com/users/20432259", "pm_score": 2, "selected": true, "text": ".channel-browser__channels {\n border-top: 1px solid rgba(86,95,115,0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item{\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color:red;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n\n}\n\n.box-color-red {\n background: red;\n }\n \n.box-color-blue {\n background: blue;\n }\n .box-color-yellow {\n background: yellow;\n }\n .box-color-green {\n background: green;\n } <div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red\">\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue\">\n\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow\">\n\n </div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green\">\n\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n</div>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20658906/" ]
74,670,258
<p>req.body returns undefined. Here is my code.</p> <pre><code>const express = require('express'); const app = express(); const courses = [ { id: 1, name: 'course1'}, { id: 2, name: 'course2'}, { id: 3, name: 'course3'}, ]; app.use(express.json()); app.get('/api/courses', (req, res) =&gt; { res.send(courses); }); app.post('/api/courses', (req, res) =&gt;{ const course = { id: courses.length + 1, name: req.body.name }; courses.push(course) res.send(course) }); const port = process.env.PORT || 3000 app.listen(port, () =&gt; console.log(`Listening on port ${port}...`)) </code></pre> <p>Using postman to post an object, for example</p> <pre><code>{ &quot;name&quot; : &quot;newCourse&quot; } </code></pre> <p>will return only id, not returning both the expected id and name. Console.log(course.name) returns undefined. This code is from a tutorial by Programming with Mosh <a href="https://www.youtube.com/watch?v=pKd0Rpw7O48" rel="nofollow noreferrer">https://www.youtube.com/watch?v=pKd0Rpw7O48</a> Time: 33 min I'm a beginner in node and express, any clue and explaination on why this doesn't work as it did in the tutorial?</p>
[ { "answer_id": 74670331, "author": "fırat dede", "author_id": 14147717, "author_profile": "https://Stackoverflow.com/users/14147717", "pm_score": 1, "selected": false, "text": "app.use(express.urlencoded({})) app.use(express.json())" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15963853/" ]
74,670,268
<p>I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns &quot;[]&quot; and never the updated list. Is there a way I can do this?</p> <p>I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent.</p> <p>here is the code:</p> <pre><code>from tkinter import * window = Tk() names = [] ent = Entry(window) ent.pack() def change(): names.append(ent.get()) btn = Button (window, command = change ) btn.pack() print(names) window.mainloop() </code></pre> <p>why is the response always &quot;[]&quot; and not the updated list</p>
[ { "answer_id": 74670365, "author": "mapperx", "author_id": 5887941, "author_profile": "https://Stackoverflow.com/users/5887941", "pm_score": 1, "selected": false, "text": "from tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names)\n\nwindow.mainloop()\n" }, { "answer_id": 74670462, "author": "pollatron", "author_id": 15553798, "author_profile": "https://Stackoverflow.com/users/15553798", "pm_score": 0, "selected": false, "text": "from tkinter import *\nimport pickle\n\nwindow = Tk()\n\n# Create list from file (if no file exists, create empty list)\ntry:\n with open('names.pickle', 'rb') as f: names = pickle.load(f)\nexcept: names = []\n\nent = Entry(window)\nent.pack()\n\ndef change():\n names.append(ent.get())\n\nbtn = Button (window, command = change )\nbtn.pack()\n\nprint(names)\n\ndef onClose():\n with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list\n window.destroy()\n\n# This will call \"onClose\" before closing the window\nwindow.protocol(\"WM_DELETE_WINDOW\", onClose)\nwindow.mainloop()\n names.pickle" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226622/" ]
74,670,273
<p><a href="https://i.stack.imgur.com/ooi2t.png" rel="nofollow noreferrer">s</a></p> <p>I want someone to tell me how to put colors on the code so its easier for me to code.</p>
[ { "answer_id": 74670365, "author": "mapperx", "author_id": 5887941, "author_profile": "https://Stackoverflow.com/users/5887941", "pm_score": 1, "selected": false, "text": "from tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names)\n\nwindow.mainloop()\n" }, { "answer_id": 74670462, "author": "pollatron", "author_id": 15553798, "author_profile": "https://Stackoverflow.com/users/15553798", "pm_score": 0, "selected": false, "text": "from tkinter import *\nimport pickle\n\nwindow = Tk()\n\n# Create list from file (if no file exists, create empty list)\ntry:\n with open('names.pickle', 'rb') as f: names = pickle.load(f)\nexcept: names = []\n\nent = Entry(window)\nent.pack()\n\ndef change():\n names.append(ent.get())\n\nbtn = Button (window, command = change )\nbtn.pack()\n\nprint(names)\n\ndef onClose():\n with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list\n window.destroy()\n\n# This will call \"onClose\" before closing the window\nwindow.protocol(\"WM_DELETE_WINDOW\", onClose)\nwindow.mainloop()\n names.pickle" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950398/" ]
74,670,286
<p>I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message</p> <pre><code>The process cannot access the file because it is being used by another process! </code></pre> <p>and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've tried a few methods, but the end statement keeps popping up.</p> <pre><code># importing pandas #importing os import pandas as pd import os csv_1 = open('SearchResults.csv', 'r') csv_2 = open('SearchResults (1).csv', 'r') csv_3 = open('SearchResults (2).csv', 'r') writer = pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') # merging three csv files df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True) #Exports csv files to excel sheet on DB_1.xlsx df.to_excel(writer, sheet_name='sheetname') csv_1.close() csv_2.close() csv_3.close() writer.save() try: os.remove('SearchResults.csv') print(&quot;The file: {} is deleted!&quot;.format('SearchResults.csv')) except OSError as e: print(&quot;Error: {} - {}!&quot;.format(e.filename, e.strerror)) try: os.remove('SearchResults (1).csv') print(&quot;The file: {} is deleted!&quot;.format('SearchResults (1).csv')) except OSError as e: print(&quot;Error: {} - {}!&quot;.format(e.filename, e.strerror)) try: os.remove('SearchResults (2).csv') print(&quot;The file: {} is deleted!&quot;.format('SearchResults (2).csv')) except OSError as e: print(&quot;Error: {} - {}!&quot;.format(e.filename, e.strerror)) </code></pre> <p>#Results:</p> <pre><code>Error: SearchResults.csv - The process cannot access the file because it is being used by another process! Error: SearchResults (1).csv - The process cannot access the file because it is being used by another process! Error: SearchResults (2).csv - The process cannot access the file because it is being used by another process! </code></pre>
[ { "answer_id": 74670365, "author": "mapperx", "author_id": 5887941, "author_profile": "https://Stackoverflow.com/users/5887941", "pm_score": 1, "selected": false, "text": "from tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names)\n\nwindow.mainloop()\n" }, { "answer_id": 74670462, "author": "pollatron", "author_id": 15553798, "author_profile": "https://Stackoverflow.com/users/15553798", "pm_score": 0, "selected": false, "text": "from tkinter import *\nimport pickle\n\nwindow = Tk()\n\n# Create list from file (if no file exists, create empty list)\ntry:\n with open('names.pickle', 'rb') as f: names = pickle.load(f)\nexcept: names = []\n\nent = Entry(window)\nent.pack()\n\ndef change():\n names.append(ent.get())\n\nbtn = Button (window, command = change )\nbtn.pack()\n\nprint(names)\n\ndef onClose():\n with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list\n window.destroy()\n\n# This will call \"onClose\" before closing the window\nwindow.protocol(\"WM_DELETE_WINDOW\", onClose)\nwindow.mainloop()\n names.pickle" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677031/" ]
74,670,295
<p>I want to merge df1 and df2, by pulling in only the numerics from df2 into df1? This would be a nested (Lookup(xlookup) in excel, but Im having difficulty working this in r? Any info would be much appreciated.</p> <pre><code>df1 &lt;- data.frame(Names = c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;), Rank = c(&quot;R1&quot;,&quot;R3&quot;,&quot;R4&quot;,&quot;R2&quot;,&quot;R5&quot;), Time_in_rank = c(2,4.25,3,1.5,5)) df2 &lt;- data.frame(Time_in_rank =c(0,1,2,3,4), R1 =c(20000,25000,30000,35000,40000), R2 =c(45000,50000,55000,60000,65000), R3 =c(70000,75000,80000,85000,90000), R4 =c(95000,96000,97000,98000,100000), R5 =c(105000,107000,109000,111000,112000)) Desired output Names Time_in_rank Rank Salary A 2 R1 30000 B 4.25 R3 90000 C 3 R4 98000 </code></pre> <p>Close but no cigar - <a href="https://stackoverflow.com/questions/37158839/merge-two-data-frames-considering-a-range-match-between-key-columns">Merge two data frames considering a range match between key columns</a></p> <p>Close but still no cigar - <a href="https://stackoverflow.com/questions/41043047/complex-non-equi-merge-in-r">Complex non-equi merge in R</a></p>
[ { "answer_id": 74670445, "author": "Martin Gal", "author_id": 12505251, "author_profile": "https://Stackoverflow.com/users/12505251", "pm_score": 1, "selected": true, "text": "tidyverse library(dplyr)\nlibrary(tidyr)\n\ndf1 %>% \n mutate(time_floor = floor(Time_in_rank)) %>% \n left_join(df2 %>% \n pivot_longer(-Time_in_rank, names_to = \"Rank\", values_to = \"Salary\"),\n by = c(\"Rank\", \"time_floor\" = \"Time_in_rank\")) %>% \n select(-time_floor)\n Names Rank Time_in_rank Salary\n1 A R1 2.00 30000\n2 B R3 4.25 90000\n3 C R4 3.00 98000\n4 D R2 1.50 50000\n5 E R5 5.00 NA\n df1 Time_in_rank Time_in_rank df2 df2" }, { "answer_id": 74679111, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": false, "text": "library(data.table)\nsetDT(df1)\nsetDT(df2)\ndf1[setnames(melt(df2, id.vars = \"Time_in_rank\"), 1, \"tir\"\n )[, tir2 := shift(tir, type = \"lead\", fill = Inf), by = variable],\n Salary := value,\n on = .(Rank == variable, Time_in_rank >= tir, Time_in_rank < tir2)]\ndf1\n# Names Rank Time_in_rank Salary\n# <char> <char> <num> <num>\n# 1: A R1 2.00 30000\n# 2: B R3 4.25 90000\n# 3: C R4 3.00 98000\n# 4: D R2 1.50 50000\n# 5: E R5 5.00 112000\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670385/" ]
74,670,330
<p>Short backstory: I am trying to create a <code>Readable</code> stream based on data chunks that are emitted back to my server from the client side with WebSockets. Here's a class I've created to &quot;simulate&quot; that behavior:</p> <pre class="lang-js prettyprint-override"><code>class DataEmitter extends EventEmitter { constructor() { super(); const data = ['foo', 'bar', 'baz', 'hello', 'world', 'abc', '123']; // Every second, emit an event with a chunk of data const interval = setInterval(() =&gt; { this.emit('chunk', data.splice(0, 1)[0]); // Once there are no more items, emit an event // notifying that that is the case if (!data.length) { this.emit('done'); clearInterval(interval); } }, 1e3); } } </code></pre> <p>In this post, the <code>dataEmitter</code> in question will have been created like this.</p> <pre class="lang-js prettyprint-override"><code>// Our data is being emitted through events in chunks from some place. // This is just to simulate that. We cannot change the flow - only listen // for the events and do something with the chunks. const dataEmitter = new DataEmitter(); </code></pre> <p>Right, so I initially tried this:</p> <pre class="lang-js prettyprint-override"><code>const readable = new Readable(); dataEmitter.on('chunk', (data) =&gt; { readable.push(data); }); dataEmitter.once('done', () =&gt; { readable.push(null); }); </code></pre> <p>But that results in this error:</p> <pre><code>Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented </code></pre> <p>So I did this, implementing <code>read()</code> as an empty function:</p> <pre class="lang-js prettyprint-override"><code>const readable = new Readable({ read() {}, }); dataEmitter.on('chunk', (data) =&gt; { readable.push(data); }); dataEmitter.once('done', () =&gt; { readable.push(null); }); </code></pre> <p>And it works when piping into a write stream, or sending the stream to my test API server. The resulting <code>.txt</code> file looks exactly as it should:</p> <pre><code>foobarbazhelloworldabc123 </code></pre> <p>However, I feel like there's something quite wrong and hacky with my solution. I attempted to put the listener registration logic (<code>.on('chunk', ...)</code> and <code>.once('done', ...)</code>) within the <code>read()</code> implementation; however, <code>read()</code> seems to get called multiple times, and that results in the listeners being registered multiple times.</p> <p>The Node.js documentation says <a href="https://nodejs.org/api/stream.html#readable_readsize" rel="nofollow noreferrer">this</a> about the <code>_read()</code> method:</p> <blockquote> <p>When readable._read() is called, if data is available from the resource, the implementation should begin pushing that data into the read queue using the this.push(dataChunk) method. _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. _read() may continue reading from the resource and pushing data until readable.push() returns false. Only when _read() is called again after it has stopped should it resume pushing additional data into the queue.</p> </blockquote> <p>After dissecting this, it seems that the consumer of the stream calls upon <code>.read()</code> when it's ready to read more data. And when it is called, data should be pushed into the stream. But, if it is not called, the stream should not have data pushed into it until the method is called again (???). So wait, does the consumer call <code>.read()</code> when it is ready for more data, or does it call it after each time <code>.push()</code> is called? Or both?? The docs seem to contradict themselves.</p> <p>Implementing <code>.read()</code> on <code>Readable</code> is straightforward when you've got a basic resource to stream, but what would be the proper way of implementing it in this case?</p> <p>And also, would someone be able to explain in better terms what the <code>.read()</code> method is on a deeper level, and how it should be implemented?</p> <p>Thanks!</p> <p><strong>Response to the answer:</strong></p> <p>I did try registering the listeners within the <code>read()</code> implementation, but because it is called multiple times by the consumer, it registers the listeners multiple times.</p> <p>Observing this code:</p> <pre class="lang-js prettyprint-override"><code>const readable = new Readable({ read() { console.log('called'); dataEmitter.on('chunk', (data) =&gt; { readable.push(data); }); dataEmitter.once('done', () =&gt; { readable.push(null); }); }, }); readable.pipe(createWriteStream('./data.txt')); </code></pre> <p>The resulting file looks like this:</p> <pre><code>foobarbarbazbazbazhellohellohellohelloworldworldworldworldworldabcabcabcabcabcabc123123123123123123123 </code></pre> <p>Which makes sense, because the listeners are being registered multiple times.</p>
[ { "answer_id": 74670384, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 1, "selected": false, "text": "const readable = new Readable({\n _read() {\n // Register event listeners for the 'chunk' and 'done' events\n dataEmitter.on('chunk', (data) => {\n readable.push(data);\n });\n dataEmitter.once('done', () => {\n readable.push(null);\n });\n },\n});\n class DataEmitter extends EventEmitter {\n constructor() {\n super();\n\n const data = [\"foo\", \"bar\", \"baz\", \"hello\", \"world\", \"abc\", \"123\"];\n // Every second, emit an event with a chunk of data\n const interval = setInterval(() => {\n this.emit(\"chunk\", data.splice(0, 1)[0]);\n\n // Once there are no more items, emit an event\n // notifying that that is the case\n if (!data.length) {\n this.emit(\"done\");\n clearInterval(interval);\n }\n }, 1e3);\n }\n}\n\nclass MyReadable extends Readable {\n constructor(dataEmitter) {\n super();\n this.dataEmitter = dataEmitter;\n }\n\n _read() {\n this.dataEmitter.on(\"chunk\", (data) => {\n this.push(data);\n });\n\n this.dataEmitter.once(\"done\", () => {\n this.push(null);\n });\n }\n}\n\nconst dataEmitter = new DataEmitter();\nconst myReadable = new MyReadable(dataEmitter);\n\n// Pipe the readable stream into a write stream\nmyReadable.pipe(createWriteStream(...));\n" }, { "answer_id": 74670731, "author": "mstephen19", "author_id": 16521381, "author_profile": "https://Stackoverflow.com/users/16521381", "pm_score": 0, "selected": false, "text": "read() class MyReadable extends Readable {\n // Keep track of whether or not the listeners have already\n // been added to the data emitter.\n #registered = false;\n\n _read() {\n // If the listeners have already been registered, do\n // absolutely nothing.\n if (this.#registered) return;\n\n // \"Notify\" the client via websockets that we're ready\n // to start streaming the data chunks.\n const emitter = new DataEmitter();\n\n const handler = (chunk: string) => {\n this.push(chunk);\n };\n\n emitter.on('chunk', handler);\n\n emitter.once('done', () => {\n this.push(null);\n // Clean up the listener once it's done (this is\n // assuming the #emitter object will still be used\n // in the future).\n emitter.off('chunk', handler);\n });\n\n // Mark the listeners as registered.\n this.#registered = true;\n }\n}\n\nconst readable = new MyReadable();\n\nreadable.pipe(createWriteStream('./data.txt'));\n read()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16521381/" ]
74,670,350
<pre><code>const products = [ { product: &quot;banana&quot;, price: 3 }, { product: &quot;mango&quot;, price: 6 }, { product: &quot;potato&quot;, price: &quot; &quot; }, { product: &quot;avocado&quot;, price: 8 }, { product: &quot;coffee&quot;, price: 10 }, { product: &quot;tea&quot;, price: &quot;&quot; }, ]; </code></pre> <pre><code>const productsByPrice = function (arr) { arr.map((item) =&gt; { let output = {}; output[item.product] = item.price; return output; }); }; console.log(productsByPrice(products)) </code></pre> <p>Hello, I am trying to use map() to map the products array to its corresponding prices but the function returns undefined</p> <p>I have tried using the debugger to step through the code and there are values stored in the output variable as it iterates through the array but in the end it returns undefined. I am only new to programming and i cant see why this happens. Thanks alot</p>
[ { "answer_id": 74670391, "author": "D. Seah", "author_id": 3808826, "author_profile": "https://Stackoverflow.com/users/3808826", "pm_score": 0, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = function (arr) {\n return arr.reduce((acc, item) => {\n acc[item.product] = item.price;\n return acc;\n }, {});\n};\n\nconsole.log(productsByPrice(products))\n" }, { "answer_id": 74670468, "author": "ncxop", "author_id": 18096353, "author_profile": "https://Stackoverflow.com/users/18096353", "pm_score": 2, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = function (arr) {\n let output = {};\n arr.map((item) => {\n output[item.product] = item.price;\n });\n return output;\n};\nconsole.log(productsByPrice(products))\n" }, { "answer_id": 74670642, "author": "Your Friend", "author_id": 16021957, "author_profile": "https://Stackoverflow.com/users/16021957", "pm_score": -1, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n ];\n\nconst productsByPrice = products.map(function (arr) {\n return `${arr.product}:${arr.price}`\n})\n\nconsole.log(productsByPrice);" }, { "answer_id": 74670928, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 0, "selected": false, "text": "Object.fromEntries() [key, value] const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = arr => {\n return Object.fromEntries(\n arr.map(({product, price}) => [product, price])\n );\n};\nconsole.log(productsByPrice(products))" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17389090/" ]
74,670,352
<p><a href="https://i.stack.imgur.com/gcwWe.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I am wondering what's the purpose of Target? If the type of Target is hash, how to set the key/value.</p> <pre><code>PS Set-ItemProperty -Path a.txt -Name Target -Value { &quot;key1&quot;:&quot;value1&quot;} At line:1 char:58 + Set-ItemProperty -Path a.txt -Name Target -Value { &quot;key1&quot;:&quot;value1&quot;} + ~~~~~~~~~ Unexpected token ':&quot;value1&quot;' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken </code></pre>
[ { "answer_id": 74670391, "author": "D. Seah", "author_id": 3808826, "author_profile": "https://Stackoverflow.com/users/3808826", "pm_score": 0, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = function (arr) {\n return arr.reduce((acc, item) => {\n acc[item.product] = item.price;\n return acc;\n }, {});\n};\n\nconsole.log(productsByPrice(products))\n" }, { "answer_id": 74670468, "author": "ncxop", "author_id": 18096353, "author_profile": "https://Stackoverflow.com/users/18096353", "pm_score": 2, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = function (arr) {\n let output = {};\n arr.map((item) => {\n output[item.product] = item.price;\n });\n return output;\n};\nconsole.log(productsByPrice(products))\n" }, { "answer_id": 74670642, "author": "Your Friend", "author_id": 16021957, "author_profile": "https://Stackoverflow.com/users/16021957", "pm_score": -1, "selected": false, "text": "const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n ];\n\nconst productsByPrice = products.map(function (arr) {\n return `${arr.product}:${arr.price}`\n})\n\nconsole.log(productsByPrice);" }, { "answer_id": 74670928, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 0, "selected": false, "text": "Object.fromEntries() [key, value] const products = [\n { product: \"banana\", price: 3 },\n { product: \"mango\", price: 6 },\n { product: \"potato\", price: \" \" },\n { product: \"avocado\", price: 8 },\n { product: \"coffee\", price: 10 },\n { product: \"tea\", price: \"\" },\n];\n\nconst productsByPrice = arr => {\n return Object.fromEntries(\n arr.map(({product, price}) => [product, price])\n );\n};\nconsole.log(productsByPrice(products))" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9298556/" ]
74,670,360
<p>Is there any way how I can show a little description above specific icon in Jetpack Compose like in this picture?</p> <p><a href="https://i.stack.imgur.com/WiZ6y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WiZ6y.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74670437, "author": "KarlMathuthu", "author_id": 20281089, "author_profile": "https://Stackoverflow.com/users/20281089", "pm_score": -1, "selected": false, "text": " /** Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon: ***/\n \n Row { \n Text(text = \"Text Above Icon\") \n Column { \n Icon(... ) \n } \n }\n" }, { "answer_id": 74671546, "author": "A. Hajian", "author_id": 9229654, "author_profile": "https://Stackoverflow.com/users/9229654", "pm_score": 0, "selected": false, "text": "Box{ \n Text(text = \"Text Above Icon\", modifier = text alignment)\n Icon(... , modifier = icon alignment) \n \n}\n" }, { "answer_id": 74674984, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 2, "selected": true, "text": "Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n val triangleShape = remember {\n GenericShape { size: Size, layoutDirection: LayoutDirection ->\n val width = size.width\n val height = size.height\n\n lineTo(width / 2, height)\n lineTo(width, 0f)\n lineTo(0f, 0f)\n }\n }\n\n Box {\n\n if (showToolTip) {\n Column(modifier = Modifier.offset(y = (-48).dp)) {\n\n\n Box(\n modifier = Modifier\n .clip(RoundedCornerShape(10.dp))\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(8.dp),\n ) {\n Text(\"Hello World\", color = Color.White)\n }\n\n\n Box(\n modifier = Modifier\n .offset(x = 15.dp)\n .clip(triangleShape)\n .width(20.dp)\n .height(16.dp)\n .background(Color(0xff26A69A))\n )\n }\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n GenericShape fun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n val rectBottom = size.height - arrowHeightPx\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset.Zero,\n size = Size(size.width, rectBottom)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n moveTo(arrowOffsetPx, rectBottom)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)\n lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)\n\n }\n}\n @Composable\nprivate fun Bubble(\n modifier: Modifier = Modifier,\n text: String\n) {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Box(\n modifier = modifier\n .clip(bubbleShape)\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(bottom = arrowHeight),\n contentAlignment = Alignment.Center\n ) {\n Box(modifier = Modifier.padding(8.dp)) {\n Text(\n text = text,\n color = Color.White,\n fontSize = 20.sp\n )\n }\n }\n}\n Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n Box {\n\n if (showToolTip) {\n Bubble(\n modifier = Modifier.offset(x = (-15).dp, (-52).dp),\n text = \"Hello World\"\n )\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14958003/" ]
74,670,361
<p>String contains words separated by spaces.</p> <p>How to get substring from start until first uppercase word (uppercase word excluded)? For example</p> <pre><code>select substringtiluppercase('aaa b cc Dfff dfgdf') </code></pre> <p>should return</p> <pre><code>aaa b cc </code></pre> <p>Can regexp substring used or other idea?</p> <p>Using PostgreSQL 13.2</p> <p>Uppercase letters are latin letters A .. Z and additionally Õ, Ä, Ö , Ü, Š, Ž</p>
[ { "answer_id": 74670437, "author": "KarlMathuthu", "author_id": 20281089, "author_profile": "https://Stackoverflow.com/users/20281089", "pm_score": -1, "selected": false, "text": " /** Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon: ***/\n \n Row { \n Text(text = \"Text Above Icon\") \n Column { \n Icon(... ) \n } \n }\n" }, { "answer_id": 74671546, "author": "A. Hajian", "author_id": 9229654, "author_profile": "https://Stackoverflow.com/users/9229654", "pm_score": 0, "selected": false, "text": "Box{ \n Text(text = \"Text Above Icon\", modifier = text alignment)\n Icon(... , modifier = icon alignment) \n \n}\n" }, { "answer_id": 74674984, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 2, "selected": true, "text": "Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n val triangleShape = remember {\n GenericShape { size: Size, layoutDirection: LayoutDirection ->\n val width = size.width\n val height = size.height\n\n lineTo(width / 2, height)\n lineTo(width, 0f)\n lineTo(0f, 0f)\n }\n }\n\n Box {\n\n if (showToolTip) {\n Column(modifier = Modifier.offset(y = (-48).dp)) {\n\n\n Box(\n modifier = Modifier\n .clip(RoundedCornerShape(10.dp))\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(8.dp),\n ) {\n Text(\"Hello World\", color = Color.White)\n }\n\n\n Box(\n modifier = Modifier\n .offset(x = 15.dp)\n .clip(triangleShape)\n .width(20.dp)\n .height(16.dp)\n .background(Color(0xff26A69A))\n )\n }\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n GenericShape fun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n val rectBottom = size.height - arrowHeightPx\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset.Zero,\n size = Size(size.width, rectBottom)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n moveTo(arrowOffsetPx, rectBottom)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)\n lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)\n\n }\n}\n @Composable\nprivate fun Bubble(\n modifier: Modifier = Modifier,\n text: String\n) {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Box(\n modifier = modifier\n .clip(bubbleShape)\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(bottom = arrowHeight),\n contentAlignment = Alignment.Center\n ) {\n Box(modifier = Modifier.padding(8.dp)) {\n Text(\n text = text,\n color = Color.White,\n fontSize = 20.sp\n )\n }\n }\n}\n Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n Box {\n\n if (showToolTip) {\n Bubble(\n modifier = Modifier.offset(x = (-15).dp, (-52).dp),\n text = \"Hello World\"\n )\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742402/" ]
74,670,369
<p>I have a feeling this question already exists, just can't find it. Is there a way to take a 2d array with x rows and 2 columns and merge multiple values into one row based on it having the same element in the first column?</p> <pre><code>[['Needs Work', 'Joe'], ['Needs Work', 'Jill'], ['Needs Work', 'Jack'], ['Complete', 'Sean'], ['Complete', 'Joe'], ['Not Started', 'Laura'], ['Needs Work', 'Jack']] </code></pre> <p>So that it looks like this</p> <pre><code>[ [ 'Needs Work', 'Joe,Jill,Jack,Jack' ], [ 'Complete', 'Sean,Joe' ], [ 'Not Started', 'Laura' ] ] </code></pre>
[ { "answer_id": 74670437, "author": "KarlMathuthu", "author_id": 20281089, "author_profile": "https://Stackoverflow.com/users/20281089", "pm_score": -1, "selected": false, "text": " /** Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon: ***/\n \n Row { \n Text(text = \"Text Above Icon\") \n Column { \n Icon(... ) \n } \n }\n" }, { "answer_id": 74671546, "author": "A. Hajian", "author_id": 9229654, "author_profile": "https://Stackoverflow.com/users/9229654", "pm_score": 0, "selected": false, "text": "Box{ \n Text(text = \"Text Above Icon\", modifier = text alignment)\n Icon(... , modifier = icon alignment) \n \n}\n" }, { "answer_id": 74674984, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 2, "selected": true, "text": "Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n val triangleShape = remember {\n GenericShape { size: Size, layoutDirection: LayoutDirection ->\n val width = size.width\n val height = size.height\n\n lineTo(width / 2, height)\n lineTo(width, 0f)\n lineTo(0f, 0f)\n }\n }\n\n Box {\n\n if (showToolTip) {\n Column(modifier = Modifier.offset(y = (-48).dp)) {\n\n\n Box(\n modifier = Modifier\n .clip(RoundedCornerShape(10.dp))\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(8.dp),\n ) {\n Text(\"Hello World\", color = Color.White)\n }\n\n\n Box(\n modifier = Modifier\n .offset(x = 15.dp)\n .clip(triangleShape)\n .width(20.dp)\n .height(16.dp)\n .background(Color(0xff26A69A))\n )\n }\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n GenericShape fun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n val rectBottom = size.height - arrowHeightPx\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset.Zero,\n size = Size(size.width, rectBottom)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n moveTo(arrowOffsetPx, rectBottom)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)\n lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)\n\n }\n}\n @Composable\nprivate fun Bubble(\n modifier: Modifier = Modifier,\n text: String\n) {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Box(\n modifier = modifier\n .clip(bubbleShape)\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(bottom = arrowHeight),\n contentAlignment = Alignment.Center\n ) {\n Box(modifier = Modifier.padding(8.dp)) {\n Text(\n text = text,\n color = Color.White,\n fontSize = 20.sp\n )\n }\n }\n}\n Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n Box {\n\n if (showToolTip) {\n Bubble(\n modifier = Modifier.offset(x = (-15).dp, (-52).dp),\n text = \"Hello World\"\n )\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16837689/" ]
74,670,374
<p>i'm working on react native expo project, i'm trying to build custom ProgressBar, I have state call step if the step increase by 1 then the width value of the view has to increase, if the step decreases then the width value of the view has to decrease, so if the value increase or decrease it seems the view has some animation on it</p> <pre><code>const ProgressBar =({step , requset}) =&gt;{ const [ steps , setSteps ]= useState(0); const [accessToken, setAccessToken] = useState(null); const [ width , setWidth ] = useState(50); useEffect( ()=&gt; { const getToken = async ()=&gt;{ const accessToken = await token.get(); setAccessToken(accessToken)} getToken(); accessToken ? requset == 1 ? setSteps(6) : setSteps(7) : setSteps(3) }) useEffect (()=&gt;{ const newWidth = (step*50); setWidth(newWidth); }) return( &lt;View style={{flexDirection:'row',}} &gt; &lt;View style={styles.progressBar}&gt; &lt;Animated.View onLayout = {e =&gt;{ const newWidth = e.nativeEvent.layout.width; setWidth(newWidth); }} style ={ [styles.progress,{width: width}]} /&gt; &lt;/View&gt; &lt;Text style={styles.progressText}&gt;{steps}/{step}&lt;/Text&gt; &lt;/View&gt; )} </code></pre> <p>How can I make a mathematical statement that calculates the amount of width increases depend on Total steps?</p>
[ { "answer_id": 74670437, "author": "KarlMathuthu", "author_id": 20281089, "author_profile": "https://Stackoverflow.com/users/20281089", "pm_score": -1, "selected": false, "text": " /** Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon: ***/\n \n Row { \n Text(text = \"Text Above Icon\") \n Column { \n Icon(... ) \n } \n }\n" }, { "answer_id": 74671546, "author": "A. Hajian", "author_id": 9229654, "author_profile": "https://Stackoverflow.com/users/9229654", "pm_score": 0, "selected": false, "text": "Box{ \n Text(text = \"Text Above Icon\", modifier = text alignment)\n Icon(... , modifier = icon alignment) \n \n}\n" }, { "answer_id": 74674984, "author": "Thracian", "author_id": 5457853, "author_profile": "https://Stackoverflow.com/users/5457853", "pm_score": 2, "selected": true, "text": "Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n val triangleShape = remember {\n GenericShape { size: Size, layoutDirection: LayoutDirection ->\n val width = size.width\n val height = size.height\n\n lineTo(width / 2, height)\n lineTo(width, 0f)\n lineTo(0f, 0f)\n }\n }\n\n Box {\n\n if (showToolTip) {\n Column(modifier = Modifier.offset(y = (-48).dp)) {\n\n\n Box(\n modifier = Modifier\n .clip(RoundedCornerShape(10.dp))\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(8.dp),\n ) {\n Text(\"Hello World\", color = Color.White)\n }\n\n\n Box(\n modifier = Modifier\n .offset(x = 15.dp)\n .clip(triangleShape)\n .width(20.dp)\n .height(16.dp)\n .background(Color(0xff26A69A))\n )\n }\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n GenericShape fun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n val rectBottom = size.height - arrowHeightPx\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset.Zero,\n size = Size(size.width, rectBottom)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n moveTo(arrowOffsetPx, rectBottom)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)\n lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)\n\n }\n}\n @Composable\nprivate fun Bubble(\n modifier: Modifier = Modifier,\n text: String\n) {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Box(\n modifier = modifier\n .clip(bubbleShape)\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(bottom = arrowHeight),\n contentAlignment = Alignment.Center\n ) {\n Box(modifier = Modifier.padding(8.dp)) {\n Text(\n text = text,\n color = Color.White,\n fontSize = 20.sp\n )\n }\n }\n}\n Column(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n Box {\n\n if (showToolTip) {\n Bubble(\n modifier = Modifier.offset(x = (-15).dp, (-52).dp),\n text = \"Hello World\"\n )\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20098345/" ]
74,670,396
<p>I'm a beginner with React and I have been coding a project for one of the courses in uni. However, I have been now struggling for quite some time with following error: Uncaught RangeError: Maximum call stack size exceeded. I have tried to find a solution with no luck.</p> <p>Here is my code for the React component that causes the error:</p> <p>`</p> <pre class="lang-js prettyprint-override"><code>import { Container } from &quot;react-bootstrap&quot; import { useParams } from &quot;react-router&quot; import apiService from &quot;../services/apiService&quot; import { useEffect, useState } from &quot;react&quot; import Spinner from 'react-bootstrap/Spinner'; const GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY export const TreeProfile = (props) =&gt; { const [tree, setTree] = useState({}) const [fetching, setFetching] = useState(true) const [zoom, setZoom] = useState(&quot;12&quot;) const [location, setLocation] = useState({latitude: &quot;&quot;, longitude: &quot;&quot;}) let { id } = useParams() const handleZoomChange2 = (event) =&gt; { console.log(event.target.value) setZoom(event.target.value) } console.log(&quot;Called TreeProfile&quot;) useEffect(() =&gt; { console.log(&quot;id&quot;, id) apiService.getOne(id).then(t =&gt; { console.log(&quot;data&quot;, t) setTree(t) setLocation({latitude: t.location.latitude, longitude: t.location.longitude}) setFetching(false) }) }, []) return ( &lt;Container className=&quot;treeprofile-page&quot;&gt; { fetching === false ? &lt;img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' /&gt; : &lt;Spinner animation=&quot;border&quot; variant=&quot;primary&quot; /&gt; } &lt;h1&gt;{tree.name}&lt;/h1&gt; { fetching === false ? &lt;h3&gt;Planted on {new Date(tree.createdAt).toDateString()}&lt;/h3&gt; : null } &lt;h3&gt;Planted by {tree.user}&lt;/h3&gt; { fetching === false ? &lt;div&gt; &lt;img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&amp;format=gif&amp;zoom=${zoom}&amp;size=300x200&amp;markers=color:red%7C${location.latitude},${location.longitude}&amp;key=${GOOGLE_API_KEY}`} alt='' /&gt; &lt;/div&gt; : null } &lt;div&gt; &lt;input className=&quot;m-3&quot; type=&quot;range&quot; min=&quot;1&quot; max=&quot;16&quot; value={zoom} onChange={handleZoomChange2} /&gt; &lt;/div&gt; &lt;button type=&quot;button&quot; className=&quot;btn btn-primary&quot; &gt;Add update&lt;/button&gt; &lt;/Container&gt; ) } </code></pre> <p>`</p> <p>The error happens every time I try to update the zoom level by sliding the slider, which calls handleZoomChange2 function that sets the state. I have other component in different route with the same functionality and it works fine. However, this one for some reason causes the error constantly.</p> <p>The apiService fetches the data with axios from the backend, which in turn fetches the data from MongoDB.</p> <p>I tried to update zoom level by sliding the slider input, which calls on handleZoomChange2 setting a new state to the zoom. However, the code throws an error Maximum call stack size exceeded. Please, help!</p> <p>Error:</p> <pre><code>TreeProfile.js:38 Uncaught RangeError: Maximum call stack size exceeded at TreeProfile (TreeProfile.js:38:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at beginWork$1 (react-dom.development.js:27426:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1) at renderRootSync (react-dom.development.js:26434:1) at recoverFromConcurrentError (react-dom.development.js:25850:1) at performSyncWorkOnRoot (react-dom.development.js:26096:1) </code></pre>
[ { "answer_id": 74670440, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": -1, "selected": false, "text": "const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n}\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n}, [tree])\n" }, { "answer_id": 74671321, "author": "Daniel Nikkari", "author_id": 15070431, "author_profile": "https://Stackoverflow.com/users/15070431", "pm_score": 0, "selected": false, "text": "tree.image.data.data <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' />\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n tree.image.data.data import { Container } from \"react-bootstrap\"\nimport { useParams } from \"react-router\"\nimport apiService from \"../services/apiService\"\nimport { useEffect, useState } from \"react\"\nimport Spinner from 'react-bootstrap/Spinner';\n\nconst GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY\n\nexport const TreeProfile = (props) => {\n const [tree, setTree] = useState(null)\n const [fetching, setFetching] = useState(true)\n const [zoom, setZoom] = useState(\"12\")\n const [location, setLocation] = useState({latitude: \"\", longitude: \"\"})\n\n let { id } = useParams()\n\n console.log(\"Called TreeProfile\")\n console.log(\"fetching\", fetching)\n\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n }, [])\n \n const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n }\n const test = (event) => {\n console.log(event.target.value)\n setFetching(!fetching)\n }\n\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n\n\n if (tree) {\n return (\n <Container className=\"treeprofile-page\">\n <div>\n <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${_arrayBufferToBase64(tree.image.data.data)}`} alt='' />\n <h1>{tree.name}</h1>\n <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3>\n <h3>Planted by {tree.user}</h3>\n </div>\n <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' />\n <div>\n <input className=\"m-3\" type=\"range\" min=\"1\" max=\"16\" value={zoom} onChange={handleZoomChange2} />\n </div>\n \n <button type=\"button\" className=\"btn btn-primary\" onClick={test} >Add update</button>\n \n </Container>\n )\n } else {\n return (\n <Container>\n <Spinner animation=\"border\" variant=\"primary\" />\n </Container>\n )\n }\n \n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15070431/" ]
74,670,400
<p>I have recyclerView and after click of card I would like to replace fragments in activity. The problem is I have no access to activity. Here is my code in adapter:</p> <pre><code>override fun onBindViewHolder(holder: ViewHolder, position: Int) { val itemsViewModel = mList[position] holder.tagImage.setImageResource(itemsViewModel.tagImage) holder.tagName.text = itemsViewModel.tagName holder.tagDescription.text = itemsViewModel.tagDescription holder.itemView.setOnClickListener { Log.d(InTorry.TAG, itemsViewModel.tagName) val fragment = ProductsFragment() val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.replace(R.id.homeFragmentsContainer, fragment) //transaction?.disallowAddToBackStack() transaction?.commit() } } </code></pre> <p>The above replace code works in fragment but in adapter there is &quot;activity?&quot; error.</p> <p>Kind Regards</p> <p>Jack</p>
[ { "answer_id": 74670440, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": -1, "selected": false, "text": "const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n}\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n}, [tree])\n" }, { "answer_id": 74671321, "author": "Daniel Nikkari", "author_id": 15070431, "author_profile": "https://Stackoverflow.com/users/15070431", "pm_score": 0, "selected": false, "text": "tree.image.data.data <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' />\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n tree.image.data.data import { Container } from \"react-bootstrap\"\nimport { useParams } from \"react-router\"\nimport apiService from \"../services/apiService\"\nimport { useEffect, useState } from \"react\"\nimport Spinner from 'react-bootstrap/Spinner';\n\nconst GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY\n\nexport const TreeProfile = (props) => {\n const [tree, setTree] = useState(null)\n const [fetching, setFetching] = useState(true)\n const [zoom, setZoom] = useState(\"12\")\n const [location, setLocation] = useState({latitude: \"\", longitude: \"\"})\n\n let { id } = useParams()\n\n console.log(\"Called TreeProfile\")\n console.log(\"fetching\", fetching)\n\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n }, [])\n \n const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n }\n const test = (event) => {\n console.log(event.target.value)\n setFetching(!fetching)\n }\n\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n\n\n if (tree) {\n return (\n <Container className=\"treeprofile-page\">\n <div>\n <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${_arrayBufferToBase64(tree.image.data.data)}`} alt='' />\n <h1>{tree.name}</h1>\n <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3>\n <h3>Planted by {tree.user}</h3>\n </div>\n <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' />\n <div>\n <input className=\"m-3\" type=\"range\" min=\"1\" max=\"16\" value={zoom} onChange={handleZoomChange2} />\n </div>\n \n <button type=\"button\" className=\"btn btn-primary\" onClick={test} >Add update</button>\n \n </Container>\n )\n } else {\n return (\n <Container>\n <Spinner animation=\"border\" variant=\"primary\" />\n </Container>\n )\n }\n \n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086818/" ]
74,670,422
<p>I have a spreadsheet in Excel that kinda looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">SubjectID</th> <th style="text-align: left;">ValidQuestions</th> <th style="text-align: left;">Name</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">XXX000</td> <td style="text-align: left;">10</td> <td style="text-align: left;">Python</td> </tr> <tr> <td style="text-align: left;">CCC111 / TTT222</td> <td style="text-align: left;">9</td> <td style="text-align: left;">Data Structure</td> </tr> </tbody> </table> </div> <p>. . The first column represents the ID code that identifies a certain subject. The second one is the number of valid questions that can be used in a exam. The third one is the name of the subject.</p> <p>I have another tab that kind looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SubjectID</th> <th>ValidQuestions</th> </tr> </thead> <tbody> <tr> <td>XXX000</td> <td></td> </tr> <tr> <td>CCC111</td> <td></td> </tr> </tbody> </table> </div> <p>But this time, the SubjectId column contains only one value that is not separated by a slash and the ValidQuestions column is empty. I need to fill the second one with values from the first tab. I tried to use VLOOKUP but it's not working. I would appreciate help.</p>
[ { "answer_id": 74670440, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": -1, "selected": false, "text": "const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n}\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n}, [tree])\n" }, { "answer_id": 74671321, "author": "Daniel Nikkari", "author_id": 15070431, "author_profile": "https://Stackoverflow.com/users/15070431", "pm_score": 0, "selected": false, "text": "tree.image.data.data <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' />\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n tree.image.data.data import { Container } from \"react-bootstrap\"\nimport { useParams } from \"react-router\"\nimport apiService from \"../services/apiService\"\nimport { useEffect, useState } from \"react\"\nimport Spinner from 'react-bootstrap/Spinner';\n\nconst GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY\n\nexport const TreeProfile = (props) => {\n const [tree, setTree] = useState(null)\n const [fetching, setFetching] = useState(true)\n const [zoom, setZoom] = useState(\"12\")\n const [location, setLocation] = useState({latitude: \"\", longitude: \"\"})\n\n let { id } = useParams()\n\n console.log(\"Called TreeProfile\")\n console.log(\"fetching\", fetching)\n\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n }, [])\n \n const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n }\n const test = (event) => {\n console.log(event.target.value)\n setFetching(!fetching)\n }\n\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n\n\n if (tree) {\n return (\n <Container className=\"treeprofile-page\">\n <div>\n <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${_arrayBufferToBase64(tree.image.data.data)}`} alt='' />\n <h1>{tree.name}</h1>\n <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3>\n <h3>Planted by {tree.user}</h3>\n </div>\n <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' />\n <div>\n <input className=\"m-3\" type=\"range\" min=\"1\" max=\"16\" value={zoom} onChange={handleZoomChange2} />\n </div>\n \n <button type=\"button\" className=\"btn btn-primary\" onClick={test} >Add update</button>\n \n </Container>\n )\n } else {\n return (\n <Container>\n <Spinner animation=\"border\" variant=\"primary\" />\n </Container>\n )\n }\n \n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19810317/" ]
74,670,428
<p>I have to create a JS program that changes the title of a page either every 30 seconds or when the user leaves the page. It depends on the word passed in parameter. I call &quot;linear&quot; the function that allows to change the title every 30 seconds and leaving the one that allows it when the user leaves the page.</p> <p>The leaving function works well but the linear function executes only the first cell of the message array to display. I tried several alternatives but nothing works, could someone explain my error? Here is the code</p> <pre><code>var titles = [&quot;MyTitle&quot;,&quot;AlsoMyTitle&quot;,&quot;MyThirdTitle&quot;,&quot;TheFourth&quot;]; var timeLaps = 1000; // time in miliseconds var i = 0; var ogTitle = document.title; function mainTitle() { document.title = ogTitle; } function newTitle() { document.title = 'Come Back!'; } function leaving() { window.onblur = newTitle; window.onfocus = mainTitle; } function linear(){ if (i == 4) { i = 0; } document.title = titleArray[i]; i++; } function main(animType) { if(animType === &quot;leaving&quot;) { leaving(); } else if (animType === &quot;linear&quot;) { setInterval(() =&gt; { changeTitle('linear') }, timeLaps); } } main('linear'); </code></pre> <p>Have a good day!</p>
[ { "answer_id": 74670465, "author": "Dalibor", "author_id": 1738094, "author_profile": "https://Stackoverflow.com/users/1738094", "pm_score": 0, "selected": false, "text": "setInterval(() => {\n changeTitle('linear')\n}, timeLaps);\n" }, { "answer_id": 74670529, "author": "ncxop", "author_id": 18096353, "author_profile": "https://Stackoverflow.com/users/18096353", "pm_score": 1, "selected": false, "text": "var titles = [\"MyTitle\",\"AlsoMyTitle\",\"MyThirdTitle\",\"TheFourth\"];\n document.title = titleArray[i];\n var titleArray = [\"MyTitle\",\"AlsoMyTitle\",\"MyThirdTitle\",\"TheFourth\"];\n" }, { "answer_id": 74671560, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 1, "selected": false, "text": "let initInterval = null; // Define interval method\n/* Set a flag to prevent constant \"focus\" event triggering\n (see lines marked with: ❉) \n*/\nlet on = false;\nlet delay = 3000; // 3 seconds for setTimeout method\n/* Change to 30000 for 30 second intervals as per OP. 3 seconds\nis just for the sake of brevity \n*/\nlet interval = 3000;\nlet count = 0; // Define count with initial value \n// Define array of titles\nconst titles = [\"TITLE I\", \"TITLE II\", \"TITLE III\", \"TITLE IV\"];\n\n/*\n|| Uncomment line A and comment line B as per OP\n*/\n// const changeTitle = str => document.title = str; // A\nconst changeTitle = str => document.querySelector(\"h1\").textContent = str; // B\n\n/*\n|| Event handler passes (e)vent object by default\n|| Redefine initInterval() method\n==========================================================\n|| wrap source of setInterval() in an anonymous function so that changeTitle() \n|| can pass the parameter >titles[count++]< \n|| Note: >count< is incremented on line C.\n==========================================================\n|| If >count< exceeds the last index of >titles< array, reset >count<\n|| Invoke changeTitle(), passing the string at the current index\n|| of >titles< array\n|| Repeat above every >interval< ms\n*/\nconst go = e => {\n initInterval = setInterval(() => {\n if (count > titles.length - 1) {\n count = 0;\n }\n changeTitle(titles[count++]); // C\n }, interval);\n}\n\n/*\n|| Anonymous event handler triggers when window loads\n|❉ Set >on< to true which indicates the user is still on the page.\n|| Change title to it's welcome message\n|| Start go(e) in >delay< ms\n*/\nwindow.onload = e => {\n on = true; // ❉\n changeTitle(\"Loaded\");\n setTimeout(go, delay);\n}\n\n/*\n|| Anonymous event handler triggers when user focuses on window.\n|❉ If the >on< flag is false...\n|| change the title to the focused message\n|| start go(e) in >delay< ms\n|❉ set >on< to true. This ensures that the only \"focus\" event that\n|| the event handler gets triggered by is when the user focuses after \n|| a \"blur\" event\n*/\nwindow.onfocus = e => {\n if (!on) { // ❉\n changeTitle(\"Focused\");\n setTimeout(go, delay);\n on = true; // ❉\n }\n}\n/*\n|| Anonymous event handler triggers when the user leaves the window.\n|❉ Set the >on< flag to false indicating that the user has left the page\n|| Change to title to a leaving message\n|| Remove the interval method\n*/\nwindow.onblur = e => {\n on = false; // ❉\n changeTitle(\"Unfocused\");\n clearInterval(initInterval);\n} <h1></h1>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11660143/" ]
74,670,430
<p>Say I've got sample data:</p> <pre class="lang-py prettyprint-override"><code>sdata = [(1,(10,20,30)), (2,(100,20)), (3,(100,200,300))] columns = [('Sn','Products')] df1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns) </code></pre> <p>Getting error:</p> <blockquote> <p>AttributeError: 'tuple' object has no attribute 'encode'</p> </blockquote> <p>How to load this variable length data ?</p>
[ { "answer_id": 74672313, "author": "Simeon Lico", "author_id": 13177180, "author_profile": "https://Stackoverflow.com/users/13177180", "pm_score": 0, "selected": false, "text": "# Import the ArrayType() function\nfrom pyspark.sql.types import ArrayType\n\n# Define the sample data\nsdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\n# Use the ArrayType() function to define the schema of the DataFrame\ncolumns = [('Sn', IntegerType()),\n ('Products', ArrayType(IntegerType()))]\n\n# Create the DataFrame with the defined schema\ndf1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns)\n\n# Print the schema of the DataFrame\ndf1.printSchema()\n" }, { "answer_id": 74673138, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 2, "selected": true, "text": "sdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\nschema = StructType([\n StructField('Sn', LongType()),\n StructField('Products', ArrayType(LongType())),\n])\n\ndf1 = spark.createDataFrame(sdata, schema=schema)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n sdata = [(1,[10,20,30]),\n (2,[100,20]),\n (3,[100,200,300])]\n\ncolumns = ['Sn','Products']\n\ndf1 = spark.createDataFrame(sdata, schema=columns)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6603160/" ]
74,670,441
<p>After creating my portfolio app with React I have integrated the required lines of code to use GitHub pages.</p> <p>The app throws no error but no components appeared except the background color.</p> <p>The code of <code>App.js</code>:</p> <pre><code>import './App.scss'; import { Route, Routes } from 'react-router-dom' import Layout from './components/Layout'; import Home from './components/Home' import About from './components/About' import Contact from './components/Contact'; function App() { return ( &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Layout /&gt;}&gt; &lt;Route index element={&lt;Home /&gt;}/&gt; &lt;Route path=&quot;about&quot; element={&lt;About /&gt;}/&gt; &lt;Route path=&quot;contact&quot; element={&lt;Contact /&gt;}/&gt; &lt;/Route&gt; &lt;/Routes&gt; ); } export default App; </code></pre> <p>The website is deployed at <a href="https://gregwdumont.github.io/Portfolio/" rel="nofollow noreferrer">https://gregwdumont.github.io/Portfolio/</a>.</p>
[ { "answer_id": 74672313, "author": "Simeon Lico", "author_id": 13177180, "author_profile": "https://Stackoverflow.com/users/13177180", "pm_score": 0, "selected": false, "text": "# Import the ArrayType() function\nfrom pyspark.sql.types import ArrayType\n\n# Define the sample data\nsdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\n# Use the ArrayType() function to define the schema of the DataFrame\ncolumns = [('Sn', IntegerType()),\n ('Products', ArrayType(IntegerType()))]\n\n# Create the DataFrame with the defined schema\ndf1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns)\n\n# Print the schema of the DataFrame\ndf1.printSchema()\n" }, { "answer_id": 74673138, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 2, "selected": true, "text": "sdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\nschema = StructType([\n StructField('Sn', LongType()),\n StructField('Products', ArrayType(LongType())),\n])\n\ndf1 = spark.createDataFrame(sdata, schema=schema)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n sdata = [(1,[10,20,30]),\n (2,[100,20]),\n (3,[100,200,300])]\n\ncolumns = ['Sn','Products']\n\ndf1 = spark.createDataFrame(sdata, schema=columns)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19248260/" ]
74,670,466
<p>I am trying to create an xlsx file in the browser and find <a href="https://github.com/exceljs/exceljs" rel="nofollow noreferrer">https://github.com/exceljs/exceljs</a> very powerful. However, I can't find a way how to save my xlsx object to a file. Probably I need to use Buffer, but how to generate a file from it?</p> <pre><code>const buffer = await workbook.xlsx.writeBuffer(); </code></pre> <p>This library can generate files in the browser <a href="https://docs.sheetjs.com/docs/" rel="nofollow noreferrer">https://docs.sheetjs.com/docs/</a> but it is not good at building complex fields.</p>
[ { "answer_id": 74670563, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 3, "selected": true, "text": "saveAs const workbook = new Excel.Workbook();\n\n// Add data to the workbook\n\nconst buffer = await workbook.xlsx.writeBuffer();\n\nconst fileSaver = require('file-saver');\n\nfileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');\n" }, { "answer_id": 74670701, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 0, "selected": false, "text": "Buffer exceljs saveAs FileSaver.js const buffer = await workbook.xlsx.writeBuffer();\n\n// Import the FileSaver.js library\nimport * as FileSaver from 'file-saver';\n\n// Use the FileSaver.js saveAs() method to save the file\nFileSaver.saveAs(new Blob([buffer]), 'my-file.xlsx');\n saveAs" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2791142/" ]
74,670,496
<p>I am following a tutorial which introduced the global JSON object to stringify objects, in the tutorial they mention that this JSON object and it's methods is provided by the browser. I've also looked at the MDN page for JSON and they list it as a standard built in object.</p> <p>I'm trying to understand if an object such as this is the same as the Date or Math objects and is built into Javascript or is it something extra that is provided by browsers implementing it?</p>
[ { "answer_id": 74670534, "author": "Vepoai", "author_id": 20677212, "author_profile": "https://Stackoverflow.com/users/20677212", "pm_score": -1, "selected": false, "text": "require('json')" }, { "answer_id": 74670543, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": true, "text": "Date Math" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6293348/" ]
74,670,499
<p>I have following table in Pandas:</p> <pre><code>index | project | category | period | update | amount 0 | 100130 | labour | 202201 | 202203 | 1000 1 | 100130 | labour | 202202 | 202203 | 1000 2 | 100130 | labour | 202203 | 202203 | 1000 3 | 100130 | labour | 202204 | 202203 | 1000 4 | 100130 | labour | 202205 | 202203 | 1000 </code></pre> <p>And my final goal is to get table grouped by project and category with summary of amount column but only from month of update until now. So for example above I will get summary from 202203 until 202205 which is 3000 for project 100130 and category labour.</p> <p>As a first step I tried following condition:</p> <pre><code>for index, row in table.iterrows(): if row[&quot;period&quot;] &lt; row[&quot;update&quot;] row[&quot;amount&quot;] = 0 </code></pre> <p>But:</p> <ol> <li>this iteration is not working</li> <li>is there some simple and not so time consuming way how to do it? As my table has over 60.000 rows, so iteration not so good idea probably.</li> </ol>
[ { "answer_id": 74670534, "author": "Vepoai", "author_id": 20677212, "author_profile": "https://Stackoverflow.com/users/20677212", "pm_score": -1, "selected": false, "text": "require('json')" }, { "answer_id": 74670543, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": true, "text": "Date Math" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226420/" ]
74,670,514
<p>I am trying to create a date identifier using only if statements and a switch statement that can determine whether an inputted date is valid, what season the date is in and finally whether it is a leap year. I tried to get the component parts working independently first and got two of them working then tried them all together but I still can't get my switch statement working. I want my switch statement to show the season by checking both the day and month to see what season we are in but I'm not sure how to do that. Here is my code:</p> <pre><code>/* Switch statement to determine season for day and month */ // Using it with a &quot;m&quot; on it's own works, how do I get it working for specific days? switch (m) { case 12: case 1: case 2: if ((m == 12 &amp;&amp; d &gt;=21) || (m == 1) || (m == 2) || (m == 3 &amp;&amp; m &lt; 21)) printf(&quot;The season is Winter.\n&quot;); break; case 3: case 4: case 5: if ((m == 3 &amp;&amp; d &gt;= 21) || (m == 4) || (m == 5) || (m == 6 &amp;&amp; d &lt; 21)) printf(&quot;The season is Spring.\n&quot;); break; case 6: case 7: case 8: if ((m == 6 &amp;&amp; d &gt;= 21) || (m == 7) || (m == 8) | (m == 9 &amp;&amp; d &lt; 21)) printf(&quot;The season is Summer.\n&quot;); break; case 9: case 10: case 11: if ((m == 9 &amp;&amp; d &gt;= 21) || (m == 10) || (m == 11) || (m == 12 &amp;&amp; d &lt; 21)) printf(&quot;The season is Autumn.\n&quot;); default: break; } } </code></pre> <p>I tried getting the code working for each part independently, but I'm still unsure about my switch statement. How can I get it working for days as well as months? Is there a way to do it still with a switch statement?</p> <p>Example Output:</p> <pre class="lang-none prettyprint-override"><code>20/06/2022 = Spring 21/06/2022 = Summer </code></pre>
[ { "answer_id": 74670534, "author": "Vepoai", "author_id": 20677212, "author_profile": "https://Stackoverflow.com/users/20677212", "pm_score": -1, "selected": false, "text": "require('json')" }, { "answer_id": 74670543, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": true, "text": "Date Math" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19989314/" ]
74,670,537
<p>I have some custom jQuery that disappears after paginating. I couldn't figure out how to keep it loaded so I figured I would try to reload it after click but thats not working either.</p> <p>here is what i was trying to get it to run:</p> <pre><code>$(document).ready(function() { $('.pagination&gt;li&gt;a').live(&quot;click&quot;, function(){ </code></pre> <p>any ideas how to make this work?</p> <p>what I would really like is to keep the custom jQuery while paginating, since there could potentially be 2 separate paginations on any given page (displaying notes and activities).</p>
[ { "answer_id": 74670534, "author": "Vepoai", "author_id": 20677212, "author_profile": "https://Stackoverflow.com/users/20677212", "pm_score": -1, "selected": false, "text": "require('json')" }, { "answer_id": 74670543, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": true, "text": "Date Math" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5684101/" ]
74,670,572
<p>I'm doing some multiple regEX replacements in powershell on a large number of files and would like to only write the file if any replacements were actually made.</p> <p>For example if I do:</p> <pre><code>($_ | Get-Content-Raw) -Replace 'MAKEUPS', 'Makeup' -Replace '_MAKEUP', 'Makeup' -Replace 'Make up', 'Makeup' -Replace 'Make-up', 'Makeup' -Replace '&quot;SELF:/', '&quot;' | Out-File $_.FullName -encoding ASCII </code></pre> <p>I only want to write the file if it found anything to replace. Is this possible, maybe with a count or boolean operation?</p> <p>I did think maybe to check the length of the string before and after but was hoping for a more elegant solution, so I thought I'd ask the experts!</p>
[ { "answer_id": 74670534, "author": "Vepoai", "author_id": 20677212, "author_profile": "https://Stackoverflow.com/users/20677212", "pm_score": -1, "selected": false, "text": "require('json')" }, { "answer_id": 74670543, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": true, "text": "Date Math" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15388876/" ]
74,670,582
<p>I was trying to find the time complexity of this nested loop</p> <pre><code>for (i = 1; i &lt;= n; i++) { for (j = 1; j &lt;= n; j++) { n--; x++; } } </code></pre> <p>If there wasn't a <code>n--</code> it would be <code>n*n</code> , O(n<sup>2</sup>) right?</p> <p>But what if <code>n</code> reduces every time second loop runs?</p> <p>What's the time complexity and big O of this nested loop?</p> <p>If I consider n = 5, x equals 4, the second loop runs 4 time</p>
[ { "answer_id": 74670697, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 3, "selected": true, "text": "n n/2 + n/4 + n/8 + n/16 + ... + n/2^k = O(n) k i n-- n*n" }, { "answer_id": 74671222, "author": "Kelly Bundy", "author_id": 12671057, "author_profile": "https://Stackoverflow.com/users/12671057", "pm_score": 1, "selected": false, "text": "j <= n j n n n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15162992/" ]
74,670,641
<p>i would like to set a df value between two values x_lim(0,2) to True.</p> <p>I would like to get a df that looks like this:</p> <pre><code>x | y | z 0 | 7 | True 1 | 3 | True 2 | 4 | True 3 | 8 | False </code></pre> <p>i tried :</p> <pre><code>def set_label(df, x_lim, y_lim, variable): for index, row in df.iterrows(): for i in range(x_lim[0],x_lim[1]): df['Label'] = variable.get() print(df) </code></pre> <p>could anyone help me to solve this problem ?</p>
[ { "answer_id": 74670653, "author": "VGP", "author_id": 19324766, "author_profile": "https://Stackoverflow.com/users/19324766", "pm_score": 2, "selected": false, "text": "import pandas as pd\n\n# Create a dataframe with sample data\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)\ndf['z'] = df['x'].between(0, 2, inclusive=True)\n\n# Print the resulting dataframe\nprint(df)\n x y z\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n" }, { "answer_id": 74670658, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 2, "selected": true, "text": "loc def set_label(df, x_lim, y_lim, variable):\n df['Label'] = False # create a new column with default value of False\n df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()\n # set the values in the Label column to True where x is between x_lim[0] and x_lim[1]\n return df\n # create a sample DataFrame\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# set the label column to True where x is between 0 and 2\ndf = set_label(df, (0, 2), None, True)\n\nprint(df)\n x y Label\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16321574/" ]
74,670,644
<p>im trying to write a function that returns the length of the longest run of repetition in a given list</p> <p>Here is my code: `</p> <pre><code>def longest_repetition(a): longest = 0 j = 0 run2 = 0 while j &lt;= len(a)-1: for i in a: run = a.count(a[j] == i) if run == 1: run2 += 1 if run2 &gt; longest: longest = run2 j += 1 run2 = 0 return longest print(longest_repetition([4,1,2,4,7,9,4])) print(longest_repetition([5,3,5,6,9,4,4,4,4])) 3 0 </code></pre> <p>`</p> <p>The first test function works fine, but the second test function is not counting at all and I'm not sure why. Any insight is much appreciated</p> <p>Edit: Just noticed that the question I was given and the expected results are not consistent. So what I'm basically trying to do is find the most repeated element in a list and the output would be the number of times it is repeated. That said, the output for the second test function should be 4 because the element '4' is repeated four times (elements are not required to be in one run as implied in my original question)</p>
[ { "answer_id": 74670653, "author": "VGP", "author_id": 19324766, "author_profile": "https://Stackoverflow.com/users/19324766", "pm_score": 2, "selected": false, "text": "import pandas as pd\n\n# Create a dataframe with sample data\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)\ndf['z'] = df['x'].between(0, 2, inclusive=True)\n\n# Print the resulting dataframe\nprint(df)\n x y z\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n" }, { "answer_id": 74670658, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 2, "selected": true, "text": "loc def set_label(df, x_lim, y_lim, variable):\n df['Label'] = False # create a new column with default value of False\n df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()\n # set the values in the Label column to True where x is between x_lim[0] and x_lim[1]\n return df\n # create a sample DataFrame\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# set the label column to True where x is between 0 and 2\ndf = set_label(df, (0, 2), None, True)\n\nprint(df)\n x y Label\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677227/" ]
74,670,665
<p>This doesn't really work</p> <p>To explain what I did: I set a vowel variable with a list Then I used a for loop to iterate through the list and print the letters not in the list</p> <p><a href="https://i.stack.imgur.com/guoHs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/guoHs.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74670834, "author": "user2678074", "author_id": 2678074, "author_profile": "https://Stackoverflow.com/users/2678074", "pm_score": 0, "selected": false, "text": "if not letter.lower in vowels:\n if not letter.lower() in vowels:\n" }, { "answer_id": 74672977, "author": "Sanjay Rai", "author_id": 13405952, "author_profile": "https://Stackoverflow.com/users/13405952", "pm_score": 0, "selected": false, "text": "if i not in vowel:\n\n#Check Vowel if not then add to output\n\n output+=i\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677245/" ]
74,670,670
<p>Hello I know that I have the code right. I want to destroy the material when my player goes on them. I don't know why I can't destroy them. I have put only to my materials box collider with X= 1 Y=1 Z=1.I don't understand why I can't destroy them. The material I gave it also as a tag. Instead of my player destroy those material he pass through them..I have a <code>RigidBody</code> on the player.</p> <pre><code>void OnCollisionEnter ( Collision collision ) { if ( collision.gameObject.tag == &quot;material&quot; ) { Destroy ( collision.gameObject ); } } </code></pre>
[ { "answer_id": 74670834, "author": "user2678074", "author_id": 2678074, "author_profile": "https://Stackoverflow.com/users/2678074", "pm_score": 0, "selected": false, "text": "if not letter.lower in vowels:\n if not letter.lower() in vowels:\n" }, { "answer_id": 74672977, "author": "Sanjay Rai", "author_id": 13405952, "author_profile": "https://Stackoverflow.com/users/13405952", "pm_score": 0, "selected": false, "text": "if i not in vowel:\n\n#Check Vowel if not then add to output\n\n output+=i\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18125145/" ]
74,670,698
<p>I'm having issues to display all the rows inside my database table. But only one rows display instead of all data.</p> <pre><code>$query= mysqli_query($conn,&quot;select* from food_table&quot;); if (mysqli_num_rows($query)&gt;0){ echo &quot;&lt;p style='color: green;'&gt;See Below the Available Foods&lt;br&gt;&lt;/p&gt;&quot;; while($row=mysqli_fetch_assoc($query)){ $food_name= $row['food_name']; $food_info = $row['food_info']; $food_price = $row['food_price']; $vendor_id = $row['vendor_id']; $default_miles = $row['default_miles']; $food_date= $row['date']; } $foods= array($food_name,$food_info,$food_price,$vendor_id,$default_miles, $food_date ); foreach($foods as $foodss){ echo &quot;$foodss.&lt;br/&gt;&quot;; } </code></pre> <p>please see result below;<a href="https://i.stack.imgur.com/Oc4iQ.png" rel="nofollow noreferrer">enter image description here</a></p>
[ { "answer_id": 74670834, "author": "user2678074", "author_id": 2678074, "author_profile": "https://Stackoverflow.com/users/2678074", "pm_score": 0, "selected": false, "text": "if not letter.lower in vowels:\n if not letter.lower() in vowels:\n" }, { "answer_id": 74672977, "author": "Sanjay Rai", "author_id": 13405952, "author_profile": "https://Stackoverflow.com/users/13405952", "pm_score": 0, "selected": false, "text": "if i not in vowel:\n\n#Check Vowel if not then add to output\n\n output+=i\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19402335/" ]
74,670,704
<p>I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.</p> <pre><code>import os import time print('your computer will be shutdown if you dont play my game or if you lose it') shutdown = input(&quot;What is 12 times 13? you have 30 seconds.&quot;) time.sleep(30) if shutdown == '156': exit() elif shutdown == '': print('you didnt even try') and os.system(&quot;shutdown /s /t 1&quot;) else: os.system(&quot;shutdown /s /t 1&quot;) </code></pre> <p>I tried threading already but that is really complicated and I'm expecting to print you didn't even try and shutdown after the 30 seconds if you didn't input anything</p>
[ { "answer_id": 74670834, "author": "user2678074", "author_id": 2678074, "author_profile": "https://Stackoverflow.com/users/2678074", "pm_score": 0, "selected": false, "text": "if not letter.lower in vowels:\n if not letter.lower() in vowels:\n" }, { "answer_id": 74672977, "author": "Sanjay Rai", "author_id": 13405952, "author_profile": "https://Stackoverflow.com/users/13405952", "pm_score": 0, "selected": false, "text": "if i not in vowel:\n\n#Check Vowel if not then add to output\n\n output+=i\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677008/" ]
74,670,709
<p>Until now, I have used <a href="https://doc.rust-lang.org/std/fs/fn.read_to_string.html" rel="nofollow noreferrer"><code>std::fs::read_to_string</code></a> and then <a href="https://doc.rust-lang.org/std/string/struct.String.html#method.lines" rel="nofollow noreferrer"><code>String.lines</code></a>'s <a href="https://doc.rust-lang.org/std/str/struct.Lines.html" rel="nofollow noreferrer"><code>std::str::Lines</code></a> (which is an <code>Iterator&lt;Item = &amp;str&gt;</code>) to read a file &quot;line by line&quot;. This obviously reads the whole file into memory, which is not ideal.</p> <p>So, there's <a href="https://doc.rust-lang.org/std/io/trait.BufRead.html#method.lines" rel="nofollow noreferrer"><code>BufRead.lines()</code></a> to read a file truly line by line. This returns <a href="https://doc.rust-lang.org/std/io/struct.Lines.html" rel="nofollow noreferrer"><code>std::io::Lines</code></a> (which is an <code>Iterator&lt;Item = Result&lt;String&gt;&gt;</code>).</p> <p>How do I convert from one iterator type to the other without <code>collect</code>ing first?</p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178016/" ]
74,670,717
<p>Is there a way I can call a function in the return section of React? kind of like how in JS I can just call a function by <code>functionName()</code> ?</p> <p><strong>WHAT EXACTLY AM I TRYING TO ACCOMPLISH?</strong> What I am wanting to do in this bakery game is when the player hits $5, the &quot;Purchase Easy Bake Oven&quot; pops up and it will cost them $25 to purchase (At this time I do not necessarily care about the math mathing, I just care for functionality). Once the player decides to purchase, this section disappears and is replaced with &quot;Easy bake Oven&quot; With a button that says $5 where at this point, every time the button is clicked my total increases by 5.</p> <p><strong>WHAT HAVE I TRIED?</strong> I feel like this should be done with an onClick event to switch from <code>const [showEZBake, setShowEZBake] = useState(false)</code> to <code>useState(True)</code>. I currently have a Turnary (or whatever you call it), but I feel like this is incorrect because I need to change the state as stated before. I have also attempted to create an if statement inside of a function where I would add an h1 element, but that did not work. Even if it did, my main issue would still be there and that is how to call a function inside of a return.</p> <p><strong>SUMMARY:</strong> I want the &quot;Purchase Oven&quot; text and $5 button to be replaced with Oven and $2 button AFTER the button was clicked.</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, {useState, useEffect} from 'react' const App = () =&gt; { // ====================================== // HOOKS // ====================================== const [score, setScore] = useState(0) // ====================================== // FUNCTIONS // ====================================== // EARN REVENUE FUNCTIONS const earn1 = () =&gt; { setScore(score + 1) } const earn5 = () =&gt; { setScore(score + 5) } const reveal = () =&gt; { // setShowEZBake(false) if (score &gt;= 5) { return ( &lt;h1&gt;TEST&lt;/h1&gt; ) } else { } } const upgrade = () =&gt; { if (score &gt;= 5) { &lt;&gt;&lt;h3&gt;Purchase Easy Bake Oven&lt;/h3&gt; &lt;button&gt;$5&lt;/button&gt;&lt;/&gt; } else { } } const [showEZBake, setShowEZBake] = useState(false) // ====================================== // DISPLAY // ====================================== return ( &lt;div&gt; &lt;h1&gt;Bakery&lt;/h1&gt; &lt;h2&gt;Revenue {score}&lt;/h2&gt; &lt;h3&gt;No Bake Pudding&lt;/h3&gt;&lt;button onClick={earn1}&gt;$1&lt;/button&gt; { score &gt;= 5 ? &lt;&gt;&lt;h3&gt;Purchase Easy Bake Oven&lt;/h3&gt; &lt;button onClick={reveal}&gt;$5&lt;/button&gt;&lt;/&gt; : null } &lt;h3&gt;&lt;/h3&gt; &lt;/div&gt; ) } export default App</code></pre> </div> </div> </p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408190/" ]
74,670,737
<p>I am trying to learn pattern matching with regex, the course is through coursera and hasn't been updated since python 3 came out so the instructors code is not working correctly.</p> <p>Here's what I have so far:</p> <pre><code># example Wiki data wiki= &quot;&quot;&quot;There are several Buddhist universities in the United States. Some of these have existed for decades and are accredited. Others are relatively new and are either in the process of being accredited or else have no formal accreditation. The list includes: • Dhammakaya Open University – located in Azusa, California, • Dharmakirti College – located in Tucson, Arizona • Dharma Realm Buddhist University – located in Ukiah, California • Ewam Buddhist Institute – located in Arlee, Montana • Naropa University - located in Boulder, Colorado • Institute of Buddhist Studies – located in Berkeley, California • Maitripa College – located in Portland, Oregon • Soka University of America – located in Aliso Viejo, California • University of the West – located in Rosemead, California • Won Institute of Graduate Studies – located in Glenside, Pennsylvania&quot;&quot;&quot; pattern=re.compile( r'(?P&lt;title&gt;.*)' # the university title r'(-\ located\ in\ )' #an indicator of the location r'(?P&lt;city&gt;\w*)' # city the university is in r'(,\ )' #seperator for the state r'(?P&lt;state&gt;\w.*)') #the state the city is in) for item in re.finditer(pattern, wiki, re.VERBOSE): print(item.groupdict()) </code></pre> <p>Output:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/r..., line 194, in &lt;module&gt; for item in re.finditer(pattern, wiki, re.VERBOSE): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/re/__init__.py&quot;, line 223, in finditer return _compile(pattern, flags).finditer(string) ^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/re/__init__.py&quot;, line 282, in _compile raise ValueError( ValueError: cannot process flags argument with a compiled pattern </code></pre> <p>I only want a dictionary with the university name, the city and the state. If I run it without re.VERBOSE, only one school shows up and none of the rest are there. I am somewhat new to python and don't know what to do about these errors</p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20486177/" ]
74,670,791
<p>I have the following timelines :</p> <pre><code> 7 a.m --------------------- 12 a.m. 2 am .................. 10 a.m 10-------11 3------5 closed closed </code></pre> <pre><code>the output should be the non-intersecting time ranges: 7-10 a.m, 11 -12 a.m, 2-3 p.m, 5-10 p.m </code></pre> <p>I tried to minus and subtract method for Ranges but didn't work A tricky part could be the following case</p> <pre><code> 7 a.m --------------------- 12 a.m. 2 am .................. 10 a.m 10----------------------------------------5 closed </code></pre> <pre><code>the output should be the non-intersecting time ranges: 7-10 a.m, 5-10 p.m </code></pre> <p>Any Idea for kotlin implementation?</p> <p>I tried to minus and subtract method for Ranges but didn't work</p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677300/" ]
74,670,818
<p>Assume I have a list of values, for example:</p> <pre><code>limits = [10, 6, 3, 5, 1] </code></pre> <p>For every item in <code>limits</code>, I need to generate a random number less than or equal to the item. However, the catch is that the sum of elements in the new random list must be equal to a specified total.</p> <p>For example if <code>total = 10</code>, then one possible random list is:</p> <pre><code>random_list = [2, 1, 3, 4, 0] </code></pre> <p>where you see <code>random_list</code> has same length as <code>limits</code>, every element in <code>random_list</code> is less than or equal to the corresponding element in <code>limits</code>, and <code>sum(random_list) = total</code>.</p> <p>How to generate such a list? I am open (and prefer) to use numpy, scipy, or pandas.</p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5495304/" ]
74,670,837
<p>New-ish to R and I feel like this has a simple solution, but I can't figure it out.</p> <p>I have 59 excel files that I want to combine. However, 4 of the columns have a mix of dates and <code>NA</code>'s (depending on if the study animal is a migrant or not) so R won't let me combine them because some are numeric and some are character. I was hoping to read all of the excel files into R, convert those 4 columns in each file to <code>as.character</code>, and then merge them all. I figured a loop could do this.</p> <p>Anything I find online has me typing out the name for each read file, which I don't really want to do for 59 files. And once I do have them read into R and those columns converted, can I merge them from R easily? Sorry if this is simple, but I'm not sure what to do that would make this easier.</p>
[ { "answer_id": 74670765, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": -1, "selected": false, "text": "String String.lines Iterator<Item = Result<String> Strings let mut read = BufReader::new(File::open(\"src/main.rs\").unwrap());\nlet lines_iter = read.lines().map(Result::unwrap_or_default);\n Iterator String &str fn solve<T: AsRef<str>>(input: impl Iterator<Item = T>) {\n for line in input {\n let line = line.as_ref();\n // do something with line\n }\n}\n" }, { "answer_id": 74672641, "author": "Chayim Friedman", "author_id": 7884305, "author_profile": "https://Stackoverflow.com/users/7884305", "pm_score": 0, "selected": false, "text": "Iterator<Item = Result<_, _>> Result<Iterator<Item = _>, _> collect() Result<Vec<_>, _> Result FromIterator Err Err itertools::process_results() let result: Result<SomeType, _> = itertools::process_results(iter, |iter| -> SomeType {\n // Here we have `iter` of type `Iterator<Item = _>`. Process it and return some result.\n});\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677313/" ]
74,670,852
<p>I am testing keycloak for learning purposes. I am testing the client credentials flow token endpoint to return a jwt for rest api use.</p> <p>The endpoint returns an <code>access_token</code> and a <code>refresh_token</code> (refresh token is disabled by default unless I enable it in console for the client). I can call the same token endpoint with a refresh token generated from the first client credentials call but it still requires a client secret.</p> <p>Is it not possible to regenerate an access token in the client credentials flow with just a refresh token?</p> <p>If not why would I ever bother to pass a <code>grant_type</code> of <code>refresh_token</code> - wouldn't I just call the client_credential flow again since they both require a client secret? I have to guess the answer will be that refresh tokens don't make sense to be used with client_credential flows?</p> <p>token parameters:</p> <p><a href="https://i.stack.imgur.com/8pKx1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8pKx1.png" alt="enter image description here" /></a></p> <p>refresh token parameters:</p> <p><a href="https://i.stack.imgur.com/dP99P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dP99P.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74673536, "author": "dreamcrash", "author_id": 1366871, "author_profile": "https://Stackoverflow.com/users/1366871", "pm_score": 0, "selected": false, "text": "client_credentials The key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL\n NOT\", \"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and\n \"OPTIONAL\" in this document are to be interpreted as described in\n RFC 2119.\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647105/" ]
74,670,867
<p>I designed the scrollable cards. The cards are only for mobile screens. The current issue is that more data gets encapsulated inside the scrollable wrapper as the content grows. No matter how long the content is, I want the div's height to increase. Is there a fix for this design that makes the card's height rise in proportion to its contents?</p> <p>The <code>read more</code> functionality is implemented, but I didn't add it to the snippet. By default, all the content will be the same. But on <code>read more</code>, the content can vary. So, I want the design to be fixed so <code>read more</code> content does not affect the card.</p> <p>By default:</p> <p><a href="https://i.stack.imgur.com/AN6NJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AN6NJ.png" alt="enter image description here" /></a></p> <p>On clicking read more/content increases:</p> <p><a href="https://i.stack.imgur.com/lEFdz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lEFdz.png" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.scrolling-wrapper { -webkit-overflow-scrolling: touch; height: 474px; width: 100%; padding-inline: 40px; position: relative; display: flex; flex-wrap: nowrap; overflow-x: auto; z-index: 0; padding-top: 150px; visibility: visible; } .scrolling-wrapper::-webkit-scrollbar { display: none; } .card { width: 100%; flex: 0 0 auto; background-color: green; border-radius: 20px; position: relative; margin-inline-end: 10px; } .our-member-owner-card-image { position: absolute; top: -66px; z-index: 10; left: 29%; } .card-content { position: absolute; padding-top: 38px; } .member-detail { padding-top: 55px; line-height: 1.7; } .member-detail h3 { text-align: center; color: #263244; font-weight: 700; font-family: "Lato"; } .member-detail p { text-align: center; color: #737c89; } .member-description { padding-inline: 20px; color: #263244; line-height: 1.6; padding-top: 9px; font-weight: 500; font-size: 16px; font-style: normal; font-weight: 500; } .member-description .read-more { color: #eb644c; text-decoration: underline; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="scrolling-wrapper"&gt; &lt;div class="card"&gt; &lt;div class="our-member-owner-card-image"&gt; &lt;img width="140px" src="https://images.unsplash.com/photo-1579279219378-731a5c4f4d16?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bXIlMjBiZWFufGVufDB8fDB8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60" /&gt; &lt;/div&gt; &lt;div class="card-content"&gt; &lt;div class="member-detail"&gt; &lt;h3 id="mobile-member-name"&gt;Mr bean&lt;/h3&gt; &lt;p id="mobile-member-designation"&gt;Actor&lt;/p&gt; &lt;/div&gt; &lt;div class="member-description"&gt; &lt;span id="mobile-member-description"&gt; Mr Bean has extensive work experience during his career of more than 25 years in the film industry. &lt;/span&gt; &lt;span id="mobile-more" &gt;Some dummy text &lt;/span&gt; &lt;span id="mobile-member-description-readmore" class="readMoreLink read-more" &gt;Read less&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="card"&gt; &lt;div class="our-member-owner-card-image"&gt; &lt;img width="140px" src="https://images.unsplash.com/photo-1579279219378-731a5c4f4d16?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bXIlMjBiZWFufGVufDB8fDB8fA%3D%3D&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60" /&gt; &lt;/div&gt; &lt;div class="card-image-shadow"&gt;&lt;/div&gt; &lt;div class="card-content"&gt; &lt;div class="member-detail"&gt; &lt;h3 id="mobile-member2-name"&gt;Mr bean&lt;/h3&gt; &lt;p id="mobile-member2-designation"&gt;Actor&lt;/p&gt; &lt;/div&gt; &lt;div class="member-description"&gt; &lt;span id="mobile-member2-description"&gt; Mr Bean has extensive work experience during his career of more than 25 years in the film industry &lt;/span&gt; &lt;span id="mobile-more2" &gt;Some dummy text &lt;/span&gt; &lt;span id="mobile-member2-description-readmore" class="readMoreLink read-more" " &gt;Read less&lt;/span &gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74673536, "author": "dreamcrash", "author_id": 1366871, "author_profile": "https://Stackoverflow.com/users/1366871", "pm_score": 0, "selected": false, "text": "client_credentials The key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL\n NOT\", \"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and\n \"OPTIONAL\" in this document are to be interpreted as described in\n RFC 2119.\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961514/" ]
74,670,886
<p>Im trying to get this code for image browsing then cropping the browsed image working:</p> <p>This is the supposed code to be working:</p> <pre><code>import &quot;./styles.css&quot;; import React, { useState } from &quot;react&quot;; import ReactCrop from 'react-image-crop'; import 'react-image-crop/dist/ReactCrop.css' export default function App() { const [src, selectFile] = useState(null); const onImageChange = (event) =&gt; { selectFile(URL.createObjectURL(event.target.files[0])); }; const [image, setImage] = useState(null); const [crop, setCrop] = useState({ aspect: 16 / 9 }); const [result, setResult] = useState(null); function getCroppedImg(){ const canvas = document.createElement('canvas'); const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; canvas.width = crop.width; canvas.height = crop.height; const ctx = canvas.getContext('2d'); ctx.drawImage ( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width, crop.height, ); const base64Image = canvas.toDataURL('image/jpeg'); setResult(base64Image) } return ( &lt;div className=&quot;container&quot;&gt; &lt;div className='row'&gt; &lt;div className='col-6'&gt; &lt;input type=&quot;file&quot; accept ='image/*' onChange={onImageChange}/&gt; &lt;/div&gt; {src &amp;&amp; &lt;div className='col-6'&gt; &lt;ReactCrop src={src} onImageLoaded={setImage} crop={crop} onChange={setCrop} /&gt; &lt;button className='btn btn-danger' onClick={getCroppedImg} &gt; Crop Image &lt;/button&gt; &lt;/div&gt;} {result &amp;&amp; &lt;div className='col-6'&gt; &lt;img src={result} alt='Cropped Image' className='img-fluid' /&gt; &lt;/div&gt;} &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p>You can use this sandbox link to immediately test and debug the code and see the error, <a href="https://codesandbox.io/s/stoic-hooks-l5gfrz" rel="nofollow noreferrer">code testing in sandbox</a></p> <p>This full code is not mainly mine, I have been following this tutorial on youtube as im trying to get it working to learn and use it on my main project, But i cannot get it working as in there this error, which is not actually in the tutorial as im not even missing any line of code so i cannot understand why this error happening, appreicated to make me understand why it happened. this is the yt link: <a href="https://www.youtube.com/watch?v=KbPRpBdBN6w&amp;t=351s" rel="nofollow noreferrer">yt tutorial code</a></p> <p>Also to add, When i try to browse the image in the current code it doesn't work so I actually tried to fix it by adding this line</p> <pre><code>&lt;img src={src} /&gt; </code></pre> <p>under the it actually started to work for showing the image, but the cropping functionality is not working.</p>
[ { "answer_id": 74673536, "author": "dreamcrash", "author_id": 1366871, "author_profile": "https://Stackoverflow.com/users/1366871", "pm_score": 0, "selected": false, "text": "client_credentials The key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL\n NOT\", \"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and\n \"OPTIONAL\" in this document are to be interpreted as described in\n RFC 2119.\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17319782/" ]
74,670,887
<p>I am building a container, you can see the docker file, its for rust app deployment on Argonaut. but its not able to start. Here you can see the Dockerfile.</p> <pre><code>FROM rust:1.64.0-buster AS builder WORKDIR /app ARG TOKEN ARG DATABASE_URL RUN git config --global url.&quot;https://${TOKEN}:@github.com/&quot;.insteadOf &quot;https://github.com/&quot; COPY . . ENV CARGO_NET_GIT_FETCH_WITH_CLI true RUN rustup component add rustfmt RUN apt-get update -y &amp;&amp; apt-get install git wget ca-certificates curl gnupg lsb-release cmake libcurl4 -y RUN cargo build FROM debian:buster-slim WORKDIR /app COPY --from=builder /app/target/debug/linkedin /app/target/release/linkedin COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ CMD [&quot;/app/target/release/linkedin&quot;] EXPOSE 3000 </code></pre> <p>It builds successfully but when it works it gets exit with error code 127.</p> <pre><code>linkedin-leadr-1 | /app/target/release/linkedin: error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory </code></pre> <p>Have not found what's wrong with it, even though I am installing libcurl4. but my docker container is not able to find it. Can you please give me the solution?</p>
[ { "answer_id": 74670899, "author": "VGP", "author_id": 19324766, "author_profile": "https://Stackoverflow.com/users/19324766", "pm_score": 0, "selected": false, "text": "FROM rust:1.64.0-buster AS builder\nWORKDIR /app\n\nARG TOKEN\nARG DATABASE_URL\n\nRUN git config --global url.\"https://${TOKEN}:@github.com/\".insteadOf \"https://github.com/\"\n\nCOPY . .\n\nENV CARGO_NET_GIT_FETCH_WITH_CLI true\n\nRUN rustup component add rustfmt\nRUN apt-get update -y && apt-get install git wget ca-certificates curl gnupg lsb-release cmake libcurl4 -y\n\nRUN cargo build\n\n# Copy the libcurl shared library from the builder stage into the final container\nRUN mkdir -p /usr/local/lib && \\\n cp /usr/lib/x86_64-linux-gnu/libcurl.so.4 /usr/local/lib && \\\n ln -s /usr/local/lib/libcurl.so.4 /usr/local/lib/libcurl.so\n\nFROM debian:buster-slim\nWORKDIR /app\nCOPY --from=builder /app/target/debug/linkedin /app/target/release/linkedin\nCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\nCMD [\"/app/target/release/linkedin\"]\nEXPOSE 3000\n" }, { "answer_id": 74675291, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "libcurl4 libcurl4 cargo build RUN rustup target add x86_64-unknown-linux-musl\nRUN cargo build --target=x86_64-unknown-linux-musl --release\n --release libcurl4 RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes \\\n libcurl4 \\\n && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\n FROM rust:1.64.0-buster AS builder\nWORKDIR /app\n\nARG TOKEN\nARG DATABASE_URL\n\nRUN git config --global url.\"https://${TOKEN}:@github.com/\".insteadOf \"https://github.com/\"\n\nCOPY . .\n\nENV CARGO_NET_GIT_FETCH_WITH_CLI true\n\nRUN rustup component add rustfmt\nRUN apt-get update -y && apt-get install git wget ca-certificates curl gnupg lsb-release cmake libcurl4 -y\n\nRUN cargo build\n\n# Copy the libcurl shared library from the builder stage into the final container\nRUN mkdir -p /usr/local/lib && \\\n cp /usr/lib/x86_64-linux-gnu/libcurl.so.4 /usr/local/lib && \\\n ln -s /usr/local/lib/libcurl.so.4 /usr/local/lib/libcurl.so\n\n\nFROM debian:buster-slim\nRUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes \\\n libcurl4 \\\n && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\n\nWORKDIR /app\nCOPY --from=builder /app/target/debug/linkedin /app/target/release/linkedin\nCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\nCMD [\"/app/target/release/linkedin\"]\nEXPOSE 3000\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9124096/" ]
74,670,903
<p>I am building a game that takes score and player name and puts them in a text file, I want to make a subsection for the menu that outputs a scores table, how do I output the textfile in a table that has been built in scene builder?</p> <ul> <li>JavaFX linking with textfield</li> </ul>
[ { "answer_id": 74670899, "author": "VGP", "author_id": 19324766, "author_profile": "https://Stackoverflow.com/users/19324766", "pm_score": 0, "selected": false, "text": "FROM rust:1.64.0-buster AS builder\nWORKDIR /app\n\nARG TOKEN\nARG DATABASE_URL\n\nRUN git config --global url.\"https://${TOKEN}:@github.com/\".insteadOf \"https://github.com/\"\n\nCOPY . .\n\nENV CARGO_NET_GIT_FETCH_WITH_CLI true\n\nRUN rustup component add rustfmt\nRUN apt-get update -y && apt-get install git wget ca-certificates curl gnupg lsb-release cmake libcurl4 -y\n\nRUN cargo build\n\n# Copy the libcurl shared library from the builder stage into the final container\nRUN mkdir -p /usr/local/lib && \\\n cp /usr/lib/x86_64-linux-gnu/libcurl.so.4 /usr/local/lib && \\\n ln -s /usr/local/lib/libcurl.so.4 /usr/local/lib/libcurl.so\n\nFROM debian:buster-slim\nWORKDIR /app\nCOPY --from=builder /app/target/debug/linkedin /app/target/release/linkedin\nCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\nCMD [\"/app/target/release/linkedin\"]\nEXPOSE 3000\n" }, { "answer_id": 74675291, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 3, "selected": true, "text": "libcurl4 libcurl4 cargo build RUN rustup target add x86_64-unknown-linux-musl\nRUN cargo build --target=x86_64-unknown-linux-musl --release\n --release libcurl4 RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes \\\n libcurl4 \\\n && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\n FROM rust:1.64.0-buster AS builder\nWORKDIR /app\n\nARG TOKEN\nARG DATABASE_URL\n\nRUN git config --global url.\"https://${TOKEN}:@github.com/\".insteadOf \"https://github.com/\"\n\nCOPY . .\n\nENV CARGO_NET_GIT_FETCH_WITH_CLI true\n\nRUN rustup component add rustfmt\nRUN apt-get update -y && apt-get install git wget ca-certificates curl gnupg lsb-release cmake libcurl4 -y\n\nRUN cargo build\n\n# Copy the libcurl shared library from the builder stage into the final container\nRUN mkdir -p /usr/local/lib && \\\n cp /usr/lib/x86_64-linux-gnu/libcurl.so.4 /usr/local/lib && \\\n ln -s /usr/local/lib/libcurl.so.4 /usr/local/lib/libcurl.so\n\n\nFROM debian:buster-slim\nRUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes \\\n libcurl4 \\\n && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\n\nWORKDIR /app\nCOPY --from=builder /app/target/debug/linkedin /app/target/release/linkedin\nCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\n\nCMD [\"/app/target/release/linkedin\"]\nEXPOSE 3000\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20607354/" ]
74,670,908
<p>The code here only shows how many words they are, how do i ignore the words that are the same? For example, &quot;A long long time ago, I can still remember&quot;, would return 8 instead of 9.</p> <p>I want it to be a method which takes one parameter s of type String and returns an int value. And im only allowed to use the bacics, so no hash keys and advance stuff.</p> <pre><code> public static int mostCommonLetter(String s){ int wordCount = 0; boolean word = false; int endOfLine = s.length() - 1; for (int i = 0; i &lt; s.length(); i++) { if (Character.isLetter(s.charAt(i)) &amp;&amp; i != endOfLine) { word = true; } else if (!Character.isLetter(s.charAt(i)) &amp;&amp; word) { wordCount++; word = false; } else if (Character.isLetter(s.charAt(i)) &amp;&amp; i == endOfLine) { wordCount++; } } return wordCount; } } </code></pre> <p>How do i ignore the words that are the same?</p>
[ { "answer_id": 74670969, "author": "JustAnotherDeveloper", "author_id": 14071914, "author_profile": "https://Stackoverflow.com/users/14071914", "pm_score": 1, "selected": false, "text": "import java.util.*;\n\npublic class MyClass {\n public static void main(String args[]) {\n String input = \"A long long time ago, I can still remember\";\n String[] words = input.split(\" \");\n List<String> uniqueWords = new ArrayList<>();\n for (String word : words) {\n if (!uniqueWords.contains(word)) {\n uniqueWords.add(word);\n } \n }\n System.out.println(\"Number of unique words: \" + uniqueWords.size());\n }\n}\n" }, { "answer_id": 74671009, "author": "diziaq", "author_id": 2774914, "author_profile": "https://Stackoverflow.com/users/2774914", "pm_score": 1, "selected": false, "text": "public int getUniqueWords(String input) {\n // Split the string into words using the split() method\n String[] words = input.split(\" \");\n\n // Create a Set to store the unique words\n Set<String> uniqueWords = new HashSet<String>();\n\n // Loop through the words and add them to the Set\n for (String word : words) {\n uniqueWords.add(word);\n }\n\n // Return unique words amount\n return uniqueWords.size();\n}\n public int getUniqueWords2(String input) {\n // here we can safely cast to int, because String can contain at most \"max int\" chars\n return (int) Arrays.stream(input.split(\" \")).distinct().count();\n}\n input // remove leading and trailing spaces\ncleanInput = input.trim();\n\n// replace multiple spaces with a single space\ncleanInput = cleanInput.replaceAll(\"\\\\s+\", \" \"); \n O(n^2)" }, { "answer_id": 74672242, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 0, "selected": false, "text": "Set<T> public static int getTotalUniqueWords(String input) {\n String[] words = input.split(\" \");\n Set<String> uniqueWords = new HashSet<>();\n Collections.addAll(uniqueWords, words);\n return uniqueWords.size();\n}\n public static long getTotalUniqueWordsStream(String input) {\n String[] words = input.split(\" \");\n return Arrays.stream(words).distinct().count();\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20572292/" ]
74,670,914
<p>So, I'm supposed to write a function <code>normpdf(x , avg, std)</code> that returns the Gaussian probability density function of <code>x</code> for a normal distribution with mean <code>avg</code> and standard deviation <code>std</code>, with <code>avg = 0</code> and <code>std = 1</code>.</p> <p>This is what I got so far, but when I click run, I get this message:</p> <pre class="lang-py prettyprint-override"><code>Input In [95] return pdf ^ SyntaxError: invalid syntax </code></pre> <p>I'm confused on what I did wrong on that part.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import math def normpdf(x, avg=0, std=1) : # normal distribution eq exponent = math.exp(-0.5 * ((x - avg) / std) ** 2) pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) return pdf # set x values x = np.linspace(1, 50) normpdf(x, avg, std) </code></pre> <p>I added the parenthesis here and <code>math.sqrt</code>:</p> <pre class="lang-py prettyprint-override"><code>pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) </code></pre> <p>... but then I got this message:</p> <pre class="lang-py prettyprint-override"><code>TypeError Traceback (most recent call last) Input In [114], in &lt;cell line: 11&gt;() 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf ---&gt; 11 normpdf(x, avg, std) Input In [114], in normpdf(x, avg, std) 6 def normpdf(x, avg=0, std=1) : 7 #normal distribution eq ----&gt; 8 exponent = math.exp(-0.5*((x-avg)/std)**2) 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf TypeError: only size-1 arrays can be converted to Python scalars </code></pre>
[ { "answer_id": 74671180, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "import numpy as np\n\ndef normpdf(x, avg=0, std=1):\n # Compute the exponent\n exponent = np.exp(-0.5 * ((x - avg) / std) ** 2)\n\n # Compute the normalization constant\n const = 1 / (std * np.sqrt(2 * np.pi))\n\n # Compute the normal probability density function\n pdf = const * exponent\n\n return pdf\n\n# Set x values\nx = np.linspace(1, 50)\n\n# Compute the probability density function for the given values of x\npdf = normpdf(x, avg, std)\n\n# Print the result\nprint(pdf)\n" }, { "answer_id": 74671181, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": false, "text": "math numpy import numpy as np\n\n\ndef normpdf(x, avg=0, std=1):\n exp = np.exp(-0.5 * ((x - avg) / std) ** 2)\n pdf = (1 / (std * np.sqrt(2 * np.pi)) * exp)\n return pdf\n\n\nx = np.linspace(1, 50)\n\nprint(normpdf(x))\n [2.41970725e-001 5.39909665e-002 4.43184841e-003 1.33830226e-004\n 1.48671951e-006 6.07588285e-009 9.13472041e-012 5.05227108e-015\n 1.02797736e-018 7.69459863e-023 2.11881925e-027 2.14638374e-032\n 7.99882776e-038 1.09660656e-043 5.53070955e-050 1.02616307e-056\n 7.00418213e-064 1.75874954e-071 1.62463604e-079 5.52094836e-088\n 6.90202942e-097 3.17428155e-106 5.37056037e-116 3.34271444e-126\n 7.65392974e-137 6.44725997e-148 1.99788926e-159 2.27757748e-171\n 9.55169454e-184 1.47364613e-196 8.36395161e-210 1.74636626e-223\n 1.34141967e-237 3.79052640e-252 3.94039628e-267 1.50690472e-282\n 2.12000655e-298 1.09722105e-314 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000]\n" }, { "answer_id": 74671344, "author": "GAP2002", "author_id": 14608493, "author_profile": "https://Stackoverflow.com/users/14608493", "pm_score": 0, "selected": false, "text": "math.exp() np.exp() import numpy as np\n\ndef normpdf(x, avg=0, std=1):\n # normal distribution eq\n exponent = np.exp(-0.5 * ((x - avg) / std) ** 2)\n pdf = (1 / (std * np.sqrt(2 * np.pi)) * exponent)\n return pdf\n\n# set x values\nx = np.linspace(1, 50)\n\nnormpdf(x)\n math.exp() math.sqrt() np.exp() np.sqrt()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677381/" ]
74,670,922
<pre><code>import 'package:flutter/material.dart'; class LayOutBuilder extends StatelessWidget { const LayOutBuilder({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: LayoutBuilder( builder: (context, p1) { if (p1.maxHeight &lt; 400) { return Container(); } }, ), ); } } </code></pre> <p>I dont know why it does not run.</p>
[ { "answer_id": 74670966, "author": "jraufeisen", "author_id": 2641242, "author_profile": "https://Stackoverflow.com/users/2641242", "pm_score": 1, "selected": false, "text": "builder return Scaffold(\n body: LayoutBuilder(\n builder: (context, p1) {\n if (p1.maxHeight < 400) {\n return Container();\n } else {\n return SizedBox(height: 0) // Or any other widget\n }\n }),\n);\n" }, { "answer_id": 74670974, "author": "Hydra", "author_id": 18299640, "author_profile": "https://Stackoverflow.com/users/18299640", "pm_score": 3, "selected": true, "text": "Container p1.maxHeight < 400 p1.maxHeight < 400 if (p1.maxHeight < 400) {\n return Container();\n} else {\n return Text('some widget');\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677437/" ]
74,670,924
<p>I have a input object</p> <pre><code> @Getter class Txn { private String hash; private String withdrawId; private String depositId; private Integer amount; private String date; } </code></pre> <p>and the output object is</p> <pre><code> @Builder @Getter class UserTxn { private String hash; private String walletId; private String txnType; private Integer amount; } </code></pre> <p>In the <strong>Txn</strong> object transfers the <strong>amount</strong> from the <strong>withdrawId -&gt; depositId</strong>.</p> <p>what I am doing is I am <strong>adding</strong> all the <strong>transactions</strong> (Txn objects) in a single amount <strong>grouped by hash</strong>.</p> <p>but for that I have to make <strong>two streams for groupingby</strong> withdrawId and second or for depositId and then the <strong>third stream for merging</strong> them</p> <p>grouping by withdrawId</p> <pre><code>var withdrawStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -&gt; hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -&gt; UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType(&quot;WITHDRAW&quot;) .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); </code></pre> <p>grouping by depositId</p> <pre><code>var depositStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -&gt; hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -&gt; UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType(&quot;DEPOSIT&quot;) .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); </code></pre> <p>then merging them again, using deposites - withdraws</p> <pre><code>var res = Stream.concat(withdrawStream, depositStream).collect(Collectors.groupingBy(UserTxn::getHash, LinkedHashMap::new, Collectors.groupingBy(UserTxn::getWalletId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -&gt; hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -&gt; { var depositAmount = withdrawEntrySet.getValue().stream().filter(userTxn -&gt; userTxn.txnType.equals(&quot;DEPOSIT&quot;)).map(UserTxn::getAmount).reduce(0, Integer::sum); var withdrawAmount = withdrawEntrySet.getValue().stream().filter(userTxn -&gt; userTxn.txnType.equals(&quot;WITHDRAW&quot;)).map(UserTxn::getAmount).reduce(0, Integer::sum); var totalAmount = depositAmount-withdrawAmount; return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType(totalAmount &gt; 0 ? &quot;DEPOSIT&quot;: &quot;WITHDRAW&quot;) .amount(totalAmount) .build(); } )); </code></pre> <p>My question is, How can I do this in one stream. Like by somehow groupingBy withdrawId and depositId is one grouping.</p> <p>something like</p> <pre><code>res = txnList.stream() .collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId &amp;&amp; Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -&gt; hashEntrySet.getValue().entrySet().stream() .map(walletEntrySet -&gt; { var totalAmount = walletEntrySet.getValue().stream().map( txn -&gt; Objects.equals(txn.getDepositId(), walletEntrySet.getKey()) ? txn.getAmount() : (-txn.getAmount())).reduce(0, Integer::sum); return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(walletEntrySet.getKey()) .txnType(&quot;WITHDRAW&quot;) .amount(totalAmount) .build(); } )); </code></pre>
[ { "answer_id": 74670966, "author": "jraufeisen", "author_id": 2641242, "author_profile": "https://Stackoverflow.com/users/2641242", "pm_score": 1, "selected": false, "text": "builder return Scaffold(\n body: LayoutBuilder(\n builder: (context, p1) {\n if (p1.maxHeight < 400) {\n return Container();\n } else {\n return SizedBox(height: 0) // Or any other widget\n }\n }),\n);\n" }, { "answer_id": 74670974, "author": "Hydra", "author_id": 18299640, "author_profile": "https://Stackoverflow.com/users/18299640", "pm_score": 3, "selected": true, "text": "Container p1.maxHeight < 400 p1.maxHeight < 400 if (p1.maxHeight < 400) {\n return Container();\n} else {\n return Text('some widget');\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11692715/" ]
74,670,948
<p>With a dataset such as <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">this</a>:</p> <pre><code> famid birth age ht 0 1 1 one 2.8 1 1 1 two 3.4 2 1 2 one 2.9 3 1 2 two 3.8 4 1 3 one 2.2 5 1 3 two 2.9 </code></pre> <p>...where we've got values for a variable <code>ht</code> for different categories of, for example, <code>age</code> , I would like to adjust a subset of the data in <code>df['ht']</code> where <code>df['age'] == 'one'</code> <em>only</em>. And I would like to do it without creating a new column.</p> <p>I've tried:</p> <pre><code>df[df['age']=='one']['ht'] = df[df['age']=='one']['ht']*10**6 </code></pre> <p>But to my mild surprise the numbers don't change. Maybe because the <code>A value is trying to be set on a copy of a slice from a DataFrame</code> warning is triggered in the same run. I've also tried with <code>df.mask()</code> and <code>df.where()</code>. But to no avail. I'm clearly failing at something very basic here, but I'd really like to know how to do this properly. There are similarly sounding questions such as <a href="https://stackoverflow.com/questions/28017807/performing-calculations-on-subset-of-data-frame-subset-in-python">Performing calculations on subset of data frame subset in Python</a>, but the suggested solutions here are pointing towards <code>df.groupby()</code>, and I don't think this necessarily is the right approach here.</p> <p>Thank you for any suggestions!</p> <p>Here's a fully reproducible dataset:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] }) df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix=r'\w+') df.reset_index(inplace = True) </code></pre>
[ { "answer_id": 74670980, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 2, "selected": false, "text": "df.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n df[df['age'] == 'one']['ht'] * 10**6 import pandas as pd\n\ndf = pd.DataFrame({\n 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n})\ndf = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age',\n sep='_', suffix=r'\\w+')\ndf.reset_index(inplace = True)\n\n# Adjust the values in the ht column where the age column is 'one'\ndf.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n\n# Print the updated dataframe\nprint(df)\n" }, { "answer_id": 74671139, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "df.loc[df['age']=='one', 'ht'] = df.loc[df['age']=='one', 'ht'] * 10**6\n df.loc[df['age']=='one', ['ht', 'birth']] = df.loc[df['age']=='one', ['ht', 'birth']]\n" }, { "answer_id": 74671154, "author": "Freyam Mehta", "author_id": 13156202, "author_profile": "https://Stackoverflow.com/users/13156202", "pm_score": 1, "selected": false, "text": "df.loc[mask, column] = new_value\n df.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n mask = df['age'].isin(['one'])\n df.loc[mask, 'ht'] = df[mask]['ht'] * 10**6\n" }, { "answer_id": 74671370, "author": "Scott Boston", "author_id": 6361531, "author_profile": "https://Stackoverflow.com/users/6361531", "pm_score": 2, "selected": false, "text": "df.loc[df['age'] == 'one', 'ht'] *= 10**6\n famid birth age ht\n0 1 1 one 2800000.0\n1 1 1 two 3.4\n2 1 2 one 2900000.0\n3 1 2 two 3.8\n4 1 3 one 2200000.0\n5 1 3 two 2.9\n6 2 1 one 2000000.0\n7 2 1 two 3.2\n8 2 2 one 1800000.0\n9 2 2 two 2.8\n10 2 3 one 1900000.0\n11 2 3 two 2.4\n12 3 1 one 2200000.0\n13 3 1 two 3.3\n14 3 2 one 2300000.0\n15 3 2 two 3.4\n16 3 3 one 2100000.0\n17 3 3 two 2.9\n" }, { "answer_id": 74671400, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 1, "selected": false, "text": "df.assign(ht = df['ht'].mask(df['age'].isin(['one']),df['ht'].mul(10**6)))\n isin() famid birth age ht\n0 1 1 one 2800000.0\n1 1 1 two 3.4\n2 1 2 one 2900000.0\n3 1 2 two 3.8\n4 1 3 one 2200000.0\n5 1 3 two 2.9\n6 2 1 one 2000000.0\n7 2 1 two 3.2\n8 2 2 one 1800000.0\n9 2 2 two 2.8\n10 2 3 one 1900000.0\n11 2 3 two 2.4\n12 3 1 one 2200000.0\n13 3 1 two 3.3\n14 3 2 one 2300000.0\n15 3 2 two 3.4\n16 3 3 one 2100000.0\n17 3 3 two 2.9\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3437787/" ]
74,670,988
<p>I would like to know how to add code in my action listener that would make the row I select or press on with my mouse change from the color red to the color white. I have tried getRowSelected() and tried to use the index but that ultimately only changes the row color when it is selected and it goes back to red. I have also attempted to user Renderer which is a newer concept to me but didn't know how to implement it the right way. Any help or guidance would be appreciated.</p> <p>Tried getRowSelected() but the row color change was only temporary and went back to red once it was unselected. Tried Renderer but didn't know how to fully implement it as it is a new concept to me.</p>
[ { "answer_id": 74671105, "author": "mesutpiskin", "author_id": 2647294, "author_profile": "https://Stackoverflow.com/users/2647294", "pm_score": 1, "selected": true, "text": "import java.awt.Color;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class CustomerNotif extends JFrame {\n private static final long serialVersionUID = 1L;\n private JTable table;\n public static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n CustomerNotif frame = new CustomerNotif();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n });\n }\n public CustomerNotif() {\n // Set up the frame and other UI components here...\n\n // Create a custom cell renderer that sets the cell color based on whether the row is selected\n DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n // Set the default cell color to white\n setBackground(Color.WHITE);\n\n // If the row is selected, set the cell color to red\n if (isSelected) {\n setBackground(Color.RED);\n }\n\n // Return the configured renderer\n return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n }\n };\n\n // Set the cell renderer for each column in the table\n for (int i = 0; i < table.getColumnCount(); i++) {\n table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);\n }\n }\n}\n" }, { "answer_id": 74671254, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\n\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class TestTableRowColor {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n ChangeRowColorPanel mainPanel = new ChangeRowColorPanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n @SuppressWarnings(\"serial\")\nclass ChangeRowColorPanel extends JPanel {\n private static final String[] COLUMN_NAMES = { \"One\", \"Two\", \"Three\", \"Selected\" };\n private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);\n private JTable table = new JTable(model);\n\n public ChangeRowColorPanel() {\n TableColumnModel columnModel = table.getColumnModel();\n columnModel.removeColumn(columnModel.getColumn(columnModel.getColumnCount() - 1));\n table.setDefaultRenderer(Object.class, new RowColorRenderer());\n table.addMouseListener(new MyMouse());\n\n int max = 5;\n for (int i = 0; i < max; i++) {\n Object[] row = new Object[COLUMN_NAMES.length];\n for (int j = 0; j < COLUMN_NAMES.length - 1; j++) {\n row[j] = (int) (100 * Math.random());\n }\n row[COLUMN_NAMES.length - 1] = false;\n model.addRow(row);\n }\n\n setLayout(new BorderLayout());\n add(new JScrollPane(table));\n }\n}\n class MyMouse extends MouseAdapter {\n @Override\n public void mousePressed(MouseEvent e) {\n JTable table = (JTable) e.getSource();\n TableModel model = table.getModel();\n boolean selected = (boolean) model.getValueAt(table.getSelectedRow(), model.getColumnCount() - 1);\n model.setValueAt(!selected, table.getSelectedRow(), model.getColumnCount() - 1);\n table.repaint();\n }\n}\n @SuppressWarnings(\"serial\")\nclass RowColorRenderer extends DefaultTableCellRenderer {\n private static final Color SELECTED_COLOR = Color.PINK;\n\n public RowColorRenderer() {\n setOpaque(true);\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n TableModel model = table.getModel();\n int selectedColumn = model.getColumnCount() - 1;\n boolean selected = (boolean) model.getValueAt(row, selectedColumn);\n Color background = selected ? SELECTED_COLOR : null;\n renderer.setBackground(background);\n return this;\n }\n\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74670988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16916384/" ]
74,671,027
<p>I mapped the countries in select. When I reset the select the placeholder is still the country name, but the value is reset to undefined.</p> <pre><code>const countries = [ { label: 'France', value: 'FR' }, { label: 'Germany', value: 'DE' }, ]; </code></pre> <pre><code>const defaultValues = { country: undefined, }; </code></pre> <pre><code>const Select: FC&lt;Props&gt; = ({ options, onSelect, placeholder = 'Select option', ...props }) =&gt; { const handleSelect = useCallback( (ev) =&gt; { const { value } = ev.target; const select = value ? options.find((opt) =&gt; opt.value === value) : null; onSelect(select); }, [options] ); return ( &lt;ChakraSelect onChange={handleSelect} placeholder={placeholder} {...props} &gt; {options?.map((opt) =&gt; ( &lt;option key={opt.label} value={opt.value}&gt; {opt.label} &lt;/option&gt; ))} &lt;/ChakraSelect&gt; ); }; export default Select; </code></pre> <pre><code>&lt;FormControl isInvalid={errors.country}&gt; &lt;Controller control={control} name='country' render={({ field: { onChange, value } }) =&gt; { return ( &lt;Select onSelect={onChange} options={countries} placeholder='Select country' value={value?.value} /&gt; ); }} rules={{ required: { value: true, message: 'Country is required', }, }} /&gt; </code></pre> <p>Reset using react-hook-form:</p> <pre><code>reset({...defaultValues}); </code></pre> <p>Here is the result after reset, value: undefined, but the placeholder is still the country name: <a href="https://i.stack.imgur.com/4pC6S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4pC6S.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74671105, "author": "mesutpiskin", "author_id": 2647294, "author_profile": "https://Stackoverflow.com/users/2647294", "pm_score": 1, "selected": true, "text": "import java.awt.Color;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class CustomerNotif extends JFrame {\n private static final long serialVersionUID = 1L;\n private JTable table;\n public static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n CustomerNotif frame = new CustomerNotif();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n });\n }\n public CustomerNotif() {\n // Set up the frame and other UI components here...\n\n // Create a custom cell renderer that sets the cell color based on whether the row is selected\n DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n // Set the default cell color to white\n setBackground(Color.WHITE);\n\n // If the row is selected, set the cell color to red\n if (isSelected) {\n setBackground(Color.RED);\n }\n\n // Return the configured renderer\n return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n }\n };\n\n // Set the cell renderer for each column in the table\n for (int i = 0; i < table.getColumnCount(); i++) {\n table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);\n }\n }\n}\n" }, { "answer_id": 74671254, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\n\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class TestTableRowColor {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n ChangeRowColorPanel mainPanel = new ChangeRowColorPanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n @SuppressWarnings(\"serial\")\nclass ChangeRowColorPanel extends JPanel {\n private static final String[] COLUMN_NAMES = { \"One\", \"Two\", \"Three\", \"Selected\" };\n private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);\n private JTable table = new JTable(model);\n\n public ChangeRowColorPanel() {\n TableColumnModel columnModel = table.getColumnModel();\n columnModel.removeColumn(columnModel.getColumn(columnModel.getColumnCount() - 1));\n table.setDefaultRenderer(Object.class, new RowColorRenderer());\n table.addMouseListener(new MyMouse());\n\n int max = 5;\n for (int i = 0; i < max; i++) {\n Object[] row = new Object[COLUMN_NAMES.length];\n for (int j = 0; j < COLUMN_NAMES.length - 1; j++) {\n row[j] = (int) (100 * Math.random());\n }\n row[COLUMN_NAMES.length - 1] = false;\n model.addRow(row);\n }\n\n setLayout(new BorderLayout());\n add(new JScrollPane(table));\n }\n}\n class MyMouse extends MouseAdapter {\n @Override\n public void mousePressed(MouseEvent e) {\n JTable table = (JTable) e.getSource();\n TableModel model = table.getModel();\n boolean selected = (boolean) model.getValueAt(table.getSelectedRow(), model.getColumnCount() - 1);\n model.setValueAt(!selected, table.getSelectedRow(), model.getColumnCount() - 1);\n table.repaint();\n }\n}\n @SuppressWarnings(\"serial\")\nclass RowColorRenderer extends DefaultTableCellRenderer {\n private static final Color SELECTED_COLOR = Color.PINK;\n\n public RowColorRenderer() {\n setOpaque(true);\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n TableModel model = table.getModel();\n int selectedColumn = model.getColumnCount() - 1;\n boolean selected = (boolean) model.getValueAt(row, selectedColumn);\n Color background = selected ? SELECTED_COLOR : null;\n renderer.setBackground(background);\n return this;\n }\n\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15042979/" ]
74,671,048
<p>I've been trying to get shell from this function but nothing seems to work<br> so what's happening here is that I have a variable of size 32 bytes and I'm trying to copy 600bytes to it<br> what I don't understand is, where my shell code will be executed is it inside the 32bytes or in the 600 - 32 bytes.<br> I can't give the whole working code as this is just a disassembly code from ghidra.</p> <p>Any help what should I do?<br> Thanks in advance.</p> <pre class="lang-c prettyprint-override"><code>void foo(void *param) { undefined varialbe [32]; memcpy(variable, param, 600); return; } </code></pre> <p>this is the shellcode I tried</p> <pre class="lang-bash prettyprint-override"><code>\x31\xc0\x50\x68\x2f\x63\x61\x74\x68\x2f\x62\x69\x6e\x89\xe3\x50\x68\x2e\x74\x78\x74\x68\x66\x6c\x61\x67\x89\xe1\x50\x51\x53\x89\xe1\x31\xc0\x83\xc0\x0b\xcd\x80 </code></pre> <p>I was expecting that I will get a shell on the system if I just input the above shell code. but all I get for not is segfaults.</p> <p>I'm new to binary exploitations. so sorry if this is a stupid question and sorry for my english.</p>
[ { "answer_id": 74671105, "author": "mesutpiskin", "author_id": 2647294, "author_profile": "https://Stackoverflow.com/users/2647294", "pm_score": 1, "selected": true, "text": "import java.awt.Color;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class CustomerNotif extends JFrame {\n private static final long serialVersionUID = 1L;\n private JTable table;\n public static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n CustomerNotif frame = new CustomerNotif();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n });\n }\n public CustomerNotif() {\n // Set up the frame and other UI components here...\n\n // Create a custom cell renderer that sets the cell color based on whether the row is selected\n DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n // Set the default cell color to white\n setBackground(Color.WHITE);\n\n // If the row is selected, set the cell color to red\n if (isSelected) {\n setBackground(Color.RED);\n }\n\n // Return the configured renderer\n return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n }\n };\n\n // Set the cell renderer for each column in the table\n for (int i = 0; i < table.getColumnCount(); i++) {\n table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);\n }\n }\n}\n" }, { "answer_id": 74671254, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\n\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class TestTableRowColor {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n ChangeRowColorPanel mainPanel = new ChangeRowColorPanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n @SuppressWarnings(\"serial\")\nclass ChangeRowColorPanel extends JPanel {\n private static final String[] COLUMN_NAMES = { \"One\", \"Two\", \"Three\", \"Selected\" };\n private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);\n private JTable table = new JTable(model);\n\n public ChangeRowColorPanel() {\n TableColumnModel columnModel = table.getColumnModel();\n columnModel.removeColumn(columnModel.getColumn(columnModel.getColumnCount() - 1));\n table.setDefaultRenderer(Object.class, new RowColorRenderer());\n table.addMouseListener(new MyMouse());\n\n int max = 5;\n for (int i = 0; i < max; i++) {\n Object[] row = new Object[COLUMN_NAMES.length];\n for (int j = 0; j < COLUMN_NAMES.length - 1; j++) {\n row[j] = (int) (100 * Math.random());\n }\n row[COLUMN_NAMES.length - 1] = false;\n model.addRow(row);\n }\n\n setLayout(new BorderLayout());\n add(new JScrollPane(table));\n }\n}\n class MyMouse extends MouseAdapter {\n @Override\n public void mousePressed(MouseEvent e) {\n JTable table = (JTable) e.getSource();\n TableModel model = table.getModel();\n boolean selected = (boolean) model.getValueAt(table.getSelectedRow(), model.getColumnCount() - 1);\n model.setValueAt(!selected, table.getSelectedRow(), model.getColumnCount() - 1);\n table.repaint();\n }\n}\n @SuppressWarnings(\"serial\")\nclass RowColorRenderer extends DefaultTableCellRenderer {\n private static final Color SELECTED_COLOR = Color.PINK;\n\n public RowColorRenderer() {\n setOpaque(true);\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n TableModel model = table.getModel();\n int selectedColumn = model.getColumnCount() - 1;\n boolean selected = (boolean) model.getValueAt(row, selectedColumn);\n Color background = selected ? SELECTED_COLOR : null;\n renderer.setBackground(background);\n return this;\n }\n\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12246961/" ]
74,671,069
<p>I have been trying to make a &quot;hidden text&quot; website of sorts.</p> <p>I have managed to code a circular <code>div</code> that follows my mouse cursor and inverts every text underneath it using <code>background-filter</code> in CSS and Javascript:</p> <pre><code>let circle = document.getElementById('circle'); const onMouseMove = (e) =&gt; { circle.style.left = e.pageX + 'px'; circle.style.top = e.pageY + 'px'; } document.addEventListener('mousemove', onMouseMove); </code></pre> <p>The CSS for the #circle element is:</p> <pre><code>#circle { position: absolute; transform: translate(-50%,-50%); height: 80px; width: 80px; border-radius: 50%; box-shadow: 0px 0px 40px 10px white; pointer-events: none; backdrop-filter: invert(100%); z-index: 100; } </code></pre> <p>I have tried setting the text opacity to 5% and then setting <code>backdrop-filter: opacity(100%)</code> but that didn't work, unfortunately. How should I go about achieving this? I am open to any and all libraries and willing to follow any tutorial. Accessibility is not an issue at the moment as this is just an experiment for myself.</p>
[ { "answer_id": 74671105, "author": "mesutpiskin", "author_id": 2647294, "author_profile": "https://Stackoverflow.com/users/2647294", "pm_score": 1, "selected": true, "text": "import java.awt.Color;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class CustomerNotif extends JFrame {\n private static final long serialVersionUID = 1L;\n private JTable table;\n public static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n CustomerNotif frame = new CustomerNotif();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n });\n }\n public CustomerNotif() {\n // Set up the frame and other UI components here...\n\n // Create a custom cell renderer that sets the cell color based on whether the row is selected\n DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n // Set the default cell color to white\n setBackground(Color.WHITE);\n\n // If the row is selected, set the cell color to red\n if (isSelected) {\n setBackground(Color.RED);\n }\n\n // Return the configured renderer\n return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n }\n };\n\n // Set the cell renderer for each column in the table\n for (int i = 0; i < table.getColumnCount(); i++) {\n table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);\n }\n }\n}\n" }, { "answer_id": 74671254, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\n\nimport javax.swing.*;\nimport javax.swing.table.*;\n\npublic class TestTableRowColor {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n ChangeRowColorPanel mainPanel = new ChangeRowColorPanel();\n\n JFrame frame = new JFrame(\"GUI\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n\n}\n @SuppressWarnings(\"serial\")\nclass ChangeRowColorPanel extends JPanel {\n private static final String[] COLUMN_NAMES = { \"One\", \"Two\", \"Three\", \"Selected\" };\n private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);\n private JTable table = new JTable(model);\n\n public ChangeRowColorPanel() {\n TableColumnModel columnModel = table.getColumnModel();\n columnModel.removeColumn(columnModel.getColumn(columnModel.getColumnCount() - 1));\n table.setDefaultRenderer(Object.class, new RowColorRenderer());\n table.addMouseListener(new MyMouse());\n\n int max = 5;\n for (int i = 0; i < max; i++) {\n Object[] row = new Object[COLUMN_NAMES.length];\n for (int j = 0; j < COLUMN_NAMES.length - 1; j++) {\n row[j] = (int) (100 * Math.random());\n }\n row[COLUMN_NAMES.length - 1] = false;\n model.addRow(row);\n }\n\n setLayout(new BorderLayout());\n add(new JScrollPane(table));\n }\n}\n class MyMouse extends MouseAdapter {\n @Override\n public void mousePressed(MouseEvent e) {\n JTable table = (JTable) e.getSource();\n TableModel model = table.getModel();\n boolean selected = (boolean) model.getValueAt(table.getSelectedRow(), model.getColumnCount() - 1);\n model.setValueAt(!selected, table.getSelectedRow(), model.getColumnCount() - 1);\n table.repaint();\n }\n}\n @SuppressWarnings(\"serial\")\nclass RowColorRenderer extends DefaultTableCellRenderer {\n private static final Color SELECTED_COLOR = Color.PINK;\n\n public RowColorRenderer() {\n setOpaque(true);\n }\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n TableModel model = table.getModel();\n int selectedColumn = model.getColumnCount() - 1;\n boolean selected = (boolean) model.getValueAt(row, selectedColumn);\n Color background = selected ? SELECTED_COLOR : null;\n renderer.setBackground(background);\n return this;\n }\n\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677514/" ]
74,671,077
<p>(Edited)If i copy the code from the answer given bellow from a different user it works perfectly in a new black html file.Something must be going on with my code not allowing the redirection to happend.I will include some of the html/css of the program</p> <pre><code>&lt;header class='header'&gt; &lt;title&gt;Εγγραφή&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;mystyle.css&quot; &gt; &lt;center&gt;&lt;img src=&quot;logo.png&quot; alt=&quot;LOGO&quot; height=100&gt;&lt;/center&gt; &lt;/header&gt; &lt;div class=&quot;text&quot;&gt; &lt;p style=&quot;font-family: system-ui; font-size: 15pt;&quot;&gt; &lt;label for=&quot;onoma&quot; style=&quot;font-size:15pt;&quot;&gt;Διεύθυνση*:&lt;/label&gt;&amp;nbsp; &lt;input id=&quot;address&quot; type=&quot;text&quot; name=&quot;address&quot; value=&quot;&quot; &gt;&amp;nbsp;&amp;nbsp; &lt;p style=&quot;font-family: system-ui; font-size: 15pt;&quot;&gt; &lt;div class=&quot;text&quot;&gt; &lt;label for=&quot;mera&quot; style=&quot;font-size:15pt;&quot;&gt;Συνθηματικό πρόσβασης*:&lt;/label&gt;&amp;nbsp; &lt;input id=&quot;password&quot; type=&quot;password&quot; name=&quot;mera&quot; value=&quot;&quot; &gt;&amp;nbsp;&amp;nbsp; &lt;label for=&quot;minas&quot; style=&quot;font-size:15pt;&quot;&gt;Κωδικός πρόσβασης*:&lt;/label&gt;&amp;nbsp; &lt;input id=&quot;password2&quot; type=&quot;password&quot; name=&quot;minas&quot; value=&quot;&quot; &gt;&amp;nbsp;&amp;nbsp; div align=&quot;center&quot;&gt; &lt;input type=&quot;reset&quot; value=&quot;Reset&quot;&gt; &lt;input type=&quot;submit&quot; id=&quot;btn&quot; value=&quot;submit&quot;&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt;&amp;nbsp;&lt;br&gt;&lt;br&gt;&amp;nbsp; &lt;script type=&quot;text/javascript&quot; src=&quot;java.js&quot;&gt;&lt;/script&gt; </code></pre> <p>CSS</p> <pre><code>body { margin: 0; font-family: system-ui } .logocolor { background-color:cornflowerblue; } .background{ background-color:wheat; } header { background-color: rgb(0, 132, 255); } .text{ text-align:left; text-indent: 150px; } label { font-family: system-ui } .change{ display: flex; } </code></pre> <p>Also the current java</p> <pre><code>function CheckPassword(address, password, password2) { if (password === &quot;&quot; || password2 === &quot;&quot; || address === &quot;&quot;) { alert(&quot;Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά&quot;) } else { alert('message'); window.location = 'newpage.html'; } } function ClickMe() { CheckPassword( document.getElementById('address').value, document.getElementById('password').value, document.getElementById('password2').value ); } document.getElementById('btn').addEventListener(&quot;click&quot;, function() {ClickMe()}); </code></pre>
[ { "answer_id": 74671132, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": -1, "selected": false, "text": "window.location.href window.location document.getElementById(\"navigate\").addEventListener(\"click\", (e) => {\n window.location.href = \"https://example.com/\";\n}) <button type=\"button\" id=\"navigate\">Navigate</button> function CheckPassword(address, password, password2) {\n if ((password == \"\") || (password2 == \"\") || (address == \"\")) {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location.href = 'new page.html';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(document.getElementById('password2').value, document.getElementById('password').value, document.getElementById('address').value)\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {\n ClickMe()\n}); window.location.href window.loaction" }, { "answer_id": 74671325, "author": "Erhan Yaşar", "author_id": 6371094, "author_profile": "https://Stackoverflow.com/users/6371094", "pm_score": 1, "selected": true, "text": "window.location.href = 'newPage.html' window.location.replace('newPage.html') function CheckPassword(address, password, password2) {\n if (password === \"\" || password2 === \"\" || address === \"\") {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location = 'https://stackoverflow.com';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(\n document.getElementById('address').value,\n document.getElementById('password').value,\n document.getElementById('password2').value\n );\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {ClickMe()}); <input type=\"text\" id=\"address\" />\n<input type=\"text\" id=\"password\" />\n<input type=\"text\" id=\"password2\" />\n\n<button id=\"btn\">Button</button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677542/" ]
74,671,078
<p>I'd like to create a query scope for my model called <code>Ticket</code>. This <code>Ticket</code> <strong>hasMany</strong> replies (Model: <code>Reply</code>). And each reply can have a status (Enum <code>Status</code>).</p> <p>Now I'd like to create a scope on the <code>Ticket</code> model, which should filter all tickets having more than 2 replies in the status <code>UNREAD</code>.</p> <p>This is my first attempt:</p> <pre class="lang-php prettyprint-override"><code>public function scopeEscalatedTickets(Builder $query): Builder { return $query-&gt;has('replies', function (Builder $q){ $q-&gt;whereNot('status', Status::READ); }); } </code></pre> <p>But now I'm stuck: How can I create the count-condition so this takes into account that I just want the tickets having more than 2 replies which do not have the <code>Status::READ</code>?</p> <p>My second thought about using something like</p> <pre class="lang-php prettyprint-override"><code>-&gt;withCount('replies')-&gt;having('replies_count', '&gt;', 2) </code></pre> <p>does not work too, and inspecting the SQL-query I at least found out that <code>withCount</code> really just counts all the related items and ignores other conditions.</p> <p>Thanks for your help :-)</p>
[ { "answer_id": 74671132, "author": "human bean", "author_id": 17186475, "author_profile": "https://Stackoverflow.com/users/17186475", "pm_score": -1, "selected": false, "text": "window.location.href window.location document.getElementById(\"navigate\").addEventListener(\"click\", (e) => {\n window.location.href = \"https://example.com/\";\n}) <button type=\"button\" id=\"navigate\">Navigate</button> function CheckPassword(address, password, password2) {\n if ((password == \"\") || (password2 == \"\") || (address == \"\")) {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location.href = 'new page.html';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(document.getElementById('password2').value, document.getElementById('password').value, document.getElementById('address').value)\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {\n ClickMe()\n}); window.location.href window.loaction" }, { "answer_id": 74671325, "author": "Erhan Yaşar", "author_id": 6371094, "author_profile": "https://Stackoverflow.com/users/6371094", "pm_score": 1, "selected": true, "text": "window.location.href = 'newPage.html' window.location.replace('newPage.html') function CheckPassword(address, password, password2) {\n if (password === \"\" || password2 === \"\" || address === \"\") {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location = 'https://stackoverflow.com';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(\n document.getElementById('address').value,\n document.getElementById('password').value,\n document.getElementById('password2').value\n );\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {ClickMe()}); <input type=\"text\" id=\"address\" />\n<input type=\"text\" id=\"password\" />\n<input type=\"text\" id=\"password2\" />\n\n<button id=\"btn\">Button</button>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7510971/" ]
74,671,079
<p>I'm consuming some k8s objects with typescript and my json looks like this:</p> <pre><code>{ &quot;startTime&quot;: &quot;2022-12-01T19:15:58Z&quot;, &quot;taskRuns&quot;: { &quot;task1&quot;: { &quot;pipelineTaskName&quot;: &quot;task1Ref&quot;, &quot;status&quot;: { &quot;completionTime&quot;: &quot;2022-12-01T19:17:27Z&quot;, &quot;conditions&quot;: [ { &quot;lastTransitionTime&quot;: &quot;2022-12-01T19:17:27Z&quot;, &quot;message&quot;: &quot;&quot;, &quot;reason&quot;: &quot;TaskRunImagePullFailed&quot;, &quot;status&quot;: &quot;False&quot;, &quot;type&quot;: &quot;Succeeded&quot; } ]}}, &quot;task2&quot;:{same fields as task1}, &quot;task3&quot;: {same} }} </code></pre> <p>I also have an array with the TaskRun names which looks like the following:</p> <pre><code>[&quot;task1&quot;,&quot;task2&quot;,....] </code></pre> <p>The relevant interface for the object above looks like:</p> <pre><code>export interface PipelineRunStatus { startTime: string; taskRuns: Truns; } export interface Truns { [key: string]: TaskRun; } export interface TaskRUn {&lt;fields from above&gt;} </code></pre> <p>I'm trying to match the array elements to the variable task keys in a taskrun and extract information with the code below:</p> <pre><code> type taskRunKey = keyof typeof currentRun.Status.taskRuns //taskRuns is my string array taskRuns.map((taskRunName: string) =&gt; { console.log(taskRunName) if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey)) console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0]) else { console.log(currentRun?.Status?.taskRuns) console.log(currentRun?.Status) } </code></pre> <p>but this prints</p> <pre><code>task1 undefined Object { TaskRuns: {… task1:{..the object above...}}} ​ task2 undefined Object { TaskRuns: {… pretty much the object above...}} ​ </code></pre> <p>etc</p> <p>In short: the code above always ends up in the &quot;else&quot; branch of the statement despite the fact that there is an object property with the correct name that matches. Can someone please explain what am I missing?</p>
[ { "answer_id": 74671109, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 1, "selected": false, "text": "for (let taskRunName in currentRun?.Status?.taskRuns) {\n console.log(taskRunName)\n\n if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey))\n console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0])\n else {\n console.log(currentRun?.Status?.taskRuns)\n console.log(currentRun?.Status)\n }\n}\n Object.keys(currentRun?.Status?.taskRuns).map((taskRunName: string) => {\n console.log(taskRunName)\n\n if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey))\n console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0])\n else {\n console.log(currentRun?.Status?.taskRuns)\n console.log(currentRun?.Status)\n }\n})\n" }, { "answer_id": 74680461, "author": "ndp", "author_id": 699012, "author_profile": "https://Stackoverflow.com/users/699012", "pm_score": 0, "selected": false, "text": "export interface PipelineRunStatus { startTime: string; TaskRuns: Truns; } hasOwnProperty Object.keys(currentRun?.Status?.TaskRuns).includes(taskRunName)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699012/" ]
74,671,112
<p>I downloaded text from the edit field to the buffer and I want to convert it to an array of strings. Every string is ending with <code>%</code>.</p> <pre class="lang-c prettyprint-override"><code>void Converter(HWND hwnd) { int Length = GetWindowTextLength(hEdit) + 1; LPSTR data = (LPSTR)malloc(Length); char set[500][11]; GetWindowTextA(hEdit, data, Length); int x = 0, y = 0; char record[10]; for (int i = 0; i &lt; Length, x&lt;500; i++) { if(data[i]!= '\0' ) { record[y] = data[i]; y++; } else if(data[i] == '%') { strcpy(set[x], record); x++; y = 0; } } free(data); } </code></pre> <p>The error message I got:</p> <pre><code>Exception thrown at location 0x00007FF684C91F9B in myproject.exe: 0xC0000005: Access violation while reading at location 0x000000CBFC8D5DAF. </code></pre>
[ { "answer_id": 74671316, "author": "anton-tchekov", "author_id": 4724047, "author_profile": "https://Stackoverflow.com/users/4724047", "pm_score": 2, "selected": false, "text": "for (int i = 0; i < Length, x<500; i++)\n for (int i = 0; i < Length && x<500; i++)\n else if if(data[i] == '%')\n{\n strcpy(set[x], record);\n x++;\n y = 0;\n}\nelse if(data[i] != '\\0')\n{\n record[y] = data[i];\n y++;\n}\n set record[y] = '\\0';\nstrcpy(set[x], record);\n strtok <string.h>" }, { "answer_id": 74671426, "author": "mzm", "author_id": 20564950, "author_profile": "https://Stackoverflow.com/users/20564950", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n char set[500][11];\n \n strcpy(&set[x][0], \"a record\");\n\n printf(\">> %s\", &set[x][0]);\n}\n >> a record\n" }, { "answer_id": 74671662, "author": "RbMm", "author_id": 6401656, "author_profile": "https://Stackoverflow.com/users/6401656", "pm_score": 0, "selected": false, "text": "char** make_array(_In_ char* buf, _Out_ unsigned* pn)\n{\n char* pc = buf;\n unsigned n = 1;\n \n while(pc = strchr(pc, '%')) n++, *pc++ = 0;\n\n if (char** arr = new char*[n])\n {\n *pn = n;\n\n char** ppc = arr;\n \n do {\n *ppc++ = buf;\n buf += strlen(buf) + 1;\n } while(--n);\n\n return arr;\n }\n\n *pn = 0;\n return 0;\n}\n\nvoid demo()\n{\n char buf[] = \"1111%2222%33333\";\n unsigned n;\n if (char** arr = make_array(buf, &n))\n {\n char** ppc = arr;\n do {\n printf(\"%s\\n\", *ppc++);\n } while (--n);\n delete [] arr;\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677187/" ]
74,671,123
<p>I am trying to get all users that have a certain <strong>listId</strong> in their contactLists object. My firebase <strong>realtime</strong> database structure is as follows:</p> <pre><code>user: john: contactLists: -NIOsvb: true, </code></pre> <p>I have other users in the DB and I want to get all that have -NIOsvb in their contactLists object. This is the approach I tried (listId is passed as a parameter):</p> <pre><code>const snapshot = await get(query(ref(db, &quot;users&quot;), orderByChild(&quot;contactLists&quot;), equalTo(listId))) </code></pre> <p>I expected to get all the user objects that have this id in their contactLists. However, the value of snapshot is null. Any suggestions would be appreciated, as I don't have a lot of experience with Firebase functions.</p>
[ { "answer_id": 74671316, "author": "anton-tchekov", "author_id": 4724047, "author_profile": "https://Stackoverflow.com/users/4724047", "pm_score": 2, "selected": false, "text": "for (int i = 0; i < Length, x<500; i++)\n for (int i = 0; i < Length && x<500; i++)\n else if if(data[i] == '%')\n{\n strcpy(set[x], record);\n x++;\n y = 0;\n}\nelse if(data[i] != '\\0')\n{\n record[y] = data[i];\n y++;\n}\n set record[y] = '\\0';\nstrcpy(set[x], record);\n strtok <string.h>" }, { "answer_id": 74671426, "author": "mzm", "author_id": 20564950, "author_profile": "https://Stackoverflow.com/users/20564950", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n \n char set[500][11];\n \n strcpy(&set[x][0], \"a record\");\n\n printf(\">> %s\", &set[x][0]);\n}\n >> a record\n" }, { "answer_id": 74671662, "author": "RbMm", "author_id": 6401656, "author_profile": "https://Stackoverflow.com/users/6401656", "pm_score": 0, "selected": false, "text": "char** make_array(_In_ char* buf, _Out_ unsigned* pn)\n{\n char* pc = buf;\n unsigned n = 1;\n \n while(pc = strchr(pc, '%')) n++, *pc++ = 0;\n\n if (char** arr = new char*[n])\n {\n *pn = n;\n\n char** ppc = arr;\n \n do {\n *ppc++ = buf;\n buf += strlen(buf) + 1;\n } while(--n);\n\n return arr;\n }\n\n *pn = 0;\n return 0;\n}\n\nvoid demo()\n{\n char buf[] = \"1111%2222%33333\";\n unsigned n;\n if (char** arr = make_array(buf, &n))\n {\n char** ppc = arr;\n do {\n printf(\"%s\\n\", *ppc++);\n } while (--n);\n delete [] arr;\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17396289/" ]
74,671,168
<p>I have a spreadseet with quite a few refrences (lookups and links to data I extract from system) In cell B1 I have how many actually rows with data I have. i.e The sheet is called Raw Data and if B1=100 I need range B2:E102 copied into sheet Master The value in B1 is dynamic, depending on data in another sheet). Could someone please help me with this? Thanks</p>
[ { "answer_id": 74671543, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub CopyRange()\n \n ' Reference the workbook.\n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n ' Reference the Source range.\n Dim sws As Worksheet: Set sws = wb.Sheets(\"Raw Data\")\n Dim slRow As Long: slRow = sws.Range(\"B1\").Value + 2\n Dim srg As Range: Set srg = sws.Range(\"B2\", sws.Cells(slRow, \"E\"))\n \n ' Reference the first Destination cell.\n Dim dws As Worksheet: Set dws = wb.Sheets(\"Master\")\n Dim dfCell As Range: Set dfCell = dws.Range(\"A1\") ' adjust!?\n \n ' Either copy values, formulas and formats,...\n srg.Copy dfCell\n ' or copy only values (more efficient):\n 'dfCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value\n \n ' Inform.\n MsgBox \"Range copied.\", vbInformation\n \nEnd Sub\n" }, { "answer_id": 74671940, "author": "JD413", "author_id": 11682370, "author_profile": "https://Stackoverflow.com/users/11682370", "pm_score": 0, "selected": false, "text": "strFile = \"C:\\Users\\raw_data.xlsm\" 'change this to your file name\nWorkbooks.Open (strFile)\n'Debug.Print strFile\n\n'log the last column for paramters\nLastColumn = ActiveSheet.Cells.Find(\"*\", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column\n\n'log the last rows for components\nLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, \"A\").End(xlUp).Row\n\nDim WorksheetStartCell As String\n\nStartCellNum = 2\n\nWorksheetHeadingStartCell = \"A\" & StartCellNum\nWorksheetValueStartCell = \"A\" & StartCellNum + 1\n\n'Debug.Print \"Worksheet Heading Start Cell: \" & WorksheetHeadingStartCell\n'Debug.Print \"Worksheet Value Start Cell: \" & WorksheetValueStartCell\n\nWorksheetHeadingEndCell = \"G\" & StartCellNum\nWorksheetValueEndCell = \"G\" & LastRow\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383423/" ]
74,671,170
<p>I have an input array which contains various domains:</p> <pre class="lang-js prettyprint-override"><code>var sites = [&quot;site2.com&quot;, &quot;site2.com&quot;, &quot;site3.com&quot;]; </code></pre> <p>I need to check, whether certain string <code>domainName</code> matches one of these sites. I used <code>indexOf</code> which worked fine, however problem occured when certain <code>domainName</code> was shown with subpage, e.g. <code>subpage.site1.com</code>. I tried to use <code>some</code> method with RegExp testing instead:</p> <pre class="lang-js prettyprint-override"><code>if(sites.some(function(rx) { return rx.test(domainName); }) </code></pre> <p>however the first problem was that I needed to change <code>&quot;&quot;</code> for every element to <code>&quot;\\&quot;</code> to make it work with RegExp:</p> <pre class="lang-js prettyprint-override"><code>var sites = [/site1.com/, /site2.com/, /site3.com/]; </code></pre> <p>while I want to keep array with quotation marks for end-user.</p> <p>Second problem was that it returns <code>true</code> for in cases where compared <code>domainName</code> is not in array, but partially its name contains is part of element in array, for example <code>anothersite1.com</code> with <code>site1.com</code>. It's rare case but happens.</p> <p>I can modify my input array with RegExp will start and end with <code>^$</code> escape characters, but it will complicate it even more, especially that I will need to also add <code>([a-z0-9]+[.])</code> to match subpages.</p> <p>I tried to use <code>replace</code> to change <code>&quot;foo&quot;</code> to <code>\foo\</code>, but I was unable since quation marks defines array elements. Also I tried to use <code>replace</code> with <code>concat</code> to merge string with escape characters to achieve element looking like RegExp formula from <code>site1.com</code> to <code>^([a-z0-9]+[.])*site1\.com$</code> but got issues with escaping characters.</p> <p>Is there a simpler way to achieve this goal?</p>
[ { "answer_id": 74671543, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 1, "selected": false, "text": "Option Explicit\n\nSub CopyRange()\n \n ' Reference the workbook.\n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n ' Reference the Source range.\n Dim sws As Worksheet: Set sws = wb.Sheets(\"Raw Data\")\n Dim slRow As Long: slRow = sws.Range(\"B1\").Value + 2\n Dim srg As Range: Set srg = sws.Range(\"B2\", sws.Cells(slRow, \"E\"))\n \n ' Reference the first Destination cell.\n Dim dws As Worksheet: Set dws = wb.Sheets(\"Master\")\n Dim dfCell As Range: Set dfCell = dws.Range(\"A1\") ' adjust!?\n \n ' Either copy values, formulas and formats,...\n srg.Copy dfCell\n ' or copy only values (more efficient):\n 'dfCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value\n \n ' Inform.\n MsgBox \"Range copied.\", vbInformation\n \nEnd Sub\n" }, { "answer_id": 74671940, "author": "JD413", "author_id": 11682370, "author_profile": "https://Stackoverflow.com/users/11682370", "pm_score": 0, "selected": false, "text": "strFile = \"C:\\Users\\raw_data.xlsm\" 'change this to your file name\nWorkbooks.Open (strFile)\n'Debug.Print strFile\n\n'log the last column for paramters\nLastColumn = ActiveSheet.Cells.Find(\"*\", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column\n\n'log the last rows for components\nLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, \"A\").End(xlUp).Row\n\nDim WorksheetStartCell As String\n\nStartCellNum = 2\n\nWorksheetHeadingStartCell = \"A\" & StartCellNum\nWorksheetValueStartCell = \"A\" & StartCellNum + 1\n\n'Debug.Print \"Worksheet Heading Start Cell: \" & WorksheetHeadingStartCell\n'Debug.Print \"Worksheet Value Start Cell: \" & WorksheetValueStartCell\n\nWorksheetHeadingEndCell = \"G\" & StartCellNum\nWorksheetValueEndCell = \"G\" & LastRow\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6345084/" ]
74,671,171
<p>If I understand correctly, value initialization <code>T obj {};</code> uses the user-define constructor while default initialization <code>T obj;</code> either uses the user-define constructor or leaves <code>obj</code> uninitialized (i.e. undefined).</p> <p>Since having uninitialized values is in general bad style, should we always prefer value initialization over default initialization? Is there any scenario where default initialization is actually better than value initialization?</p>
[ { "answer_id": 74671284, "author": "Freyam Mehta", "author_id": 13156202, "author_profile": "https://Stackoverflow.com/users/13156202", "pm_score": 0, "selected": false, "text": "struct MyStruct {\n int a;\n std::string b;\n std::vector<double> c;\n};\n\nint main() {\n // Use default initialization to initialize the member objects\n // with their default constructors\n MyStruct s;\n\n // s.a will be uninitialized (i.e. indeterminate)\n // s.b will be initialized to the empty string\n // s.c will be initialized to an empty vector\n}\n" }, { "answer_id": 74671312, "author": "The Dreams Wind", "author_id": 5690248, "author_profile": "https://Stackoverflow.com/users/5690248", "pm_score": 2, "selected": false, "text": "T obj; obj int char malloc calloc T obj {}; T obj; {} default std::initializer_list {} T obj T obj{}" }, { "answer_id": 74671318, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "Value initialization 0 int a {}; // value initialization\nstd::cout << a << std::endl;\n\nint b; // default initialization\nstd::cout << b << std::endl;\n struct S {\nS() {}\n};\n\nint main() {\nS s1 {}; // value initialization\nS s2; // default initialization - compile-time error\n\nreturn 0;\n}\n value initialization" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677599/" ]
74,671,173
<p>If my understanding is correct, the following declarations should both call the copy constructor of <code>T</code> which takes type of <code>x</code> as a parameter.</p> <pre><code>T t = x; T t(x); </code></pre> <p>But when I do the same for <code>std::unique_ptr&lt;int&gt;</code> I get an error with the first declaration, while the second compiles and does what is expected.</p> <pre><code>std::unique_ptr&lt;int&gt; x = new int(); std::unique_ptr&lt;int&gt; x (new int()); </code></pre> <p>Is there a difference in the two syntax for calling the copy constructor?</p>
[ { "answer_id": 74671197, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "std::unique_ptr<> explicit std::unique_ptr<int> x = std::unique_ptr<int>(new int());\n// or\nauto x = std::unique_ptr<int>(new int());\n// or make_unique()\n" }, { "answer_id": 74671210, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "std::unique_ptr::unique_ptr( pointer p ) =" }, { "answer_id": 74671243, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "std::unique_ptr T t = x; std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr T t(x); std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr make_unique std::unique_ptr<int> x = std::make_unique<int>();\nstd::unique_ptr<int> y(std::make_unique<int>());\n make_unique std::unique_ptr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2858773/" ]
74,671,192
<p>Say I have a list of files with mixed suffixes, e.g. .cpp and .c, and I want to make a list where each .cpp and each .c extension is changed to .o. I realize I could sequentially process my list multiple times, one for each extension of interest. But is there a way to use a variable substitution to do it in one step?</p>
[ { "answer_id": 74671197, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "std::unique_ptr<> explicit std::unique_ptr<int> x = std::unique_ptr<int>(new int());\n// or\nauto x = std::unique_ptr<int>(new int());\n// or make_unique()\n" }, { "answer_id": 74671210, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "std::unique_ptr::unique_ptr( pointer p ) =" }, { "answer_id": 74671243, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "std::unique_ptr T t = x; std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr T t(x); std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr make_unique std::unique_ptr<int> x = std::make_unique<int>();\nstd::unique_ptr<int> y(std::make_unique<int>());\n make_unique std::unique_ptr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087756/" ]
74,671,230
<p>I would like to know how do I display these values from an api that returns me an xml. I've looked in some places, but it's always one without the namespace and others with namespace... but mine has both and it always bugs and doesn't display the values..</p> <p>my xml:</p> <pre><code>&lt;QTableGridDataSourceForMobileOfDocumentWBuH9k12 xmlns=&quot;http://schemas.datacontract.org/2004/07/Sinfic.DataContracts&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt; &lt;TotalRows&gt;1&lt;/TotalRows&gt; &lt;Rows xmlns:a=&quot;http://schemas.datacontract.org/2004/07/Sinfic.DataContracts.Documents&quot;&gt; &lt;a:Document&gt; &lt;a:a&gt;6017&lt;/a:a&gt; &lt;a:aa&gt;135&lt;/a:aa&gt; &lt;a:ab&gt;-23.15749833&lt;/a:ab&gt; &lt;a:ac&gt;-45.79356167&lt;/a:ac&gt; &lt;a:ad&gt;6.80&lt;/a:ad&gt; &lt;a:ai&gt;0&lt;/a:ai&gt; &lt;a:aj&gt;Administrator&lt;/a:aj&gt; &lt;a:am&gt;32872&lt;/a:am&gt; &lt;a:an&gt;Leonardo Righi&lt;/a:an&gt; &lt;a:ao&gt;16470252&lt;/a:ao&gt; &lt;a:ap&gt;16470108&lt;/a:ap&gt; &lt;a:aq&gt; &lt;a:data&gt; &lt;a:key&gt; &lt;a:id&gt;d0180056-f7e6-4b13-8865-a963a9a131&lt;/a:id&gt; &lt;a:tag&gt;nomeTecnico&lt;/a:tag&gt; &lt;/a:key&gt; &lt;a:value&gt;Denis Rodrigues&lt;/a:value&gt; &lt;/a:data&gt; &lt;a:ar&gt; &lt;a:data&gt; &lt;a:key&gt; &lt;a:id&gt;d6052d01-92b3-45a5-9059-f401eddf0ef5&lt;/a:id&gt; &lt;a:tag&gt;ImageAnswer&lt;/a:tag&gt; &lt;/a:key&gt; &lt;a:value&gt;27422&lt;/a:value&gt; &lt;/a:data&gt; &lt;/a:ar&gt; &lt;a:b&gt;150&lt;/a:b&gt; &lt;a:bb&gt;Manutenção Automáticas&lt;/a:bb&gt; &lt;a:bc&gt;02 - CELULARES&lt;/a:bc&gt; &lt;a:bd&gt;Cancelado&lt;/a:bd&gt; &lt;a:bf&gt;09/03/2022 14:52&lt;/a:bf&gt; &lt;a:bg&gt;11/03/2022 15:00&lt;/a:bg&gt; &lt;a:bh&gt;Automaticas&lt;/a:bh&gt; &lt;a:bi&gt;5&lt;/a:bi&gt; &lt;a:bj&gt;09/03/2022 14:41&lt;/a:bj&gt; &lt;a:bk&gt;09/03/2022 14:52&lt;/a:bk&gt; &lt;a:bq&gt;LOGISTICA LTDA&lt;/a:bq&gt; &lt;a:br&gt;2&lt;/a:br&gt; &lt;a:bs&gt;2&lt;/a:bs&gt; &lt;a:bt&gt;false&lt;/a:bt&gt; &lt;a:bu&gt;MyDocs&lt;/a:bu&gt; &lt;a:bv&gt;# 1.4.17[14017]&lt;/a:bv&gt; &lt;a:by&gt;f1edqKgAgFWvOHGTmEFw42uggIDQt-K8pKPFaC6Em-Z7etzLOSr3Al6eCPndbg2&lt;/a:by&gt; &lt;a:cd&gt;656&lt;/a:cd&gt; &lt;a:ce&gt;13235&lt;/a:ce&gt; &lt;a:l&gt;DENIS &lt;/a:l&gt; &lt;a:o&gt;f8b521e8-e92f-478e-a883&lt;/a:o&gt; &lt;/a:Document&gt; &lt;/Rows&gt; &lt;/QTableGridDataSourceForMobileOfDocumentWBuH9k12&gt; </code></pre> <p>I tried this code, as close as I got:</p> <pre><code>&lt;?php $x = simplexml_load_file('teste.xml'); $campos = $x-&gt; children('a', true)-&gt; children('a', true); foreach($campos as $chave =&gt; $valor){ echo $chave.' : '. $valor . '&lt;br&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 74671197, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "std::unique_ptr<> explicit std::unique_ptr<int> x = std::unique_ptr<int>(new int());\n// or\nauto x = std::unique_ptr<int>(new int());\n// or make_unique()\n" }, { "answer_id": 74671210, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "std::unique_ptr::unique_ptr( pointer p ) =" }, { "answer_id": 74671243, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "std::unique_ptr T t = x; std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr T t(x); std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr make_unique std::unique_ptr<int> x = std::make_unique<int>();\nstd::unique_ptr<int> y(std::make_unique<int>());\n make_unique std::unique_ptr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15823070/" ]
74,671,244
<p>From,</p> <pre><code>jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + &quot;,&quot; + .DomainName' &lt;&lt; EOF { &quot;DistributionList&quot;: { &quot;Items&quot;: [ { &quot;Id&quot;: &quot;EG3MOA&quot;, &quot;Status&quot;: &quot;Deployed&quot;, &quot;LastModifiedTime&quot;: &quot;2022-12-03T19:32:35.007000+00:00&quot;, &quot;DomainName&quot;: &quot;a***.cloudfront.net&quot;, &quot;Aliases&quot;: { &quot;Quantity&quot;: 1, &quot;Items&quot;: [ &quot;a.domain.tld&quot;, &quot;b.domain.tld&quot; ] } }, { &quot;Id&quot;: &quot;EG3MOB&quot;, &quot;Status&quot;: &quot;Deployed&quot;, &quot;LastModifiedTime&quot;: &quot;2022-12-03T19:32:35.007000+00:00&quot;, &quot;DomainName&quot;: &quot;b***.cloudfront.net&quot;, &quot;Aliases&quot;: { &quot;Quantity&quot;: 1, &quot;Items&quot;: [ &quot;c.domain.tld&quot;, &quot;d.domain.tld&quot; ] } } ] } } EOF </code></pre> <p>It yields:</p> <pre><code>&quot;EG3MOA,a***.cloudfront.net&quot; &quot;EG3MOB,b***.cloudfront.net&quot; </code></pre> <p>How would I also get the `Alias Items, so that I have:</p> <pre><code>&quot;EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'&quot; &quot;EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'&quot; </code></pre>
[ { "answer_id": 74671197, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "std::unique_ptr<> explicit std::unique_ptr<int> x = std::unique_ptr<int>(new int());\n// or\nauto x = std::unique_ptr<int>(new int());\n// or make_unique()\n" }, { "answer_id": 74671210, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "std::unique_ptr::unique_ptr( pointer p ) =" }, { "answer_id": 74671243, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "std::unique_ptr T t = x; std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr T t(x); std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr make_unique std::unique_ptr<int> x = std::make_unique<int>();\nstd::unique_ptr<int> y(std::make_unique<int>());\n make_unique std::unique_ptr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477340/" ]
74,671,257
<p>I am using the <a href="https://platform.uno/" rel="nofollow noreferrer">Uno Platform</a> and trying to create a <a href="https://gallery.platform.uno/" rel="nofollow noreferrer">Material Card</a> through C#. I have been able to find a number of examples of a Card created in XAML but nothing in C#.</p> <p>My current code is below to create a Card and add it to a Grid. I know I need to do something with adding a HeaderContentTemplate and SubHeaderContentTemplate but I am sure exactly what needs to be done.</p> <pre><code>Card myCard = new Card(); myCard.HeaderContent = &quot;test&quot;; myCard.SubHeaderContent = &quot;test&quot;; Grid.SetRow(myCard, k); Grid.SetColumn(myCard, l); myGrid.Children.Add(myCard); </code></pre> <p>Any help would be greatly appreciated. Thank you.</p>
[ { "answer_id": 74671197, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "std::unique_ptr<> explicit std::unique_ptr<int> x = std::unique_ptr<int>(new int());\n// or\nauto x = std::unique_ptr<int>(new int());\n// or make_unique()\n" }, { "answer_id": 74671210, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "std::unique_ptr::unique_ptr( pointer p ) =" }, { "answer_id": 74671243, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "std::unique_ptr T t = x; std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr T t(x); std::unique_ptr std::unique_ptr std::unique_ptr std::unique_ptr make_unique std::unique_ptr<int> x = std::make_unique<int>();\nstd::unique_ptr<int> y(std::make_unique<int>());\n make_unique std::unique_ptr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677500/" ]
74,671,260
<p>I have a component that calls a method which in the background computes a heavy calculation with a map function (not fetching anything), and I'm looking to insert a callback function in there to update the DOM with the loading percentage of the computation with every iteration of the map function.</p> <p>Basically, I'm trying to update the DOM with the loadingPercentage variable in the following code. Console.log statement outputs the correct percentages.</p> <p>`</p> <pre><code> useEffect(() =&gt; { const frames: AnimationFrame[] = getAnimationFrames( (loadingPercentage: number) =&gt; { console.log(loadingPercentage); // Here's the part I'm trying to insert something to update the DOM } ); setFrames(frames.map((frame) =&gt; frame.analysis)); setBoards(frames.map((frame) =&gt; frame.board)); }, []); </code></pre> <p>`</p> <p>I'm trying to get the percentage on the DOM as follows:</p> <pre><code>&lt;div&gt;{loadingPercentage}&lt;/div&gt; //Not updating at all... </code></pre> <p>In case it could be useful, the heavy computation I mentioned in this case is <strong>getAnimationFrames()</strong> which is located in a non-react typescript file as such:</p> <pre><code>export const getAnimationFrames = ( loading?: Function, pgn: string = defaultPgn ) =&gt; { const history = getHistoryFromPgn(pgn); const totalMoves = history.length; let loadingPercentage = 0; let moveNo = 0; const animationFrames: AnimationFrame[] = history.map((move) =&gt; { const animationFrame = getAnimationFrame(move); moveNo++; loadingPercentage = (moveNo * 100) / totalMoves; if (loading) { **loading(loadingPercentage);** } return animationFrame; }); return animationFrames; }; </code></pre> <p>What I tried:</p> <ol> <li><p>Making a state variable like const [loadingPercentage, setLoadingPercentage] = useState(0) and add it as a dependency to the useEffect hook but the getAnimationFrames function must be called only once so that didn't make a lot of sense.</p> </li> <li><p>Removing the getAnimationFrames function, and instead of using a loop I tried to get useEffect to behave like a loop by adding getAnimationFrame in the useEffect function to push the frames to an array with each component load, with the loadingPercentage as a dependency of useEffect. This seemed like it almost worked but eventually it started giving too many renders error.</p> </li> <li><p>Tried const loadingPercentage = useRef(0);, and updated loadingPercentage.current with loadingPercentage value at every iteration. This did not update the DOM as expected.</p> </li> <li><p>Tried abandoning React all together and did document.getElementById('loadingDiv').innerText = loadingPercentage. Seems like this is very easy to do with Vanilla JS, but cannot get it to work in React.</p> </li> </ol> <p>Let me know if you have any ideas.</p> <p>Thank you!</p>
[ { "answer_id": 74671490, "author": "Enfield li", "author_id": 16648127, "author_profile": "https://Stackoverflow.com/users/16648127", "pm_score": 2, "selected": true, "text": "loadingPercentage setState getAnimationFrames type FrameState = { animationFrames: AnimationFrame[], loadingPercentage: number };\n\nconst [frames, setFrames] = useState<FrameState>({ animationFrames: [], loadingPercentage: 0 })\n\nuseEffect(() => {\n heavyComputation(frames, setFrames)\n}, []);\n\nfunction heavyComputation(frames, setFrames) {\n for (let index = 0; index < 100; index++) { \n if(100 % index) {\n setFrames({...frames, loadingPercentage: index}) \n } \n }\n}\n setState" }, { "answer_id": 74672379, "author": "keremduran", "author_id": 18808188, "author_profile": "https://Stackoverflow.com/users/18808188", "pm_score": 0, "selected": false, "text": " import { useState, useEffect } from 'react';\nimport { getAnimationFrame, getHistoryFromPgn } from './chess/chessApi';\nconst defaultPgn =\n '1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 15. Bc4 Nxc3 16. Bc5 Rfe8+ 17. Kf1 Be6 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ 20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1';\n\nconst history = getHistoryFromPgn(defaultPgn);\n\nexport default function App() {\n const [state, setState] = useState(0);\n\n useEffect(() => {\n heavyComputation();\n }, []);\n\n const sleep = (milliseconds: number) => {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n };\n\n async function heavyComputation() {\n for (let index = 0; index < history.length; index++) {\n getAnimationFrame(history[index]);\n await sleep(0);\n setState(index);\n }\n }\n\n return <div className='App'>{state}</div>;\n\n\nPutting an await sleep(0) between the loop ticks has worked out, from this point it will be easy to compute a loadingPercentage and update the DOM with it.\n\nThank you Enfield li for the answer!\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18808188/" ]
74,671,283
<p>Can someone help me to set stop loss = 100 pips to this strategy? I have no idea how to do it</p> <pre><code>//@version=5 strategy(&quot;MovingAvg2Line Cross&quot;, overlay=true) fastLength = input(9) slowLength = input(18) price = close mafast = ta.sma(price, fastLength) maslow = ta.sma(price, slowLength) if (ta.crossover(mafast, maslow)) strategy.entry(&quot;MA2CrossLE&quot;, strategy.long, comment=&quot;MA2CrossLE&quot;) if (ta.crossunder(mafast, maslow)) strategy.entry(&quot;MA2CrossSE&quot;, strategy.short, comment=&quot;MA2CrossSE&quot;) //plot(strategy.equity, title=&quot;equity&quot;, color=color.red, linewidth=2, style=plot.style_areabr) </code></pre> <p>If someone can write for me code of stop loss i would be grateful</p>
[ { "answer_id": 74671490, "author": "Enfield li", "author_id": 16648127, "author_profile": "https://Stackoverflow.com/users/16648127", "pm_score": 2, "selected": true, "text": "loadingPercentage setState getAnimationFrames type FrameState = { animationFrames: AnimationFrame[], loadingPercentage: number };\n\nconst [frames, setFrames] = useState<FrameState>({ animationFrames: [], loadingPercentage: 0 })\n\nuseEffect(() => {\n heavyComputation(frames, setFrames)\n}, []);\n\nfunction heavyComputation(frames, setFrames) {\n for (let index = 0; index < 100; index++) { \n if(100 % index) {\n setFrames({...frames, loadingPercentage: index}) \n } \n }\n}\n setState" }, { "answer_id": 74672379, "author": "keremduran", "author_id": 18808188, "author_profile": "https://Stackoverflow.com/users/18808188", "pm_score": 0, "selected": false, "text": " import { useState, useEffect } from 'react';\nimport { getAnimationFrame, getHistoryFromPgn } from './chess/chessApi';\nconst defaultPgn =\n '1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 15. Bc4 Nxc3 16. Bc5 Rfe8+ 17. Kf1 Be6 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ 20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1';\n\nconst history = getHistoryFromPgn(defaultPgn);\n\nexport default function App() {\n const [state, setState] = useState(0);\n\n useEffect(() => {\n heavyComputation();\n }, []);\n\n const sleep = (milliseconds: number) => {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n };\n\n async function heavyComputation() {\n for (let index = 0; index < history.length; index++) {\n getAnimationFrame(history[index]);\n await sleep(0);\n setState(index);\n }\n }\n\n return <div className='App'>{state}</div>;\n\n\nPutting an await sleep(0) between the loop ticks has worked out, from this point it will be easy to compute a loadingPercentage and update the DOM with it.\n\nThank you Enfield li for the answer!\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677656/" ]
74,671,293
<p>Suppose I have <code>ABC</code> in cell <code>A1</code> and <code>XaA</code> in cell B1. Taking into account upper and lower case I would like to recognize that <code>A</code> is indeed in common. How can I do this using Excel or Google Sheets function?</p> <p>Thank you</p> <p>I used <code>=INDEX(FLATTEN(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT(&quot;(.)&quot;, LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT(&quot;(.)&quot;, LEN(E1)))&lt;&gt;&quot;&quot;)), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT(&quot;(.)&quot;, LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT(&quot;(.)&quot;, LEN(E1)))&lt;&gt;&quot;&quot;))&lt;&gt;&quot;&quot;)&amp;&quot;&quot;&amp;TRANSPOSE(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT(&quot;(.)&quot;, LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT(&quot;(.)&quot;, LEN(E2)))&lt;&gt;&quot;&quot;)), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT(&quot;(.)&quot;, LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT(&quot;(.)&quot;, LEN(E2)))&lt;&gt;&quot;&quot;))&lt;&gt;&quot;&quot;))))</code> formula but clearly I am not moving in the right direction.</p>
[ { "answer_id": 74671490, "author": "Enfield li", "author_id": 16648127, "author_profile": "https://Stackoverflow.com/users/16648127", "pm_score": 2, "selected": true, "text": "loadingPercentage setState getAnimationFrames type FrameState = { animationFrames: AnimationFrame[], loadingPercentage: number };\n\nconst [frames, setFrames] = useState<FrameState>({ animationFrames: [], loadingPercentage: 0 })\n\nuseEffect(() => {\n heavyComputation(frames, setFrames)\n}, []);\n\nfunction heavyComputation(frames, setFrames) {\n for (let index = 0; index < 100; index++) { \n if(100 % index) {\n setFrames({...frames, loadingPercentage: index}) \n } \n }\n}\n setState" }, { "answer_id": 74672379, "author": "keremduran", "author_id": 18808188, "author_profile": "https://Stackoverflow.com/users/18808188", "pm_score": 0, "selected": false, "text": " import { useState, useEffect } from 'react';\nimport { getAnimationFrame, getHistoryFromPgn } from './chess/chessApi';\nconst defaultPgn =\n '1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 15. Bc4 Nxc3 16. Bc5 Rfe8+ 17. Kf1 Be6 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ 20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1';\n\nconst history = getHistoryFromPgn(defaultPgn);\n\nexport default function App() {\n const [state, setState] = useState(0);\n\n useEffect(() => {\n heavyComputation();\n }, []);\n\n const sleep = (milliseconds: number) => {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n };\n\n async function heavyComputation() {\n for (let index = 0; index < history.length; index++) {\n getAnimationFrame(history[index]);\n await sleep(0);\n setState(index);\n }\n }\n\n return <div className='App'>{state}</div>;\n\n\nPutting an await sleep(0) between the loop ticks has worked out, from this point it will be easy to compute a loadingPercentage and update the DOM with it.\n\nThank you Enfield li for the answer!\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16168456/" ]
74,671,304
<p>I'm new using the boost::multiprecision library and tried to use it combination with boost::math::interpolators::cardinal_cubic_b_spline however I can't compile the program.</p> <p>The example code is</p> <pre><code>#include &lt;boost/math/interpolators/cardinal_cubic_b_spline.hpp&gt; #include &lt;iostream&gt; #include &lt;boost/multiprecision/gmp.hpp&gt; using boost::multiprecision::mpf_float_50; int main() { std::vector&lt;mpf_float_50&gt; v(10); mpf_float_50 step(0.01); for (size_t i = 0; i &lt; v.size(); ++i) { v.at(i) = sin(i*step); } mpf_float_50 leftPoint(0.0); boost::math::interpolators::cardinal_cubic_b_spline&lt;mpf_float_50&gt; spline(v.begin(), v.end(), leftPoint, step); mpf_float_50 x(3.1); mpf_float_50 tmpVal = spline(x); std::cout &lt;&lt; tmpVal &lt;&lt; std::endl; return 0; } </code></pre> <p>When change the type of variables to boost::multiprecision::cpp_bin_float_50 the program is working. Also, boost::multiprecision::mpf_float_50 is working in all other examples I have tried.</p> <p>The error I get is:</p> <pre><code>/home/..../main.cpp:19:31: required from here /usr/include/boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp:50:10: error: conversion from ‘expression&lt;boost::multiprecision::detail::function,boost::multiprecision::detail::abs_funct&lt;boost::multiprecision::backends::gmp_float&lt;50&gt; &gt;,boost::multiprecision::detail::expression&lt;boost::multiprecision::detail::subtract_immediates, boost::multiprecision::number&lt;boost::multiprecision::backends::gmp_float&lt;50&gt; &gt;, long unsigned int, void, void&gt;,[...],[...]&gt;’ to non-scalar type ‘expression&lt;boost::multiprecision::detail::subtract_immediates,boost::multiprecision::number&lt;boost::multiprecision::backends::gmp_float&lt;50&gt; &gt;,long unsigned int,[...],[...]&gt;’ requested </code></pre> <p>The same error appeared for cpp_dec_float_50, mpfr_float_50 etc. I'm not sure what I'm doing wrong.</p>
[ { "answer_id": 74671446, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "cardinal_cubic_b_spline mpf_float_50 boost::multiprecision::gmp cpp_bin_float_50" }, { "answer_id": 74672155, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 3, "selected": true, "text": "number<> using F = boost::multiprecision::mpf_float_50;\n\nint main() {\n F a = 3, b = 2;\n F c = b - a;\n std::cout << \"a:\" << a << \", b:\" << b << \", c:\" << c << std::endl;\n\n b = abs(b - a);\n std::cout << \"a:\" << a << \", b:\" << b << \", c:\" << c << std::endl;\n}\n a:3, b:2, c:-1\na:3, b:1, c:-1\n number<> typeof(F{} - F{}) F namespace mp = boost::multiprecision;\nusing F = mp::mpf_float_50;\n\nint main() {\n F a = 3, b = 2;\n\n mp::detail::expression<mp::detail::subtract_immediates, F, F> //\n c = b - a;\n namespace mp = boost::multiprecision;\nusing F = mp::number<mp::gmp_float<50>, mp::et_off>;\n #include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n\nnamespace mp = boost::multiprecision;\nusing F = mp::number<mp::gmp_float<50>, mp::et_off>;\n\nint main() {\n std::vector<F> v(10);\n F step(0.01);\n\n for (size_t i = 0; i < v.size(); ++i) {\n v.at(i) = sin(i * step);\n }\n\n F leftPoint(0.0);\n boost::math::interpolators::cardinal_cubic_b_spline<F> spline(v.begin(), v.end(), leftPoint, step);\n\n F x(3.1);\n F tmpVal = spline(x);\n std::cout << tmpVal << std::endl;\n}\n 0.0449663\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677586/" ]
74,671,307
<p>I am looking for a harsher version of <code>[[nodiscard]]</code> that throws an fatal error instead of a warning when a return value is ignored. So for example:</p> <pre><code>[[harshnodiscard]] int getSize() { return 0; } </code></pre> <p>Any code that ignores the return value of <code>getSize</code> should not compile.</p> <p>Is there any functionality for this?</p>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19333949/" ]
74,671,338
<p>No errors are shown in the &quot;problems&quot; tab nor in the code itself. How do I get these errors to show up in the &quot;problems&quot; tab and in my code for easier debugging?</p> <p>Right now it says &quot;No problems have been detected in the workspace.&quot; When my code runs with errors in the terminal.</p> <p>I tried reinstalling and resetting my settings, no luck.</p> <p>error example (only shown in terminal):</p> <pre><code>Traceback (most recent call last): File &quot;redacted&quot;, line 29, in &lt;module&gt; main() File &quot;redacted&quot;, line 6, in main deal_cards(deck, numcards) File &quot;redacted&quot;, line 17, in deal_cards if number &gt; len(deck): TypeError: object of type 'NoneType' has no len() </code></pre>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18971086/" ]
74,671,339
<p>I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it</p> <pre><code> elif (original_collatz % 2) == 0: new_collatz = collatz/2 </code></pre> <p>anyone have an idea how to check</p> <p>i tried it with modulo but could figure out how it works, and my program just ignores this line, whole program: `</p> <pre><code>#collatz program import time collatz = 7 original_collatz = collatz new_collatz = collatz while True: if original_collatz % 2 == 1: new_collatz = (collatz * 3) + 1 elif (original_collatz % 2) == 0: new_collatz = collatz/2 collatz = new_collatz print(collatz) if collatz == 1: print('woo hoo') original_collatz += 1 time.sleep(1) </code></pre>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19499093/" ]
74,671,361
<p>In Rust Polars(might apply to python pandas as well) assigning values in a new column with a complex logic involving values of other columns can be achieved in two ways. The <a href="https://stackoverflow.com/questions/70968749/pandas-replace-equivalent-in-python-polars">default</a> way is using a nested <a href="https://docs.rs/polars/latest/polars/prelude/struct.When.html" rel="nofollow noreferrer">WhenThen</a> expression. Another way to achieve same thing is with LeftJoin. Naturally I would expect When Then to be much faster than Join, but it is not the case. In this example, When Then is <strong>6 times slower</strong> than Join. Is that actually expected? Am I using When Then wrong?</p> <p>In this example the goal is to assign weights/multipliers column based on three other columns: <em>country</em>, <em>city</em> and <em>bucket</em>.</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap; use polars::prelude::*; use rand::{distributions::Uniform, Rng}; // 0.6.5 pub fn bench() { // PREPARATION // This MAP is to be used for Left Join let mut weights = df![ &quot;country&quot;=&gt;vec![&quot;UK&quot;; 5], &quot;city&quot;=&gt;vec![&quot;London&quot;; 5], &quot;bucket&quot; =&gt; [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;], &quot;weights&quot; =&gt; [0.1, 0.2, 0.3, 0.4, 0.5] ].unwrap().lazy(); weights = weights.with_column(concat_lst([col(&quot;weights&quot;)]).alias(&quot;weihts&quot;)); // This MAP to be used in When.Then let weight_map = bucket_weight_map(&amp;[0.1, 0.2, 0.3, 0.4, 0.5], 1); // Generate the DataSet itself let mut rng = rand::thread_rng(); let range = Uniform::new(1, 5); let b: Vec&lt;String&gt; = (0..10_000_000).map(|_| rng.sample(&amp;range).to_string()).collect(); let rc = vec![&quot;UK&quot;; 10_000_000]; let rf = vec![&quot;London&quot;; 10_000_000]; let val = vec![1; 10_000_000]; let frame = df!( &quot;country&quot; =&gt; rc, &quot;city&quot; =&gt; rf, &quot;bucket&quot; =&gt; b, &quot;val&quot; =&gt; val, ).unwrap().lazy(); // Test with Left Join use std::time::Instant; let now = Instant::now(); let r = frame.clone() .join(weights, [col(&quot;country&quot;), col(&quot;city&quot;), col(&quot;bucket&quot;)], [col(&quot;country&quot;), col(&quot;city&quot;), col(&quot;bucket&quot;)], JoinType::Left) .collect().unwrap(); let elapsed = now.elapsed(); println!(&quot;Left Join took: {:.2?}&quot;, elapsed); // Test with nested When Then let now = Instant::now(); let r1 = frame.clone().with_column( when(col(&quot;country&quot;).eq(lit(&quot;UK&quot;))) .then( when(col(&quot;city&quot;).eq(lit(&quot;London&quot;))) .then(rf_rw_map(col(&quot;bucket&quot;),weight_map,NULL.lit())) .otherwise(NULL.lit()) ) .otherwise(NULL.lit()) ) .collect().unwrap(); let elapsed = now.elapsed(); println!(&quot;Chained When Then: {:.2?}&quot;, elapsed); // Check results are identical dbg!(r.tail(Some(10))); dbg!(r1.tail(Some(10))); } /// All this does is building a chained When().Then().Otherwise() fn rf_rw_map(col: Expr, map: HashMap&lt;String, Expr&gt;, other: Expr) -&gt; Expr { // buf is a placeholder let mut it = map.into_iter(); let (k, v) = it.next().unwrap(); //The map will have at least one value let mut buf = when(lit::&lt;bool&gt;(false)) // buffer WhenThen .then(lit::&lt;f64&gt;(0.).list()) // buffer WhenThen, needed to &quot;chain on to&quot; .when(col.clone().eq(lit(k))) .then(v); for (k, v) in it { buf = buf .when(col.clone().eq(lit(k))) .then(v); } buf.otherwise(other) } fn bucket_weight_map(arr: &amp;[f64], ntenors: u8) -&gt; HashMap&lt;String, Expr&gt; { let mut bucket_weights: HashMap&lt;String, Expr&gt; = HashMap::default(); for (i, n) in arr.iter().enumerate() { let j = i + 1; bucket_weights.insert( format![&quot;{j}&quot;], Series::from_vec(&quot;weight&quot;, vec![*n; ntenors as usize]) .lit() .list(), ); } bucket_weights } </code></pre> <p>The result is surprising to me: <code>Left Join took: 561.26ms</code> vs <code>Chained When Then: 3.22s</code></p> <p>Thoughts?</p> <h2>UPDATE</h2> <p>This does not make much difference. Nested WhenThen is still over 3s</p> <pre class="lang-rust prettyprint-override"><code>// Test with nested When Then let now = Instant::now(); let r1 = frame.clone().with_column( when(col(&quot;country&quot;).eq(lit(&quot;UK&quot;)).and(col(&quot;city&quot;).eq(lit(&quot;London&quot;)))) .then(rf_rw_map(col(&quot;bucket&quot;),weight_map,NULL.lit())) .otherwise(NULL.lit()) ) .collect().unwrap(); let elapsed = now.elapsed(); println!(&quot;Chained When Then: {:.2?}&quot;, elapsed); </code></pre>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15437999/" ]
74,671,365
<p>hello I need to maximaze or minimize a div in my html page using only javascript no jquery i wanna be able to do like this <a href="http://jsfiddle.net/miqdad/Qy6Sj/1/" rel="nofollow noreferrer">http://jsfiddle.net/miqdad/Qy6Sj/1/</a></p> <pre><code>$(&quot;#button&quot;).click(function(){ if($(this).html() == &quot;-&quot;){ $(this).html(&quot;+&quot;); } else{ $(this).html(&quot;-&quot;); } $(&quot;#box&quot;).slideToggle(); }); </code></pre> <p>this is exactly how i want it to be but no jquery</p> <p>but with no jquery only javascript, can someone please help me, I googled this everywhere and couldnt find the answer</p>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20608344/" ]
74,671,373
<p>am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex.</p> <pre><code>ABCD EFG HIJK LMNOP </code></pre> <p>then they would be appended into the same array until it reaches a blank line at which point it stops and starts appending the next number of continuous arrays to a different array.</p> <p>In my head a for loop is the way to go as i have the number of lines but i am just not sure how to check if a line has ANY TYPE of text or not (Not looking for any substrings just checking if the line itself contains anything).</p>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12029214/" ]
74,671,374
<p>I have a script block</p> <pre><code>$test = { param( $path ) other stuff here...} </code></pre> <p>I assume I need to use <code>Invoke-Command -ScriptBlock $test</code> but how do I pass what the $path param should be ?</p>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/800592/" ]
74,671,375
<p>I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working.</p> <p>I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to fix the errors, nothing really happens, it stays the same. I expect the search_error.html page to appear when the user inputs a product name that is not in the database. Though I keep getting for example, when I type &quot;hello,&quot; the page appears with &quot;Search results for hello.&quot; But it should result the search_error.html page. I also tried currently a else clause in my views.py, but it shows the same thing. I think my else clause isn't working and I don't know why.</p> <p>My views.py:</p> <pre><code>def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html') def search_error(request): return render(request, 'epharmacyweb/search_error.html') </code></pre> <p>My urls.py under URLPatterns:</p> <pre><code>path('search/', views.search, name='search'), path('search_error/', views.search_error, name='search_error'), </code></pre> <p>My search.html page:</p> <pre><code>{% if searched %} &lt;div class=&quot;pb-3 h3&quot;&gt;Search Results for {{ searched }}&lt;/div&gt; &lt;div class=&quot;row row-cols-1 row-cols-sm-2 row-cols-md-5 g-3&quot;&gt; {% for product in products %} &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;card shadow-sm&quot;&gt; &lt;img class=&quot;img-fluid&quot; alt=&quot;Responsive image&quot; src=&quot;{{ product.image.url }}&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;p class=&quot;card-text&quot;&gt; &lt;a class=&quot;text-dark text-decoration-none&quot; href=&quot;{{ product.get_absolute_url }}&quot;&gt;{{ product.title }}&lt;/a&gt; &lt;/p&gt; &lt;div class=&quot;d-flex justify-content-between align-items-center&quot;&gt; &lt;small class=&quot;text-muted&quot;&gt;&lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; &lt;br&gt;&lt;/br&gt; {% else %} &lt;h1&gt;You haven't searched anything yet...&lt;/h1&gt; {% endif %} </code></pre>
[ { "answer_id": 74671319, "author": "Kan Jang", "author_id": 20677565, "author_profile": "https://Stackoverflow.com/users/20677565", "pm_score": -1, "selected": false, "text": " [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n" }, { "answer_id": 74671423, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "[[nodiscard]] static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n getSize() static_assert [[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n if (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461410/" ]
74,671,391
<p>how do I double the object side by side?</p> <pre><code>print(&quot; *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****&quot; *2) </code></pre> <p>this code puts the objects one below another, how do i do that it prints it besides?</p>
[ { "answer_id": 74671422, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": -1, "selected": false, "text": "obj = \" *\\n * \\n * \\n * \\n ***\\n * *\\n * *\\n *****\"\n\nprint(\"\\n\".join([obj, obj]))\n obj = \" *\\n * \\n * \\n * \\n ***\\n * *\\n * *\\n *****\"\n\nprint(obj * 2, sep=\"\")\n" }, { "answer_id": 74671526, "author": "nokla", "author_id": 20258214, "author_profile": "https://Stackoverflow.com/users/20258214", "pm_score": 2, "selected": false, "text": "obj = \" *\\n * *\\n * *\\n * *\\n*** ***\\n * *\\n * *\\n *****\"\n\nlines = obj.split('\\n')\nspace = len(max(lines, key=len)) + 3\n\nfor line in lines:\n print(line + \" \"* (space - len(line)) + line)\n" }, { "answer_id": 74671538, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 0, "selected": false, "text": "arrow = \" *\\n * *\\n * *\\n * *\\n*** ***\\n * *\\n * *\\n *****\"\n \narrow_lines = arrow.split(\"\\n\")\ndouble_arrow_lines = [line +\" \"*(15-len(line)) +line for line in arrow_lines]\ndouble_arrow = \"\\n\".join(double_arrow_lines)\n \nprint(double_arrow)\n" }, { "answer_id": 74671553, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 1, "selected": false, "text": "# using dots to indicate spaces clearly\ns = '''\\\n....*.....\n...*.*....\n..*...*...\n.*.....*..\n***...***.\n..*...*...\n..*...*...\n..*****...\n'''.replace('.',' ')\n\n# double each line\nfor line in s.splitlines():\n print(line * 2)\n * * \n * * * * \n * * * * \n * * * * \n*** *** *** *** \n * * * * \n * * * * \n ***** ***** \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13125495/" ]