qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,673,489
<p>I am trying to deploy my react application on netlify. It is working fine on my desktop and even <code>npm run build</code> is properly working. The material ui packages that I am using are also working fine on my desktop but when I am deploying on netlify the build fails. This is the error log</p> <pre><code>12:16:02 PM: No npm workspaces detected 12:16:02 PM: Started restoring cached node modules 12:16:02 PM: Finished restoring cached node modules 12:16:02 PM: Installing NPM modules using NPM version 8.19.2 12:16:04 PM: npm ERR! code ERESOLVE 12:16:04 PM: npm ERR! ERESOLVE could not resolve 12:16:04 PM: npm ERR! 12:16:04 PM: Creating deploy upload records 12:16:04 PM: npm ERR! While resolving: @material-ui/core@4.12.4 12:16:04 PM: npm ERR! Found: react@18.2.0 12:16:04 PM: npm ERR! node_modules/react 12:16:04 PM: npm ERR! react@&quot;^18.2.0&quot; from the root project 12:16:04 PM: npm ERR! peer react@&quot;&gt;=16.8.0&quot; from @emotion/react@11.10.5 12:16:04 PM: Failed during stage 'building site': Build script returned non-zero exit code: 1 (https://ntl.fyi/exit-code-1) 12:16:04 PM: npm ERR! node_modules/@emotion/react 12:16:04 PM: npm ERR! @emotion/react@&quot;^11.10.5&quot; from the root project 12:16:04 PM: npm ERR! peer @emotion/react@&quot;^11.0.0-rc.0&quot; from @emotion/styled@11.10.5 12:16:04 PM: npm ERR! node_modules/@emotion/styled 12:16:04 PM: npm ERR! @emotion/styled@&quot;^11.10.5&quot; from the root project 12:16:04 PM: npm ERR! 3 more (@mui/material, @mui/styled-engine, @mui/system) 12:16:04 PM: npm ERR! 3 more (@mui/material, @mui/styled-engine, @mui/system) 12:16:04 PM: npm ERR! 16 more (@emotion/styled, ...) 12:16:04 PM: npm ERR! 12:16:04 PM: npm ERR! Could not resolve dependency: 12:16:04 PM: npm ERR! peer react@&quot;^16.8.0 || ^17.0.0&quot; from @material-ui/core@4.12.4 12:16:04 PM: npm ERR! node_modules/@material-ui/core 12:16:04 PM: npm ERR! @material-ui/core@&quot;^4.12.4&quot; from the root project 12:16:04 PM: npm ERR! 12:16:04 PM: npm ERR! Conflicting peer dependency: react@17.0.2 12:16:04 PM: npm ERR! node_modules/react 12:16:04 PM: npm ERR! peer react@&quot;^16.8.0 || ^17.0.0&quot; from @material-ui/core@4.12.4 12:16:04 PM: npm ERR! node_modules/@material-ui/core 12:16:04 PM: npm ERR! @material-ui/core@&quot;^4.12.4&quot; from the root project 12:16:04 PM: npm ERR! 12:16:04 PM: npm ERR! Fix the upstream dependency conflict, or retry 12:16:04 PM: npm ERR! this command with --force, or --legacy-peer-deps 12:16:04 PM: npm ERR! to accept an incorrect (and potentially broken) dependency resolution. 12:16:04 PM: npm ERR! 12:16:04 PM: npm ERR! See /opt/buildhome/.npm/eresolve-report.txt for a full report. 12:16:04 PM: npm ERR! A complete log of this run can be found in: 12:16:04 PM: npm ERR! /opt/buildhome/.npm/_logs/2022-12-04T06_46_03_020Z-debug-0.log 12:16:04 PM: Error during NPM install 12:16:04 PM: Build was terminated: Build script returned non-zero exit code: 1 12:16:04 PM: Failing build: Failed to build site 12:16:04 PM: Finished processing build request in 5.438038347s``` </code></pre>
[ { "answer_id": 74673497, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "switch while (true) {\n String userInput = scan.nextLine();\n\n switch(userInput) {\n case \".help\":\n // print list of commands\n break;\n\n case \".ping\":\n // print pong\n break;\n\n default:\n // print error message for unknown command\n }\n}\n" }, { "answer_id": 74673549, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 0, "selected": false, "text": "while (true) {\n String userInput = scan.nextLine();\n\n if (userInput.equals(\".help\")) {\n // print list of commands\n } else if (userInput.equals(\".ping\")) {\n // print pong\n } else if (userInput.startsWith(\".\")) {\n System.out.println(\"Invalid command. Type .help for a list of commands.\");\n }\n}\n\n" }, { "answer_id": 74673744, "author": "wvullhorst", "author_id": 3383848, "author_profile": "https://Stackoverflow.com/users/3383848", "pm_score": 0, "selected": false, "text": " while (true) {\n String userInput = scan.nextLine();\n if (userInput.equals(\".help\")) {\n //print list of commands\n } else if (userInput.equals(\".ping\")) {\n //print pong\n } else if(userInput.startsWith(\".\")) {\n // applies if userInput starts with \".\" but is not .help or .ping\n }\n else {\n // applies if userInput does not start with a \".\"\n }\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16666888/" ]
74,673,492
<p>This here changes all the squares to pink. <a href="https://jsfiddle.net/7cye4hfu/1/" rel="nofollow noreferrer">https://jsfiddle.net/7cye4hfu/1/</a></p> <p>If I wanted to change one of the pink squares to a different color, how would I do that?</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>.channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; background-color: pink; } .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; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red { background: red; border-radius: 4px; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; }</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 box-color-red"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow"&gt;&lt;/div&gt; &lt;div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green"&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="https://via.placeholder.com/465x465" 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="https://via.placeholder.com/465x465" 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="https://via.placeholder.com/465x465" 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="https://via.placeholder.com/465x465" class="responsive-image-component"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74673497, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "switch while (true) {\n String userInput = scan.nextLine();\n\n switch(userInput) {\n case \".help\":\n // print list of commands\n break;\n\n case \".ping\":\n // print pong\n break;\n\n default:\n // print error message for unknown command\n }\n}\n" }, { "answer_id": 74673549, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 0, "selected": false, "text": "while (true) {\n String userInput = scan.nextLine();\n\n if (userInput.equals(\".help\")) {\n // print list of commands\n } else if (userInput.equals(\".ping\")) {\n // print pong\n } else if (userInput.startsWith(\".\")) {\n System.out.println(\"Invalid command. Type .help for a list of commands.\");\n }\n}\n\n" }, { "answer_id": 74673744, "author": "wvullhorst", "author_id": 3383848, "author_profile": "https://Stackoverflow.com/users/3383848", "pm_score": 0, "selected": false, "text": " while (true) {\n String userInput = scan.nextLine();\n if (userInput.equals(\".help\")) {\n //print list of commands\n } else if (userInput.equals(\".ping\")) {\n //print pong\n } else if(userInput.startsWith(\".\")) {\n // applies if userInput starts with \".\" but is not .help or .ping\n }\n else {\n // applies if userInput does not start with a \".\"\n }\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20658906/" ]
74,673,518
<p>I can't able to use flexWrap property inside the ScrollView container.</p> <p>My code looks like this</p> <pre><code>function Home({ navigation }) { return ( &lt;View style={styles.container}&gt; &lt;ScrollView style={styles.scrollContainer}&gt; &lt;LayoutButton navigation={navigation} title={&quot;go to setting&quot;} path=&quot;Setting&quot; /&gt; &lt;LayoutButton navigation={navigation} title={&quot;go to setting&quot;} path=&quot;Setting&quot; /&gt; &lt;LayoutButton navigation={navigation} title={&quot;go to setting&quot;} path=&quot;Setting&quot; /&gt; &lt;LayoutButton navigation={navigation} title={&quot;go to setting&quot;} path=&quot;Setting&quot; /&gt; &lt;/ScrollView&gt; &lt;StatusBar style=&quot;auto&quot; /&gt; &lt;/View&gt; ); } </code></pre> <p>and styles for this is</p> <pre><code>const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: &quot;#fff&quot;, alignItems: &quot;center&quot;, justifyContent: &quot;center&quot;, flexWrap: &quot;wrap&quot;, }, scrollContainer: { backgroundColor: &quot;#B7C3F3&quot;, width: &quot;100%&quot;, flexWrap: &quot;wrap&quot;, }, }); </code></pre> <p>I don't know whether the flex works under the ScrollView or not. I am new to the native please help me with this problem and thanks in advance</p>
[ { "answer_id": 74673545, "author": "Dorian", "author_id": 20642451, "author_profile": "https://Stackoverflow.com/users/20642451", "pm_score": 0, "selected": false, "text": "flex: 1" }, { "answer_id": 74673590, "author": "O2K", "author_id": 13957052, "author_profile": "https://Stackoverflow.com/users/13957052", "pm_score": 1, "selected": false, "text": "const styles = StyleSheet.create({\ncontainer: {\nflex: 1,\nbackgroundColor: \"#fff\",\nalignItems: \"center\",\njustifyContent: \"center\",\nflexWrap: \"wrap\",\n},\nscrollContainer: {\nbackgroundColor: \"#B7C3F3\",\nwidth: \"100%\",\nflexWrap: \"wrap\",\nheight: \"100%\", // Add a height property with a fixed value\n},\n});\n" }, { "answer_id": 74673623, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 2, "selected": true, "text": "function Home({ navigation }) {\n return (\n <View style={styles.container}>\n <ScrollView style={styles.scrollContainer}>\n <View style={styles.wrapContainer}>\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n </View>\n </ScrollView>\n <StatusBar style=\"auto\" />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#fff\",\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n scrollContainer: {\n backgroundColor: \"#B7C3F3\",\n width: \"100%\",\n },\n wrapContainer: {\n flexWrap: \"wrap\",\n },\n});\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15717417/" ]
74,673,537
<p>I have a master-detail page in blazor wasm: a left panel with a list of items, and a right panel with the selected item.</p> <p>An example (ascii generated <a href="https://asciiflow.com/#/share/eJyrVspLzE1VssorzcnRUcpJrEwtUrJSqo5RqohRsrI0M9GJUaoEsowsDIGsktSKEiAnRkkBAnwdg0NcgxRwABfXEEdPn5iYvEdT9gxdBHG%2FQmZJaq6CIYr%2FQMJEAoQ52CVpZA7Y0Ub4zKEQkezuR9Mmko%2FIsw8SCLS1g95%2Boq99dE4jkGRrjC5JujnYJQfMnIEJRxOK3Y1DcsDMGboI6H4gQvNXRklJQbGVvn55ebleakVibkFOql5yfq4%2BKPb0jWKUapVqAUgyQu8%3D" rel="nofollow noreferrer">here</a>), with item 2 selected:</p> <pre><code> MASTER DETAIL +--------------------+----------------------------------------+ | item 1 | | | | | | | item 2 | +--------------------+ | |░░░░░░░░░░░░░░░░░░░░| | |░item 2░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | +--------------------+ | | item 3 | | | | | | | | +--------------------+ | | item 4 | | | | | | | | +--------------------+----------------------------------------+ https://www.example.com/items/2 </code></pre> <p>URLs:</p> <ul> <li><code>/items</code> for page showing items without a selection</li> <li><code>/items/2</code> for page showing items with item 2 selected</li> </ul> <p>I managed to do all that, using this approach:</p> <ul> <li><code>MyLayout.razor</code> has a <code>&lt;Master /&gt;</code> component (left), and a <code>&lt;Detail Id=_selectedId /&gt;</code> component (right)</li> <li>When an item is clicked in the master component (left), it raises an event with the <code>Id</code></li> <li>The layout handles that event, and passes the id to the detail component (right)</li> <li>The detail component (right) shows the new item</li> </ul> <p>I also want the browser's location updated from <code>/items</code> to <code>/items/2</code>, so I used: <code>NavigationManager.NavigateTo(&quot;/items/&quot; + id)</code>. <strong>But that reloads all components</strong>.</p> <p>Workarounds:</p> <ul> <li>I haven't found a way to update the browser location without reloading the page (though I could do that in javascript). Even if that were possible, I'm not sure that's a good way to do it.</li> <li>I could use a query string parameter instead, <code>/items?id=10</code>, then the <code>NavigationManager</code> would (I think) avoid the rerendering - but I can't use this approach, it must be part of the URI.</li> </ul> <p>What is the recommended way to handle master-detail navigation in blazor?</p>
[ { "answer_id": 74673545, "author": "Dorian", "author_id": 20642451, "author_profile": "https://Stackoverflow.com/users/20642451", "pm_score": 0, "selected": false, "text": "flex: 1" }, { "answer_id": 74673590, "author": "O2K", "author_id": 13957052, "author_profile": "https://Stackoverflow.com/users/13957052", "pm_score": 1, "selected": false, "text": "const styles = StyleSheet.create({\ncontainer: {\nflex: 1,\nbackgroundColor: \"#fff\",\nalignItems: \"center\",\njustifyContent: \"center\",\nflexWrap: \"wrap\",\n},\nscrollContainer: {\nbackgroundColor: \"#B7C3F3\",\nwidth: \"100%\",\nflexWrap: \"wrap\",\nheight: \"100%\", // Add a height property with a fixed value\n},\n});\n" }, { "answer_id": 74673623, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 2, "selected": true, "text": "function Home({ navigation }) {\n return (\n <View style={styles.container}>\n <ScrollView style={styles.scrollContainer}>\n <View style={styles.wrapContainer}>\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n </View>\n </ScrollView>\n <StatusBar style=\"auto\" />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#fff\",\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n scrollContainer: {\n backgroundColor: \"#B7C3F3\",\n width: \"100%\",\n },\n wrapContainer: {\n flexWrap: \"wrap\",\n },\n});\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9971404/" ]
74,673,542
<p>this is the code I have so far</p> <pre><code>public class WindowHelpGui extends JFrame{ JScrollPane scroll; //constructor public WindowHelpGui(){ //add window title super(&quot;Help&quot;); //set window layout setLayout(null); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.setBounds(10, 10, 750, 550); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(); panel1.add(new JTextArea(&quot;\nDRAFT TEXT 101 \ncodnvfdinofndovndofinvinfdivnifdnvidfnviofnivnidfnviofdnvindfinv ivondfviondfiovndfionvifdnvionivfdninfdinfivnidfovniofnviofnvifdnv fndiovnf\nh\ne\nl\nl\no\n\nf\nr\no\nm\n\nt\nh\ne\n\no\nt\nh&quot;+ &quot;e\nr\n\ns\ni\nd\ne\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n nHello&quot;)); panel2.add(new JTextArea(&quot;panel2 working&quot;)); panel3.add(new JTextArea(&quot;panel3 working&quot;)); JScrollPane scroll = new JScrollPane(panel1, JScrollPane. HORIZONTAL_SCROLLBAR_NEVER, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDE add(scroll, panel1); tabbedPane.add(&quot;How to play&quot;, panel1); tabbedPane.add(&quot;Seeds&quot;, panel2); tabbedPane.add(&quot;Tools&quot;, panel3); //scroll = new Jscro this.add(tabbedPane); //set size of window setSize(800,600); //set visibility setVisible(true); //set resizable setResizable(false); //set default close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } </code></pre> <p>when I run this I dont see any window popping up. Can someone help me please?</p> <p>I have tried also tried using add(scroll, tabbedPane) but it just adds a new tab on my window.</p>
[ { "answer_id": 74673545, "author": "Dorian", "author_id": 20642451, "author_profile": "https://Stackoverflow.com/users/20642451", "pm_score": 0, "selected": false, "text": "flex: 1" }, { "answer_id": 74673590, "author": "O2K", "author_id": 13957052, "author_profile": "https://Stackoverflow.com/users/13957052", "pm_score": 1, "selected": false, "text": "const styles = StyleSheet.create({\ncontainer: {\nflex: 1,\nbackgroundColor: \"#fff\",\nalignItems: \"center\",\njustifyContent: \"center\",\nflexWrap: \"wrap\",\n},\nscrollContainer: {\nbackgroundColor: \"#B7C3F3\",\nwidth: \"100%\",\nflexWrap: \"wrap\",\nheight: \"100%\", // Add a height property with a fixed value\n},\n});\n" }, { "answer_id": 74673623, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 2, "selected": true, "text": "function Home({ navigation }) {\n return (\n <View style={styles.container}>\n <ScrollView style={styles.scrollContainer}>\n <View style={styles.wrapContainer}>\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n <LayoutButton\n navigation={navigation}\n title={\"go to setting\"}\n path=\"Setting\"\n />\n </View>\n </ScrollView>\n <StatusBar style=\"auto\" />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#fff\",\n alignItems: \"center\",\n justifyContent: \"center\",\n },\n scrollContainer: {\n backgroundColor: \"#B7C3F3\",\n width: \"100%\",\n },\n wrapContainer: {\n flexWrap: \"wrap\",\n },\n});\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20679621/" ]
74,673,568
<p>I am learning the backend in node. I am trying to execute the following piece of code `</p> <pre><code>const axios= require('axios') async function getData(){ const resp = await axios.get('https://jsonplaceholder.typicode.com/todos/1') console.log('hello',resp.data) } getData() </code></pre> <p>I am getting output like this: <a href="https://i.stack.imgur.com/0V1fG.png" rel="nofollow noreferrer">My output</a></p> <p>The expected output is: <a href="https://i.stack.imgur.com/lQDpE.png" rel="nofollow noreferrer">expected output</a></p> <p>I tried running code with <code>node index.js</code> and with extension <code>code runner</code>. The output is the same, even on replit I am getting the same result. Can someone explain, what am i doing wrong?</p>
[ { "answer_id": 74673668, "author": "Eduardo Procópio Gomez", "author_id": 10827693, "author_profile": "https://Stackoverflow.com/users/10827693", "pm_score": 1, "selected": false, "text": "br Accept-Encoding deflate await axios.get('https://jsonplaceholder.typicode.com/todos/1', {\n headers: {\n 'Accept-Encoding': 'deflate'\n }\n})\n" }, { "answer_id": 74677702, "author": "Jonathan", "author_id": 20460317, "author_profile": "https://Stackoverflow.com/users/20460317", "pm_score": 0, "selected": false, "text": "const resp = await axios.get('https://jsonplaceholder.typicode.com/todos/1', {\n 'accept-encoding': 'gzip, deflate'\n});\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11964388/" ]
74,673,571
<p>I have a list of integers like this</p> <pre><code>numbers = [1, 5, 7, 19, 22, 55] </code></pre> <p>I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as <code>(1,5), (5,7), (7,19)</code> and so on.</p> <p>Kindly suggest.</p> <p>I have tried using for loops. Didn't get expected output.</p>
[ { "answer_id": 74673586, "author": "Lexpj", "author_id": 10229386, "author_profile": "https://Stackoverflow.com/users/10229386", "pm_score": 0, "selected": false, "text": "lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)]\n" }, { "answer_id": 74673595, "author": "Iain Shelvington", "author_id": 548562, "author_profile": "https://Stackoverflow.com/users/548562", "pm_score": 3, "selected": true, "text": "from itertools import pairwise\n\nnumbers = [1, 5, 7, 19, 22, 55]\nlist(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10117185/" ]
74,673,631
<p>I'm creating an app with firebase as a database. After sending data to firebase, app screen should pop out for that I had bloclistener on the screen but after sending the data to firestore database, nothing is happening, flow is stopped after coming to loaded state in bloc file why? check my code so that you will know. I can see my data in firebase but it is not popping out because flow is not coming to listener.</p> <pre><code> state: class SampletestInitial extends SampletestState { @override List&lt;Object&gt; get props =&gt; []; } class SampletestLoaded extends SampletestState { SampletestLoaded(); @override List&lt;Object&gt; get props =&gt; []; } class SampletestError extends SampletestState { final error; SampletestError({required this.error}); @override List&lt;Object&gt; get props =&gt; [error]; } bloc: class SampletestBloc extends Bloc&lt;SampletestEvent, SampletestState&gt; { SampletestBloc() : super(SampletestInitial()) { on&lt;SampletestPostData&gt;((event, emit) async { emit(SampletestInitial()); try { await Repo().sampleTesting(event.des); emit(SampletestLoaded()); } catch (e) { emit(SampletestError(error: e.toString())); print(e); } }); } } Repo: ---- Firebase post data Future&lt;void&gt; sampleTesting(String des) async { final docTicket = FirebaseFirestore.instance.collection('sample').doc(); final json = {'Same': des}; await docTicket.set(json); } TicketScreen: //After clicking the button --- BlocProvider&lt;SampletestBloc&gt;.value( value: BlocProvider.of&lt;SampletestBloc&gt;(context, listen: false) ..add(SampletestPostData(description.text)), child: BlocListener&lt;SampletestBloc, SampletestState&gt;( listener: (context, state) { if (state is SampletestLoaded) { Navigator.pop(context); print(&quot;Popped out&quot;); } }, ), ); </code></pre>
[ { "answer_id": 74673586, "author": "Lexpj", "author_id": 10229386, "author_profile": "https://Stackoverflow.com/users/10229386", "pm_score": 0, "selected": false, "text": "lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)]\n" }, { "answer_id": 74673595, "author": "Iain Shelvington", "author_id": 548562, "author_profile": "https://Stackoverflow.com/users/548562", "pm_score": 3, "selected": true, "text": "from itertools import pairwise\n\nnumbers = [1, 5, 7, 19, 22, 55]\nlist(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14668121/" ]
74,673,662
<p>I have two programs. 1:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main () { do { cout&lt;&lt;&quot;Hello world&quot;; char yn='y'; } while (yn=='y' || yn=='Y'); return 0; } </code></pre> <p>2:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main () { char yn='y'; do { cout&lt;&lt;&quot;Hello world&quot;; } while (yn=='y' || yn=='Y'); return 0; } </code></pre> <p>First program is showing error like this:</p> <pre class="lang-none prettyprint-override"><code>comparison between pointer and integer ('double (*)(int, double)' and 'char') } while (yn=='y' || yn=='Y'); </code></pre> <p>I think both programs are same but still first program is showing error.</p>
[ { "answer_id": 74673688, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 2, "selected": false, "text": "yn int main () {\n do\n {\n cout<<\"Hello world\";\n char yn='y';\n // scope of yn variable stops here\n }\n while (yn=='y' || yn=='Y'); // so yn variable not in scope here\n return 0;\n}\n yn while (yn=='y' || yn=='Y'); yn yn yesno" }, { "answer_id": 74673905, "author": "Deepthi Tabitha Bennet", "author_id": 17112163, "author_profile": "https://Stackoverflow.com/users/17112163", "pm_score": 1, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\nint main () {\n\n do {\n\n cout<<\"Hello world\"; \n char yn='y';\n\n } while (yn=='y' || yn=='Y');\n return 0;\n}\n char yn='y' yn while (yn=='y' || yn=='Y') yn #include <iostream>\nusing namespace std;\n\nint main () {\n\n char yn='y';\n\n do {\n\n cout<<\"Hello world\"; \n\n } while (yn=='y' || yn=='Y');\n return 0;\n}\n char yn='y' main() yn main()" }, { "answer_id": 74673934, "author": "Clifford", "author_id": 168986, "author_profile": "https://Stackoverflow.com/users/168986", "pm_score": 2, "selected": true, "text": "{...} while yn <cmath> <iostream> using namespace std; std::cout using namespace std::cout ;\n std:: using yn while yn() std -ansi" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630256/" ]
74,673,689
<p>I have a dataframe that looks like that:</p> <pre><code> col1 0 10 1 5 2 8 3 12 4 13 5 6 6 9 7 11 8 10 9 3 10 21 11 18 12 14 13 16 14 30 15 45 16 31 17 40 18 38 </code></pre> <p>For each cell in 'col1' I calculate a range of values:</p> <pre><code>df['df_min'] = df.col1 - df.col1 * 0.2 df['df_max'] = df.col1 + df.col1 * 0.2 </code></pre> <p>For each cell there's a range, I would like to count how many cells in 'col1' in the past xx cells (3 in this example) are within that range, but without a loop as it takes a very long time with my actual model.</p> <p>I'm trying to achieve this result:</p> <pre><code> col1 df_min df_max counter 0 10 8.0 12.0 -1 1 5 4.0 6.0 -1 2 8 6.4 9.6 -1 3 12 9.6 14.4 1 4 13 10.4 15.6 1 5 6 4.8 7.2 0 6 9 7.2 10.8 0 7 11 8.8 13.2 2 8 10 8.0 12.0 2 9 3 2.4 3.6 0 10 21 16.8 25.2 0 11 18 14.4 21.6 1 12 14 11.2 16.8 0 13 16 12.8 19.2 2 14 30 24.0 36.0 0 15 45 36.0 54.0 0 16 31 24.8 37.2 1 17 40 32.0 48.0 1 18 38 30.4 45.6 3 </code></pre> <p>Here's the (messy) code that I could come up with, but I'd really like a faster solution, if possible. Any help would be gladly appreciated.</p> <pre><code>df = pd.DataFrame({&quot;col1&quot;:[10, 5, 8, 12, 13, 6, 9, 11, 10, 3, 21, 18, 14, 16, 30, 45, 31, 40, 38]}) back = 3 # numbers of cells to check back df['df_min'] = df.col1 - df.col1 * 0.2 df['df_max'] = df.col1 + df.col1 * 0.2 l = [] for window in df.col1.rolling(window=back+1, center=False, closed='right'): if window.empty: pass else: a = window.iloc[-1] range_min = a - a * 0.2 range_max = a + a * 0.2 c = 0 if len(window) == back+1: for b in window: if (b &gt;= range_min and b &lt;= range_max): c += 1 c = c-1 # substract 1 because window includes the tested value which is always true l.append(c) df1 = pd.DataFrame(l, columns=['counter']) df = df.join(df1) print(df) </code></pre>
[ { "answer_id": 74674318, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "df['df_min'] = df.col1 - df.col1 * 0.2\ndf['df_max'] = df.col1 + df.col1 * 0.2\nn = 3\ns = pd.Series(dtype='float')\nfor i in range(0, n):\n s1 = df.col1.shift(i+1).ge(df['df_min']) & df.col1.shift(i+1).le(df['df_max'])\n s = s.add(s1, fill_value=0)\ns[:n] = -1\ndf['counter'] = s\n df col1 df_min df_max counter\n0 10 8.0 12.0 -1.0\n1 5 4.0 6.0 -1.0\n2 8 6.4 9.6 -1.0\n3 12 9.6 14.4 1.0\n4 13 10.4 15.6 1.0\n5 6 4.8 7.2 0.0\n6 9 7.2 10.8 0.0\n7 11 8.8 13.2 2.0\n8 10 8.0 12.0 2.0\n9 3 2.4 3.6 0.0\n10 21 16.8 25.2 0.0\n11 18 14.4 21.6 1.0\n12 14 11.2 16.8 0.0\n13 16 12.8 19.2 2.0\n14 30 24.0 36.0 0.0\n15 45 36.0 54.0 0.0\n16 31 24.8 37.2 1.0\n17 40 32.0 48.0 1.0\n18 38 30.4 45.6 3.0\n n = 10 import numpy as np\ndf = pd.DataFrame(np.random.randint(20,100, 1000000), columns=['col1'])\n" }, { "answer_id": 74675416, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "pandas.core.window.rolling.Rolling.apply n = 3\n\ndf['counter'] = (df['col1'].rolling(n+1)\n .apply(lambda x: \n np.sum((x[:n] >= (x[n] * 0.8)) & (x[:n] <= (x[n] * 1.2))), \n raw=True).fillna(-1).astype(int))\n col1 df_min df_max counter\n0 10 8.0 12.0 -1\n1 5 4.0 6.0 -1\n2 8 6.4 9.6 -1\n3 12 9.6 14.4 1\n4 13 10.4 15.6 1\n5 6 4.8 7.2 0\n6 9 7.2 10.8 0\n7 11 8.8 13.2 2\n8 10 8.0 12.0 2\n9 3 2.4 3.6 0\n10 21 16.8 25.2 0\n11 18 14.4 21.6 1\n12 14 11.2 16.8 0\n13 16 12.8 19.2 2\n14 30 24.0 36.0 0\n15 45 36.0 54.0 0\n16 31 24.8 37.2 1\n17 40 32.0 48.0 1\n18 38 30.4 45.6 3\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19568665/" ]
74,673,700
<p>I heard that React Props is read only by default, however, I could overwrite props value in a component without errors. Is there settings to make props read only?</p> <pre><code>interface Props { readonly isText: boolean; } const ComponentA: FC&lt;Props&gt; = ({isText}: Props) { isText = false // &lt;- I can change isText even if I add readonly. why? return &lt;&gt;{isText}&lt;/&gt; } </code></pre>
[ { "answer_id": 74674318, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "df['df_min'] = df.col1 - df.col1 * 0.2\ndf['df_max'] = df.col1 + df.col1 * 0.2\nn = 3\ns = pd.Series(dtype='float')\nfor i in range(0, n):\n s1 = df.col1.shift(i+1).ge(df['df_min']) & df.col1.shift(i+1).le(df['df_max'])\n s = s.add(s1, fill_value=0)\ns[:n] = -1\ndf['counter'] = s\n df col1 df_min df_max counter\n0 10 8.0 12.0 -1.0\n1 5 4.0 6.0 -1.0\n2 8 6.4 9.6 -1.0\n3 12 9.6 14.4 1.0\n4 13 10.4 15.6 1.0\n5 6 4.8 7.2 0.0\n6 9 7.2 10.8 0.0\n7 11 8.8 13.2 2.0\n8 10 8.0 12.0 2.0\n9 3 2.4 3.6 0.0\n10 21 16.8 25.2 0.0\n11 18 14.4 21.6 1.0\n12 14 11.2 16.8 0.0\n13 16 12.8 19.2 2.0\n14 30 24.0 36.0 0.0\n15 45 36.0 54.0 0.0\n16 31 24.8 37.2 1.0\n17 40 32.0 48.0 1.0\n18 38 30.4 45.6 3.0\n n = 10 import numpy as np\ndf = pd.DataFrame(np.random.randint(20,100, 1000000), columns=['col1'])\n" }, { "answer_id": 74675416, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "pandas.core.window.rolling.Rolling.apply n = 3\n\ndf['counter'] = (df['col1'].rolling(n+1)\n .apply(lambda x: \n np.sum((x[:n] >= (x[n] * 0.8)) & (x[:n] <= (x[n] * 1.2))), \n raw=True).fillna(-1).astype(int))\n col1 df_min df_max counter\n0 10 8.0 12.0 -1\n1 5 4.0 6.0 -1\n2 8 6.4 9.6 -1\n3 12 9.6 14.4 1\n4 13 10.4 15.6 1\n5 6 4.8 7.2 0\n6 9 7.2 10.8 0\n7 11 8.8 13.2 2\n8 10 8.0 12.0 2\n9 3 2.4 3.6 0\n10 21 16.8 25.2 0\n11 18 14.4 21.6 1\n12 14 11.2 16.8 0\n13 16 12.8 19.2 2\n14 30 24.0 36.0 0\n15 45 36.0 54.0 0\n16 31 24.8 37.2 1\n17 40 32.0 48.0 1\n18 38 30.4 45.6 3\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7359831/" ]
74,673,707
<p>Take these two list of strings for example.</p> <pre><code>names = ['Jack', 'Steve', 'Marc', 'Xavier', 'Bob'] names_copy = ['Steve', 'Marc', 'Xavier', 'Bob', 'Jack'] </code></pre> <p>Essentially I'm trying to find a way to sort <code>names_copy</code> in the same way that <code>names</code> is sorted.</p> <p>So, a sorted version of <code>names_copy</code> would result in <code>['Jack', 'Steve', 'Marc', 'Xavier', 'Bob']</code></p> <blockquote> <p>NOTE: in my program, names_copy is being created with a map, so I cannot use <code>.sort()</code>, <code>sorted()</code> works however.</p> </blockquote> <p>I understand the sorted() function takes in a key parameter indicating the sort order, but I'm not too sure how to use it here.</p>
[ { "answer_id": 74677550, "author": "Timus", "author_id": 14311263, "author_profile": "https://Stackoverflow.com/users/14311263", "pm_score": 0, "selected": false, "text": "names_copy_sorted = sorted(names_copy, key=names.index)\n names_copy names names key priorities = dict((n, i) for i, n in enumerate(names))\nnames_copy_sorted = sorted(names_copy, key=priorities.get)\n names_copy names priorities = dict((n, i) for i, n in enumerate(names))\ndefault = len(priorities)\ndef key(name): return priorities.get(name, default)\n\nnames_copy_sorted = sorted(names_copy, key=key)\n names_copy names names names.index priorities.get" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20679438/" ]
74,673,724
<p>I have a java class, but when I'm trying to build a project I get an error</p> <pre class="lang-none prettyprint-override"><code>error: unclosed string literal return load().query(&quot;&quot;&quot; ^ </code></pre> <p><em>(the third quote)</em></p> <p>Can you please explain to me why it is an error?</p> <p>My code</p> <pre><code>@Component(ThreatImplMethodRepository.NAME) public class ThreatImplMethodRepository extends DefaultRepository&lt;ThreatImplMethod&gt; { public static final String NAME = &quot;gwf_ThreatImplMethodRepository&quot;; @Override protected Class&lt;ThreatImplMethod&gt; entityClass() { return ThreatImplMethod.class; } public List&lt;ThreatImplMethod&gt; getBySourcesAndTargets(List&lt;ImpactSource&gt; sources, List&lt;ImpactTarget&gt; targets, FetchPlan fetchPlan) { return load().query(&quot;&quot;&quot; select distinct im from gwf_ThreatImplMethodLink imLink join imLink.implMethods im where imLink.source in :sources and imLink.targets in :targets &quot;&quot;&quot;) .parameter(&quot;sources&quot;, sources) .parameter(&quot;targets&quot;, targets) .fetchPlan(fetchPlan) .list(); } } </code></pre>
[ { "answer_id": 74673842, "author": "Paresh_Maheshwari", "author_id": 15412080, "author_profile": "https://Stackoverflow.com/users/15412080", "pm_score": -1, "selected": false, "text": "@Component(ThreatImplMethodRepository.NAME)\npublic class ThreatImplMethodRepository extends \nDefaultRepository<ThreatImplMethod> {\npublic static final String NAME = \"gwf_ThreatImplMethodRepository\";\n\n@Override\nprotected Class<ThreatImplMethod> entityClass() {\n return ThreatImplMethod.class;\n}\n\npublic List<ThreatImplMethod> getBySourcesAndTargets(List<ImpactSource> sources, List<ImpactTarget> targets, FetchPlan fetchPlan) {\n return load().query(\"\"\"\n select distinct im\n from gwf_ThreatImplMethodLink imLink\n join imLink.implMethods im\n where imLink.source in :sources\n and imLink.targets in :targets\n \"\"\")\n .parameter(\"sources\", sources)\n .parameter(\"targets\", targets)\n .fetchPlan(fetchPlan)\n .list();\n }\n}\n" }, { "answer_id": 74675054, "author": "MC Emperor", "author_id": 507738, "author_profile": "https://Stackoverflow.com/users/507738", "pm_score": 3, "selected": true, "text": "\"\"" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13993894/" ]
74,673,772
<p>I know already upload answer to this same question but I try them they are not working for me because there is also some some update in selenium code too. <strong>Getting this Error</strong> <code>selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element &lt;div class=&quot;up-typeahead-fake&quot; data-test=&quot;up-c-typeahead-input-fake&quot;&gt;...&lt;/div&gt; is not clickable at point (838, 0). Other element would receive the click: &lt;div class=&quot;up-modal-header&quot;&gt;...&lt;/div&gt; </code>, When trying to send my searching keyword in this input with labeled &quot;Skills Search&quot; in advance searching pop-pup form.</p> <p><strong>Here is the URL:</strong> <a href="https://www.upwork.com/nx/jobs/search/modals/advanced-search?sort=recency&amp;pageTitle=Advanced%20Search&amp;_navType=modal&amp;_modalInfo=%5B%7B%22navType%22%3A%22modal%22,%22title%22%3A%22Advanced%20Search%22,%22modalId%22%3A%221670133126002%22,%22channelName%22%3A%22advanced-search-modal%22%7D%5D" rel="nofollow noreferrer">https://www.upwork.com/nx/jobs/search/modals/advanced-search?sort=recency&amp;pageTitle=Advanced%20Search&amp;_navType=modal&amp;_modalInfo=%5B%7B%22navType%22%3A%22modal%22,%22title%22%3A%22Advanced%20Search%22,%22modalId%22%3A%221670133126002%22,%22channelName%22%3A%22advanced-search-modal%22%7D%5D</a></p> <p><strong>Here is my code:</strong></p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.common.proxy import Proxy, ProxyType import time from fake_useragent import UserAgent import pyttsx3 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def main(): options = Options() service = Service('F:\\work\\chromedriver_win32\\chromedriver.exe') options.add_argument(&quot;start-maximized&quot;) options.add_argument('--disable-blink-features=AutomationControlled') #Adding the argument options.add_experimental_option(&quot;excludeSwitches&quot;,[&quot;enable-automation&quot;])#Disable chrome contrlled message (Exclude the collection of enable-automation switches) options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension options.add_experimental_option('useAutomationExtension', False) #Turn-off useAutomationExtension prefs = {&quot;credentials_enable_service&quot;: False, &quot;profile.password_manager_enabled&quot;: False} options.add_experimental_option(&quot;prefs&quot;, prefs) ua = UserAgent() userAgent = ua.random options.add_argument(f'user-agent={userAgent}') driver = webdriver.Chrome(service=service , options=options) url = 'https://www.upwork.com/nx/jobs/search/?sort=recency' driver.get(url) time.sleep(7) advsearch = driver.find_element(By.XPATH,'//button[contains(@title,&quot;Advanced Search&quot;)]') advsearch.click() time.sleep(10) skill = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//div[contains(@class,&quot;up-typeahead&quot;)]'))) skill.click() time.sleep(10) keys = [&quot;Web Scraping&quot;,&quot;Selenium WebDriver&quot;, &quot;Data Scraping&quot;, &quot;selenium&quot;, &quot;Web Crawling&quot;, &quot;Beautiful Soup&quot;, &quot;Scrapy&quot;, &quot;Data Extraction&quot;, &quot;Automation&quot;] for i in range(len(keys)): skill.send_keys(Keys[i],Keys.ENTER) time.sleep (2) main() </code></pre> <p>I try to send keys to the input field but its give me Error .ElementClickInterceptedException , I try old answer from stack previous question answer related to this error but they are not working for me because there is also some some update in selenium code too.</p>
[ { "answer_id": 74673886, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 1, "selected": false, "text": " import time\n\n skill = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//div[contains(@class,\"up-typeahead\")]')))\n driver.execute_script(\"arguments[0].click();\" ,skill)\n time.sleep(1)\n" }, { "answer_id": 74674154, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 1, "selected": true, "text": "import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://www.upwork.com/nx/jobs/search/?sort=recency\"\ndriver.get(url)\n\nkeys = [\"Web Scraping\",\"Selenium WebDriver\", \"Data Scraping\", \"selenium\", \"Web Crawling\", \"Beautiful Soup\", \"Scrapy\", \"Data Extraction\", \"Automation\"]\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler')))\ntime.sleep(5)\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler'))).click()\nfor i in range(len(keys)):\n wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,\"Advanced Search\")]'))).click()\n advanced_search_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test=\"modal-advanced-search-and_terms\"]')))\n advanced_search_input.clear()\n advanced_search_input.send_keys(keys[i])\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test=\"modal-advanced-search-search-btn\"]'))).click()\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20147022/" ]
74,673,815
<p>I have been watching videos of C#.net, Asp.net, and MVC from the kudvenkat youtube channel this man is so brilliant at teaching dot net technology but kudvenkat`s dot net videos are from 2012 and I think there will be dot net version 4.0 but still, currently so many peoples are learning dot net from him so here I want to know if there any issues with dot net version and can I still learn from him?</p>
[ { "answer_id": 74673886, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 1, "selected": false, "text": " import time\n\n skill = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//div[contains(@class,\"up-typeahead\")]')))\n driver.execute_script(\"arguments[0].click();\" ,skill)\n time.sleep(1)\n" }, { "answer_id": 74674154, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 1, "selected": true, "text": "import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://www.upwork.com/nx/jobs/search/?sort=recency\"\ndriver.get(url)\n\nkeys = [\"Web Scraping\",\"Selenium WebDriver\", \"Data Scraping\", \"selenium\", \"Web Crawling\", \"Beautiful Soup\", \"Scrapy\", \"Data Extraction\", \"Automation\"]\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler')))\ntime.sleep(5)\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#onetrust-accept-btn-handler'))).click()\nfor i in range(len(keys)):\n wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(@title,\"Advanced Search\")]'))).click()\n advanced_search_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test=\"modal-advanced-search-and_terms\"]')))\n advanced_search_input.clear()\n advanced_search_input.send_keys(keys[i])\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'[data-test=\"modal-advanced-search-search-btn\"]'))).click()\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457998/" ]
74,673,825
<p>I have an array like:</p> <pre><code>arr = [&quot;100 abc&quot;, &quot;ad&quot;, &quot;5 star&quot;, &quot;orange&quot;]; </code></pre> <p>I want to sort firstly strings with no numbers at the beginning and then strings with numbers add at the end, omit numbers and sort strings by name alphabetically.</p> <p>Expected output:</p> <pre><code>ad, orange, 100 abc, 5 star. </code></pre> <p>How can I do that in TypeScript/Angular?</p>
[ { "answer_id": 74673979, "author": "LawrenceWebDev", "author_id": 6533103, "author_profile": "https://Stackoverflow.com/users/6533103", "pm_score": 0, "selected": false, "text": "const startsWithNum = (str) => /^\\d/.test(str);\n\nconst afterNumPart = (str) => str.match(/^\\d+\\s(.*)/)[0];\n\nconst compareStrings = (a, b) => {\n if (startsWithNum(a)) {\n if (startsWithNum(b)) {\n // Both strings contain numbers, compare using parts after numbers\n return afterNumPart (a) < afterNumPart (b) ? -1 : 1;\n } else {\n // A contains numbers, but B does not, B comes first\n return 1;\n }\n } else if (startsWithNum(b)) {\n // A does not contain numbers, but B does, A comes first\n return -1;\n } else {\n // Neither string contains numbers, compare full strings\n return a < b ? -1 : 1;\n }\n};\n\nconst arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"];\nconst sortedArr = arr.sort(compareStrings);\n// ['ad', 'orange', '100 abc', '5 star']\n" }, { "answer_id": 74674065, "author": "Avraham Weinstein", "author_id": 8938503, "author_profile": "https://Stackoverflow.com/users/8938503", "pm_score": 0, "selected": false, "text": "const arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"]\narr.map(item => {\n return item.split(' ').map((subItem: string) => +subItem ? +subItem : subItem)}\n ).sort((a,b) => {\n if(a.find((item: any) => typeof item === 'number')){\n return 1;\n }else return -1\n }).map(item => item.join(' '))\n" }, { "answer_id": 74674428, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 1, "selected": false, "text": "filter result = [\n ...arr.filter(a => !/\\d/.test(a)),\n ...arr.filter(a => /\\d/.test(a)),\n]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15209188/" ]
74,673,827
<p>I'm trying to create a custom iterator over a string's characters, with the difference that it &quot;splits&quot; the string into two iterators. Which one is then used in its own <code>next()</code> depends on custom logic.</p> <pre class="lang-rs prettyprint-override"><code>struct WrappingIter&lt;I&gt; { iter_1: I, iter_2: I, // ... } impl&lt;I&gt; WrappingIter&lt;I&gt; where I: Iterator, { pub fn new(string: &amp;str, start_idx: usize) -&gt; Self { Self { iter_1: string[start_idx..].chars(), iter_2: string[..start_idx].chars(), // ... } } } </code></pre> <p>That gives me this error (for both assignments):</p> <pre><code> 1 error[E0308]: mismatched types --&gt; src/lib.rs:38:25 | 29 | impl&lt;I&gt; WrappingIter&lt;I&gt; | - this type parameter ... 38 | iter_1: string[start_idx..].chars(), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter `I`, found struct `Chars` | = note: expected type parameter `I` found struct `Chars&lt;'_&gt;` </code></pre> <p>I can't tell why. <a href="https://doc.rust-lang.org/std/str/struct.Chars.html#impl-Iterator-for-Chars%3C%27a%3E" rel="nofollow noreferrer"><code>std::str::Chars</code> implements the <code>Iterator</code> trait</a>, so my logic was that I could directly assign it to <code>WrappingIter</code>'s members. Need I perhaps perform some sort of cast?</p>
[ { "answer_id": 74673979, "author": "LawrenceWebDev", "author_id": 6533103, "author_profile": "https://Stackoverflow.com/users/6533103", "pm_score": 0, "selected": false, "text": "const startsWithNum = (str) => /^\\d/.test(str);\n\nconst afterNumPart = (str) => str.match(/^\\d+\\s(.*)/)[0];\n\nconst compareStrings = (a, b) => {\n if (startsWithNum(a)) {\n if (startsWithNum(b)) {\n // Both strings contain numbers, compare using parts after numbers\n return afterNumPart (a) < afterNumPart (b) ? -1 : 1;\n } else {\n // A contains numbers, but B does not, B comes first\n return 1;\n }\n } else if (startsWithNum(b)) {\n // A does not contain numbers, but B does, A comes first\n return -1;\n } else {\n // Neither string contains numbers, compare full strings\n return a < b ? -1 : 1;\n }\n};\n\nconst arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"];\nconst sortedArr = arr.sort(compareStrings);\n// ['ad', 'orange', '100 abc', '5 star']\n" }, { "answer_id": 74674065, "author": "Avraham Weinstein", "author_id": 8938503, "author_profile": "https://Stackoverflow.com/users/8938503", "pm_score": 0, "selected": false, "text": "const arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"]\narr.map(item => {\n return item.split(' ').map((subItem: string) => +subItem ? +subItem : subItem)}\n ).sort((a,b) => {\n if(a.find((item: any) => typeof item === 'number')){\n return 1;\n }else return -1\n }).map(item => item.join(' '))\n" }, { "answer_id": 74674428, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 1, "selected": false, "text": "filter result = [\n ...arr.filter(a => !/\\d/.test(a)),\n ...arr.filter(a => /\\d/.test(a)),\n]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151327/" ]
74,673,857
<p>I'm cleaning some text data and I've come across a problem associated with removing newline text. For this data, there are not merely <code>\n</code> strings in the text, but <code>\n\n</code> strings, as well as numbered newlines such as: <code>\n2</code> and <code>\n\n2</code>. The latter are my problem. How does one remove this using regex?</p> <p>I'm working in R. Here is some sample text and what I've used, so far:</p> <pre><code>#string string &lt;- &quot;There is a square in the apartment. \n\n4Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten.\n2&quot; #code attempt gsub(&quot;[\r\\n0-9]&quot;, '', string) </code></pre> <p>The problem with this regex code is that it removes numbers and matches with the letter <code>n</code>.</p> <p>I would like to have the following output:</p> <pre><code>&quot;There is a square in the apartment. Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten.&quot; </code></pre> <p>I'm using <a href="https://regexr.com/" rel="nofollow noreferrer">regexr</a> for reference.</p>
[ { "answer_id": 74673979, "author": "LawrenceWebDev", "author_id": 6533103, "author_profile": "https://Stackoverflow.com/users/6533103", "pm_score": 0, "selected": false, "text": "const startsWithNum = (str) => /^\\d/.test(str);\n\nconst afterNumPart = (str) => str.match(/^\\d+\\s(.*)/)[0];\n\nconst compareStrings = (a, b) => {\n if (startsWithNum(a)) {\n if (startsWithNum(b)) {\n // Both strings contain numbers, compare using parts after numbers\n return afterNumPart (a) < afterNumPart (b) ? -1 : 1;\n } else {\n // A contains numbers, but B does not, B comes first\n return 1;\n }\n } else if (startsWithNum(b)) {\n // A does not contain numbers, but B does, A comes first\n return -1;\n } else {\n // Neither string contains numbers, compare full strings\n return a < b ? -1 : 1;\n }\n};\n\nconst arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"];\nconst sortedArr = arr.sort(compareStrings);\n// ['ad', 'orange', '100 abc', '5 star']\n" }, { "answer_id": 74674065, "author": "Avraham Weinstein", "author_id": 8938503, "author_profile": "https://Stackoverflow.com/users/8938503", "pm_score": 0, "selected": false, "text": "const arr = [\"100 abc\", \"ad\", \"5 star\", \"orange\"]\narr.map(item => {\n return item.split(' ').map((subItem: string) => +subItem ? +subItem : subItem)}\n ).sort((a,b) => {\n if(a.find((item: any) => typeof item === 'number')){\n return 1;\n }else return -1\n }).map(item => item.join(' '))\n" }, { "answer_id": 74674428, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 1, "selected": false, "text": "filter result = [\n ...arr.filter(a => !/\\d/.test(a)),\n ...arr.filter(a => /\\d/.test(a)),\n]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18667604/" ]
74,673,859
<p>I have two json datas as</p> <pre><code>json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}] json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}] </code></pre> <p>i want to merge both the json and needed optput as</p> <pre><code>json_final = [{'purchasedPerson__id': 2, 'credit': 3000 , 'debit'=0}, {'purchasedPerson__id': 4, 'credit': 5000 , 'debit'=2000}, {'purchasedPerson__id': 1, 'credit'=0, 'debit': 8526}] </code></pre> <p>how the above method can be done</p>
[ { "answer_id": 74673899, "author": "Dileep", "author_id": 3786004, "author_profile": "https://Stackoverflow.com/users/3786004", "pm_score": 0, "selected": false, "text": "# Initialize the final JSON array\njson_final = []\n\n# Loop through the first JSON data set\nfor item in json_1:\n # Initialize the final JSON object for this item\n final_item = {'purchasedPerson__id': item['purchasedPerson__id'], 'credit': item['credit'], 'debit': 0}\n # Loop through the second JSON data set\n for item2 in json_2:\n # If the id matches, update the final item with the debit value\n if item['purchasedPerson__id'] == item2['purchasedPerson__id']:\n final_item['debit'] = item2['debit']\n # Add the final item to the final JSON array\n json_final.append(final_item)\n\n# Loop through the second JSON data set\nfor item in json_2:\n # Initialize a flag to keep track of whether the item already exists in the final JSON array\n exists = False\n # Loop through the final JSON array\n for final_item in json_final:\n # If the id matches, set the exists flag to True\n if final_item['purchasedPerson__id'] == item['purchasedPerson__id']:\n exists = True\n # If the item does not exist in the final JSON array, add it with credit and debit values of 0\n if not exists:\n json_final.append({'purchasedPerson__id': item['purchasedPerson__id'], 'credit': 0, 'debit': item['debit']})\n" }, { "answer_id": 74673951, "author": "Tranbi", "author_id": 13525512, "author_profile": "https://Stackoverflow.com/users/13525512", "pm_score": 1, "selected": false, "text": "pandas import pandas as pd\n\njson_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]\njson_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}]\ndf1 = pd.DataFrame(json_1)\ndf2 = pd.DataFrame(json_2)\n\ndf_out = pd.merge(df1, df2, on=\"purchasedPerson__id\", how=\"outer\").fillna(0)\ndf_out.to_dict(orient=\"records\")\n [{'purchasedPerson__id': 2, 'credit': 3000.0, 'debit': 0.0}, {'purchasedPerson__id': 4, 'credit': 5000.0, 'debit': 2000.0}, {'purchasedPerson__id': 1, 'credit': 0.0, 'debit': 8526.0}]\n" }, { "answer_id": 74674000, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 2, "selected": true, "text": "json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]\njson_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}]\n\n# create a dictionary for the merged data\ndata = {}\n\n# loop through each JSON and add the data to the dictionary\nfor j in json_1:\n data[j['purchasedPerson__id']] = {'credit': j['credit'], 'debit': 0}\n\nfor j in json_2:\n if j['purchasedPerson__id'] in data:\n data[j['purchasedPerson__id']] = {'credit': data[j['purchasedPerson__id']]['credit'], 'debit': j['debit']}\n else:\n data[j['purchasedPerson__id']] = {'credit': 0, 'debit': j['debit']}\n\n# convert the dictionary to a list\njson_final = []\nfor key, value in data.items():\n json_final.append({'purchasedPerson__id': key, 'credit': value['credit'], 'debit': value['debit']})\n\nprint(json_final)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14442225/" ]
74,673,863
<p>how to click on anchor tag in the card and redirects me to another page with more details of the current card example click on opens new tab with current (clicked) card details here is an api for item <a href="https://api.npoint.io/d275425a434e02acf2f7/News/0" rel="nofollow noreferrer">https://api.npoint.io/d275425a434e02acf2f7/News/0</a></p> <p>snippets of code also a link that works <a href="https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js</a></p> <p>my api <a href="https://api.npoint.io/d275425a434e02acf2f7" rel="nofollow noreferrer">https://api.npoint.io/d275425a434e02acf2f7</a> for rendering all items in cards</p> <pre><code> filteredCat?.map((list) =&gt; { if (list.showOnHomepage === &quot;yes&quot;) { const date = format( new Date(list.publishedDate), &quot;EEE dd MMM yyyy&quot; ); const showCat = news.map((getid) =&gt; { if (getid.id == list.categoryID) return getid.name; }); // const rec = list.publishedDate.sort((date1, date2) =&gt; date1 - date2); return ( &lt;Card className=&quot; extraCard col-lg-3&quot; style={{ width: &quot;&quot; }} id={list.categoryID} &gt; &lt;Card.Img variant=&quot;top&quot; src={list.urlToImage} alt=&quot;Image&quot; /&gt; &lt;Card.Body&gt; &lt;Card.Title className=&quot;textTitle&quot;&gt; {list.title} &lt;/Card.Title&gt; &lt;Card.Text&gt;&lt;/Card.Text&gt; &lt;small className=&quot;text-muted d-flex&quot;&gt; &lt;FaRegCalendarAlt className=&quot;m-1&quot; style={{ color: &quot;#0aceff&quot; }} /&gt; {date} &lt;/small&gt; &lt;div style={{ color: &quot;#0aceff&quot; }} className=&quot;d-flex justify-content-between&quot; &gt; &lt;Button variant=&quot;&quot; className={classes[&quot;btn-cat&quot;]}&gt; {showCat} &lt;/Button&gt; &lt;div&gt; &lt;FaRegHeart /&gt; &lt;FaLink /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Card.Body&gt; &lt;/Card&gt; ); } }) } &lt;/div&gt; } </code></pre> <p>I tried this technique but it does direct me to the same page not the new tab with empty page !!</p> <pre><code>function handleClick(event) { event.preventDefault(); window.location.href = 'src/comp/newsitem'; } function news() { return ( &lt;a href=&quot;#&quot; onClick={handleClick}&gt; Click me to redirect! &lt;/a&gt; ); } </code></pre>
[ { "answer_id": 74673874, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 1, "selected": false, "text": "function handleClick(event) {\n // Prevent the default behavior of the anchor tag\n event.preventDefault();\n\n // Set the new page's URL using the window.location.href property\n window.location.href = 'src/comp/newsitem';\n}\n function news() {\n return (\n <a href=\"#\" onClick={handleClick}>\n Click me to redirect!\n </a>\n );\n}\n" }, { "answer_id": 74674259, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 1, "selected": true, "text": "import { BrowserRouter, Routes, Route } from 'react-router-dom';\nimport App from './App';\nimport News from './News';\nimport NewsItem from './NewsItem';\n\nfunction Pages() {\n\n return (\n <BrowserRouter>\n <Routes>\n <Route path='/news' element={<News />} />\n <Route path='/newsItem' element={<NewsItem />} />\n <Route path='/' element={<App />} />\n </Routes>\n </BrowserRouter>\n );\n}\n\nexport default Pages;\n import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport Pages from \"./Pages\";\n\nconst rootElement = document.getElementById(\"root\");\nconst root = createRoot(rootElement);\n\nroot.render(\n <StrictMode>\n <Pages />\n </StrictMode>\n);\n function NewsItem() {\n return <div>News Item</div>;\n}\nexport default NewsItem;\n import { Link } from 'react-router-dom' \n <Link to='/news' />\n <Link to='/news' target='_blank' />\n <Link to=\"/newsItem\">News Item</Link>\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676584/" ]
74,673,894
<pre><code>for (int i = 1; i &lt;= size; i++) { printf(&quot;Enter element %d: &quot;, i); scanf(&quot;%d&quot;, &amp;array[i]); if (array [i] &lt; 0) break; } printf(&quot;[&quot;); for (int i = 1; i &lt;= size; i++) { if (array[i] &lt; 0) break; printf(&quot;%d&quot;, array[i]); } printf(&quot;]&quot;); </code></pre> <p>The output of the code is this</p> <pre><code>Enter size: 10 Enter element 1: 6 Enter element 2: 8 Enter element 3: 23 Enter element 4: -2 [6,8,23,] </code></pre> <p>And the professor is expecting it to be this</p> <pre><code>Enter size: 10 Enter element 1: 6 Enter element 2: 8 Enter element 3: 23 Enter element 4: -2 [6,8,23] </code></pre>
[ { "answer_id": 74673874, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 1, "selected": false, "text": "function handleClick(event) {\n // Prevent the default behavior of the anchor tag\n event.preventDefault();\n\n // Set the new page's URL using the window.location.href property\n window.location.href = 'src/comp/newsitem';\n}\n function news() {\n return (\n <a href=\"#\" onClick={handleClick}>\n Click me to redirect!\n </a>\n );\n}\n" }, { "answer_id": 74674259, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 1, "selected": true, "text": "import { BrowserRouter, Routes, Route } from 'react-router-dom';\nimport App from './App';\nimport News from './News';\nimport NewsItem from './NewsItem';\n\nfunction Pages() {\n\n return (\n <BrowserRouter>\n <Routes>\n <Route path='/news' element={<News />} />\n <Route path='/newsItem' element={<NewsItem />} />\n <Route path='/' element={<App />} />\n </Routes>\n </BrowserRouter>\n );\n}\n\nexport default Pages;\n import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport Pages from \"./Pages\";\n\nconst rootElement = document.getElementById(\"root\");\nconst root = createRoot(rootElement);\n\nroot.render(\n <StrictMode>\n <Pages />\n </StrictMode>\n);\n function NewsItem() {\n return <div>News Item</div>;\n}\nexport default NewsItem;\n import { Link } from 'react-router-dom' \n <Link to='/news' />\n <Link to='/news' target='_blank' />\n <Link to=\"/newsItem\">News Item</Link>\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680229/" ]
74,673,906
<p><strong>models.py</strong></p> <pre><code>class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) </code></pre> <p><strong>views.py</strong></p> <p>The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse.</p> <pre><code>def backlog_list(request): account_name = request.POST['account_name'] access_log = Log.objects.filter(source=account_name) return JsonResponse({&quot;access_log&quot;:list(access_log.values())}) </code></pre> <p><strong>dashboard.html</strong></p> <p>This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like <a href="https://i.stack.imgur.com/JVlQ2.png" rel="nofollow noreferrer">this</a> otherwise.</p> <pre><code>&lt;h3&gt;You scanned the QR code during these times.&lt;/h3&gt; &lt;div id=&quot;display&quot;&gt; &lt;/div&gt; &lt;script&gt; $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'POST', url : &quot;/backlog_list&quot;, data:{ account_name:$('#account_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(response){ console.log(response); $(&quot;#display&quot;).empty(); for (var key in response.access_log) { var temp=&quot;&lt;div class='container darker'&gt;&lt;span class='time-left'&gt;&quot;+response.access_log[key].date+&quot;&lt;/span&gt;&lt;/div&gt;&quot;; $(&quot;#display&quot;).append(temp); } }, error: function(response){ alert('An error occurred') } }); },1000); }) &lt;/script&gt; </code></pre> <p>My goal is to have the Date and time displayed like &quot;Jan. 10, 2000, 9:30:20 A.M.&quot;</p> <p>I've tried changing the format directly from the models.py by adding &quot;strftime&quot; but the error response is triggered.</p>
[ { "answer_id": 74673874, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 1, "selected": false, "text": "function handleClick(event) {\n // Prevent the default behavior of the anchor tag\n event.preventDefault();\n\n // Set the new page's URL using the window.location.href property\n window.location.href = 'src/comp/newsitem';\n}\n function news() {\n return (\n <a href=\"#\" onClick={handleClick}>\n Click me to redirect!\n </a>\n );\n}\n" }, { "answer_id": 74674259, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 1, "selected": true, "text": "import { BrowserRouter, Routes, Route } from 'react-router-dom';\nimport App from './App';\nimport News from './News';\nimport NewsItem from './NewsItem';\n\nfunction Pages() {\n\n return (\n <BrowserRouter>\n <Routes>\n <Route path='/news' element={<News />} />\n <Route path='/newsItem' element={<NewsItem />} />\n <Route path='/' element={<App />} />\n </Routes>\n </BrowserRouter>\n );\n}\n\nexport default Pages;\n import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport Pages from \"./Pages\";\n\nconst rootElement = document.getElementById(\"root\");\nconst root = createRoot(rootElement);\n\nroot.render(\n <StrictMode>\n <Pages />\n </StrictMode>\n);\n function NewsItem() {\n return <div>News Item</div>;\n}\nexport default NewsItem;\n import { Link } from 'react-router-dom' \n <Link to='/news' />\n <Link to='/news' target='_blank' />\n <Link to=\"/newsItem\">News Item</Link>\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14723671/" ]
74,674,016
<p>I would like to know where in my code the form went wrong.</p> <pre><code>&lt;?php if(isset($_POST['submit'])) { $arrayName = array(&quot;TeacherA&quot;, &quot;TeacherB&quot;, &quot;TeacherC&quot; , &quot;TeacherD&quot;, &quot;TeacherE&quot;); $minimum = 5; $maximum = 10; $name = $_POST['yourName']; $email = $_POST['yourEmail']; if(strlen($name) &lt; $minimum) { echo &quot;Your name should be longer than 5 characters&quot;; } if(strlen($name) &gt; $maximum) { echo &quot;Your name should not be longer than 10 characters&quot;; } if(!in_array($name,$arrayName)){ echo &quot;Please do register with us before you can login&quot;; } else { echo &quot;Welcome!&quot;; } } ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Blank&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action=&quot;form.php&quot; method=&quot;post&quot;&gt; &lt;label&gt;Your Name: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;yourName&quot;&gt; &lt;br&gt; &lt;label for=&quot;&quot;&gt;Your E mail:&lt;/label&gt; &lt;input type=&quot;email&quot; name=&quot;yourEmail&quot; id=&quot;&quot;&gt;&lt;br&gt; &lt;!-- &lt;textarea name=&quot;yourMessage&quot; id=&quot;&quot; cols=&quot;30&quot; rows=&quot;10&quot;&gt;&lt;/textarea&gt;&lt;br&gt; --&gt; &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;submit&quot;&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I run through the localhost, however, I could not get result that I wanted.</p> <p>The result that I wanted is if I didn't enter the names in the &quot;Your Name&quot; field, then it should show the result:</p> <p><strong>Please do register with us before you can login</strong></p>
[ { "answer_id": 74674317, "author": "Vicky Maharjan", "author_id": 9135930, "author_profile": "https://Stackoverflow.com/users/9135930", "pm_score": -1, "selected": false, "text": "if(!isset($name)){\n echo \"Please do register with us before you can login\";\n}\nelse{\n echo \"Welcome\";\n}\n <input type=\"text\" name=\"yourName\" required>\n" }, { "answer_id": 74674382, "author": "Hamza El Fahli", "author_id": 20680433, "author_profile": "https://Stackoverflow.com/users/20680433", "pm_score": 1, "selected": false, "text": "strlen($name) 0 Your name should be longer than 5 characters if (isset($_POST['submit'])) {\n\n $arrayName = array(\"TeacherA\", \"TeacherB\", \"TeacherC\", \"TeacherD\", \"TeacherE\");\n\n $minimum = 5;\n $maximum = 10;\n\n $name = $_POST['yourName'];\n $email = $_POST['yourEmail'];\n\n if (empty($name)) {\n\n echo \"Please do register with us before you can login\";\n\n } else {\n\n if (strlen($name) < $minimum) {\n\n echo \"Your name should be longer than 5 characters\";\n\n } else {\n\n if (strlen($name) > $maximum) {\n\n echo \"Your name should be less than 10 characters\";\n\n } else {\n\n if (in_array($name, $arrayName)) {\n\n echo \"Welcome!\";\n\n } else {\n\n echo \"Your login is not correct\";\n\n }\n\n }\n\n }\n\n }\n\n }\n empty() return;" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15033925/" ]
74,674,025
<p>I have a bit complicated PowerQuery query which has many steps. Within these steps I have a date, team and conditions as below (not actual data)</p> <p><a href="https://i.stack.imgur.com/0UOdJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0UOdJ.png" alt="enter image description here" /></a></p> <p>So the challenge is that I want to count the Pass number for each team for each day and then create another count for Pass and Fail and then it will be used in so many calculations which I can handle later.</p> <p>I have tried many options, like for example grouping, but it was so confusing because as I mentioned before, the query has so many columns and calculations now. I could successfully solve the issue by creating DAX measure, but the issue here that I need to calculate the average outcome which is not possible to because I couldn't also average the measure of the outcome. So I have no other option but to make the countif though PowerQuery.</p> <p>Appreciate your help and ideas.</p> <p>Raw data as text is <a href="https://docs.google.com/spreadsheets/d/17LIy4nhdZutfq6xUCf7QL_alSkAVR9yF45BfvKIdk0c/edit#gid=0" rel="nofollow noreferrer">here in google sheets</a></p>
[ { "answer_id": 74674518, "author": "David Bacci", "author_id": 18345037, "author_profile": "https://Stackoverflow.com/users/18345037", "pm_score": 0, "selected": false, "text": "let\n Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText(\"i45WMtQ31DcyMDJW0lFyDAISAYnFxUqxOigSrn44JFxcgYRbYmYOuoSfD7KEkb4RilEkSeA0Cr8E3LlIEmDnEpYw1jfWNzAywDSKIgmcduCUQI0PJAnU+CDGKNSwotwOiFGxAA==\", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t, Team = _t, #\"PASS/FAIL\" = _t]),\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Date\", type text}, {\"Team\", type text}, {\"PASS/FAIL\", type text}}),\n #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Date\", \"Team\"}, {{\"Count\", each Table.RowCount(_), Int64.Type}}),\n Custom1 = List.Distinct( #\"Grouped Rows\"[Date]),\n #\"Converted to Table\" = Table.FromList(Custom1, Splitter.SplitByNothing(), {\"Date\"}, null, ExtraValues.Error),\n #\"Added Custom\" = Table.AddColumn(#\"Converted to Table\", \"Team\", each List.Distinct( #\"Grouped Rows\"[Team])),\n #\"Expanded Team\" = Table.ExpandListColumn(#\"Added Custom\", \"Team\"),\n #\"Merged Queries\" = Table.NestedJoin(#\"Expanded Team\", {\"Date\", \"Team\"}, #\"Grouped Rows\", {\"Date\", \"Team\"}, \"Expanded Team\", JoinKind.LeftOuter),\n #\"Expanded Expanded Team\" = Table.ExpandTableColumn(#\"Merged Queries\", \"Expanded Team\", {\"Count\"}, {\"Count\"}),\n #\"Replaced Value\" = Table.ReplaceValue(#\"Expanded Expanded Team\",null,0,Replacer.ReplaceValue,{\"Count\"})\nin\n #\"Replaced Value\"\n" }, { "answer_id": 74675494, "author": "Ron Rosenfeld", "author_id": 2872922, "author_profile": "https://Stackoverflow.com/users/2872922", "pm_score": 1, "selected": false, "text": "0203 2023 #\"Grouped Rows\" = Table.Group(#\"Previous Step\", {\"Date\", \"Team\"}, {\n {\"Pass\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Pass\")), Int64.Type},\n {\"Fail\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Fail\")), Int64.Type}\n })\n let\n Source = Excel.CurrentWorkbook(){[Name=\"Table12\"]}[Content],\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Date\", type date}, {\"Team\", type text}, {\"PASS/FAIL\", type text}}),\n #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Date\", \"Team\"}, {\n {\"Pass\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Pass\")), Int64.Type},\n {\"Fail\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Fail\")), Int64.Type}\n })\nin\n #\"Grouped Rows\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11657343/" ]
74,674,033
<p>I am trying to define custom function and I wanted to find how can I calculate estimated cost of that function</p> <p><a href="https://www.postgresql.org/docs/current/sql-createfunction.html" rel="nofollow noreferrer">https://www.postgresql.org/docs/current/sql-createfunction.html</a></p> <p>I tried giving different values of cost function but unable to find to find how to estimate that cost.</p>
[ { "answer_id": 74677289, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 1, "selected": false, "text": "seq_page_cost" }, { "answer_id": 74677330, "author": "Marcell Almeida", "author_id": 1690338, "author_profile": "https://Stackoverflow.com/users/1690338", "pm_score": -1, "selected": false, "text": "CREATE FUNCTION get_customer_orders(customer_id int)\nRETURNS SETOF orders\nAS $$\n SELECT * FROM orders WHERE customer_id = $1;\n$$ LANGUAGE SQL\nCOST 100;\n" }, { "answer_id": 74679638, "author": "mwalter", "author_id": 16975520, "author_profile": "https://Stackoverflow.com/users/16975520", "pm_score": 0, "selected": false, "text": " CREATE OR REPLACE FUNCTION a() RETURNS SET OF INTEGER AS $$\n SELECT 1;\n$$\nLANGUAGE SQL;\nEXPLAIN SELECT * FROM a() CROSS JOIN (Values(1),(2),(3)) as foo;\n\nNested Loop (cost=0.25..47.80 rows=3000 width=8)\n -> Function Scan on a (cost=0.25..10.25 rows=1000 width=4)\n -> Materialize (cost=0.00..0.05 rows=3 width=4)\n -> Values Scan on \"*VALUES*\" (cost=0.00..0.04 rows=3 width=4)\n(4 rows)\n EXPLAIN SELECT * FROM pg_language WHERE lanname ILIKE '%sql%' AND slow_\nfunction(lanname)AND fast_function(lanname);\n QUERY PLAN\n-------------------------------------------------------------------------\nSeq Scan on pg_language (cost=0.00..101.05 rows=1 width=114)\n Filter: (fast_function(lanname) AND (lanname ~~* '%sql%'::text) AND \nslow_function(lanname))\n(2 rows)\n" }, { "answer_id": 74680064, "author": "jjanes", "author_id": 1721239, "author_profile": "https://Stackoverflow.com/users/1721239", "pm_score": 0, "selected": false, "text": "explain analyze select sqrt(x::double precision) from generate_series(1,1000000) f(x);\n explain analyze select your_func(x::double precision) from generate_series(1,1000000) f(x);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7805549/" ]
74,674,071
<p>It's really expensive to transfer whole model from server to client specially when loading lists. The solution is to ignore empty, null or default values which can be refilled in client side. Consider a <code>Customer</code> model like this:</p> <pre><code>export class Customer { customerId: number = 0; ncode: string = 'some default text'; name: string = ''; age: int = 20; isActive: boolean = false; birthday: Date | null = null; // And much more fields ... } </code></pre> <p>We have same model in server side and the server will ignore null and default fields in serialization. For example, this is a customer sent from server:</p> <pre><code>&quot;{'customerId':1234}&quot; </code></pre> <p>What happens is that the object created by angular http get, is a <code>Customer</code> with only <code>customerId</code> field! All other fields are undefined. Is there any solution to fix it globally with no third party library to force angular to value missing fields with their default values?</p> <p>Update: Here is the request code:</p> <pre><code>export class CustomerComponent implements OnInit { constructor(private http: HttpClient) { } ngOnInit(): void { this.http.get&lt;Customer&gt;('/api/getCustomer').subscribe((response) =&gt; { console.log(response); // {'customerId':12345} }); } } </code></pre> <p>Update 2: As I thought there may be a global solution, I made a simple example. But we have a generic function to handle all api requests, which is generic and returns <code>&lt;T&gt;(&lt;any&gt;response)</code></p> <pre><code>public request&lt;T&gt;(api: string, method: string = 'GET', formData: any): Observable&lt;T&gt;{ return new Observable((observer: Observer&lt;T&gt;) =&gt; { header = new HttpHeaders({/*...*/}); this.http.request&lt;T&gt;(new HttpRequest(method, api, JSON.stringify(formData), {headers: header})) .subscribe({next: (response) =&gt; { observer.next(&lt;T&gt;(&lt;any&gt;response)); // &lt;= This line must be changed I think }}); } } </code></pre>
[ { "answer_id": 74674793, "author": "Mehyar Sawas", "author_id": 5012127, "author_profile": "https://Stackoverflow.com/users/5012127", "pm_score": 0, "selected": false, "text": "this.http.get<Customer>('/api/getCustomer').subscribe((response) => {\n const customer = {...new Customer(), ...response}; // use spread operator to merge the two objects (defaults, response values)\n console.log(customer); // response will be a Customer instance \n });\n" }, { "answer_id": 74674804, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 2, "selected": false, "text": "ngOnInit(): void { \n this.http.get<Customer>('/api/getCustomer').pipe(\n // Instantiate an object with default-values\n // and merge it with the retrieved partial-object:\n map(res =>({ ...new Customer(), ...res } as Customer))\n )\n .subscribe((response) => { console.log(response); });\n}\n\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6363853/" ]
74,674,094
<p>If there is any wrong property (For example if I send the payload data, Person_ instead of Person), model <strong>fully</strong> gets as null <em>(Post([FromBody] Request data))</em></p> <pre><code>public class Person { public Guid Id { get; set; } public string? Firstname { get; set; } public string? Lastname { get; set; } } public class Request { public Guid Id { get; set; } public Guid? Personid { get; set; } public virtual Person? Person { get; set; } } public IActionResult Post([FromBody] Request data) { ... } curl --location --request POST 'https://localhost:7124/v2/request?$expand=Person($select=Id,Firstname,Lastname)/Request&amp;@odata.context=%27https://localhost:7124/v2/$metadata' \ --header 'Content-Type: application/json' \ --data-raw '{ &quot;Id&quot;: &quot;a436677a-fa4b-465e-8e70-211a1a3de8e9&quot;, &quot;Personid&quot;: &quot;be9b53ad-4dfb-4db5-b269-32669f7c4e2d&quot;, &quot;Person_&quot; : { &quot;Firstname&quot;: &quot;JOHN&quot;, &quot;Lastname&quot;: &quot;SMITH&quot;, } }' </code></pre> <p>I need to get the model even though some properties not correct according to model schema.</p> <p>What could be the reason for it being null?</p>
[ { "answer_id": 74674329, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "Person Request public Person Person_ { get; set; } public virtual Person? Person_ { get; set; } Person JsonProperty [JsonProperty(\"Person_\")]\npublic virtual Person? Person { get; set; }\n" }, { "answer_id": 74675157, "author": "user2748122", "author_id": 2748122, "author_profile": "https://Stackoverflow.com/users/2748122", "pm_score": -1, "selected": false, "text": "public class CustomResourceDeserializer : ODataResourceDeserializer\n{\n public CustomResourceDeserializer(IODataDeserializerProvider deserializerProvider) : base(deserializerProvider)\n {\n }\n\n public override void ApplyNestedProperty(object resource, ODataNestedResourceInfoWrapper resourceInfoWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\n {\n try\n {\n base.ApplyNestedProperty(resource, resourceInfoWrapper, structuredType, readContext);\n }\n catch (System.Exception)\n {\n \n }\n \n }\n}\n" }, { "answer_id": 74677266, "author": "Chris Schaller", "author_id": 1690217, "author_profile": "https://Stackoverflow.com/users/1690217", "pm_score": 1, "selected": true, "text": "null ModelState public class Request\n{\n public Guid Id { get; set; }\n public Guid? Personid { get; set; }\n public virtual Person? Person { get; set; }\n public IDictionary<string, object> DynamicProperties { get; set; }\n}\n builder.Entity<Request>(\"request\").EntityType.IsOpen();\n _person JToken /// <summary>\n/// Inserts a new item into this collection\n/// </summary>\n/// <param name=\"item\">The item to insert</param>\n/// <returns>CreatedODataResult</returns>\n[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Format | AllowedQueryOptions.Select)]\npublic virtual async Task<IActionResult> Post([FromBody] Newtonsoft.Json.Linq.JToken x)\n//public virtual async Task<IActionResult> Post(TEntity item)\n{\n TEntity item = x.ToObject<TEntity>();\n\n ... insert custom logic to resolve the badly formed properties\n\n // Tell the client that the request is invalid, if it is still invalid.\n if (!ModelState.IsValid)\n return BadRequest(ModelState);\n\n //EvalSecurityPolicy(item, Operation.Insert);\n await ApplyPost(item);\n //UpdateRelationships(item, Operation.Insert);\n\n await _db.SaveChangesAsync();\n\n return Created(item);\n}\n\n/// <summary>\n/// Inheriting classes can override this method to apply custom fields or other properties from dynamic members in the posted item, base class will apply TenantId only if it has not already been applied\n/// </summary>\n/// <remarks>This process is called after the usual validation overriding just this process means you do not have to replicate the existing internal logic for the afore mentioned tasks.</remarks>\n/// <param name=\"item\">The new item that has been uploaded</param>\n/// <returns>Promise to add the item to the underlying table store</returns>\npublic virtual Task ApplyPost(TEntity item)\n{\n GetEntitySet().Add(item);\n return Task.CompletedTask;\n}\n ODataController ApplyPost ModelState" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748122/" ]
74,674,114
<p>I am new in java. I am trying convert simple java app with terminal output to a app with a GUI or UI. I have seen small java applications with little window , like calculator or currency converter.</p> <p>This is the program I am trying to convert to a GUI app <a href="https://github.com/Abhinav-26/Employee-Management-System/blob/master/EmployManagementSystem.java" rel="nofollow noreferrer">https://github.com/Abhinav-26/Employee-Management-System/blob/master/EmployManagementSystem.java</a></p> <p>I have tried to run this app. I am getting the out put in a terminal. (image 1)<a href="https://i.stack.imgur.com/qh0MH.png" rel="nofollow noreferrer">terminal output</a></p> <p>I need a UI to this simple app , like image 2 - <a href="https://i.stack.imgur.com/bUB2J.png" rel="nofollow noreferrer">example of ui</a></p> <p>I am expecting to get a simple java app with UI , like in picture 2. Is there a way to edit existing app ? What should I google / lookup ?</p>
[ { "answer_id": 74674329, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "Person Request public Person Person_ { get; set; } public virtual Person? Person_ { get; set; } Person JsonProperty [JsonProperty(\"Person_\")]\npublic virtual Person? Person { get; set; }\n" }, { "answer_id": 74675157, "author": "user2748122", "author_id": 2748122, "author_profile": "https://Stackoverflow.com/users/2748122", "pm_score": -1, "selected": false, "text": "public class CustomResourceDeserializer : ODataResourceDeserializer\n{\n public CustomResourceDeserializer(IODataDeserializerProvider deserializerProvider) : base(deserializerProvider)\n {\n }\n\n public override void ApplyNestedProperty(object resource, ODataNestedResourceInfoWrapper resourceInfoWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\n {\n try\n {\n base.ApplyNestedProperty(resource, resourceInfoWrapper, structuredType, readContext);\n }\n catch (System.Exception)\n {\n \n }\n \n }\n}\n" }, { "answer_id": 74677266, "author": "Chris Schaller", "author_id": 1690217, "author_profile": "https://Stackoverflow.com/users/1690217", "pm_score": 1, "selected": true, "text": "null ModelState public class Request\n{\n public Guid Id { get; set; }\n public Guid? Personid { get; set; }\n public virtual Person? Person { get; set; }\n public IDictionary<string, object> DynamicProperties { get; set; }\n}\n builder.Entity<Request>(\"request\").EntityType.IsOpen();\n _person JToken /// <summary>\n/// Inserts a new item into this collection\n/// </summary>\n/// <param name=\"item\">The item to insert</param>\n/// <returns>CreatedODataResult</returns>\n[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Format | AllowedQueryOptions.Select)]\npublic virtual async Task<IActionResult> Post([FromBody] Newtonsoft.Json.Linq.JToken x)\n//public virtual async Task<IActionResult> Post(TEntity item)\n{\n TEntity item = x.ToObject<TEntity>();\n\n ... insert custom logic to resolve the badly formed properties\n\n // Tell the client that the request is invalid, if it is still invalid.\n if (!ModelState.IsValid)\n return BadRequest(ModelState);\n\n //EvalSecurityPolicy(item, Operation.Insert);\n await ApplyPost(item);\n //UpdateRelationships(item, Operation.Insert);\n\n await _db.SaveChangesAsync();\n\n return Created(item);\n}\n\n/// <summary>\n/// Inheriting classes can override this method to apply custom fields or other properties from dynamic members in the posted item, base class will apply TenantId only if it has not already been applied\n/// </summary>\n/// <remarks>This process is called after the usual validation overriding just this process means you do not have to replicate the existing internal logic for the afore mentioned tasks.</remarks>\n/// <param name=\"item\">The new item that has been uploaded</param>\n/// <returns>Promise to add the item to the underlying table store</returns>\npublic virtual Task ApplyPost(TEntity item)\n{\n GetEntitySet().Add(item);\n return Task.CompletedTask;\n}\n ODataController ApplyPost ModelState" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680462/" ]
74,674,141
<p>I have example data as follows:</p> <pre><code>library(data.table) datA &lt;- fread(&quot;ID somevar NA 4 NA 3 2 5&quot;) datB &lt;- fread(&quot;ID somevar 7 4 NA 3 NA 5&quot;) dat_list &lt;- list(datA, datB) </code></pre> <p>In dat_list I would like to replace all <code>NA</code>'s in the <code>ID</code> column with a new <code>ID</code>-number.</p> <p>I would like this number to be unique and start at <code>100</code>. I thought of something like this:</p> <pre><code>for (i in seq_along(dat_list)){ temp &lt;- dat_list[[i]] count_of_seq &lt;- sum(is.na(temp$ID)) sequence_dat &lt;- seq(100, 100+count_of_seq) temp &lt;- setDT(temp)[is.na(ID), ID:=sequence_dat[i]] } </code></pre> <p>But this does not work because, it uses only one number of the sequence for each list:</p> <p><a href="https://i.stack.imgur.com/bB5M1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bB5M1.png" alt="enter image description here" /></a></p> <p>How should I do this properly?</p> <p>Desired output:</p> <pre><code>library(data.table) datA &lt;- fread(&quot;ID somevar 100 4 101 3 2 5&quot;) datB &lt;- fread(&quot;ID somevar 7 4 102 3 103 5&quot;) dat_list &lt;- list(datA, datB) </code></pre>
[ { "answer_id": 74674220, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 1, "selected": false, "text": "dplyr dat_list %>%\n bind_rows(., .id = \"dataset_ID\") %>%\n mutate(ID = ifelse(is.na(ID), 99 + cumsum(is.na(ID)), ID)) %>%\n group_split(dataset_ID, .keep = FALSE)\n\n[[1]]\n# A tibble: 3 × 2\n ID somevar\n <dbl> <int>\n1 100 4\n2 101 3\n3 2 5\n\n[[2]]\n# A tibble: 3 × 2\n ID somevar\n <dbl> <int>\n1 7 4\n2 102 3\n3 103 5\n" }, { "answer_id": 74674262, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 1, "selected": false, "text": "id <- 99\nfor (i in seq_along(dat_list)) {\n nas <- is.na(dat_list[[i]]$ID)\n dat_list[[i]]$ID[nas] <- id + seq_len(sum(nas))\n id <- id + sum(nas)\n}\n\ndat_list\n# [[1]]\n# ID somevar\n# 1: 100 4\n# 2: 101 3\n# 3: 2 5\n# \n# [[2]]\n# ID somevar\n# 1: 7 4\n# 2: 102 3\n# 3: 103 5\n" }, { "answer_id": 74679721, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "data.table library(data.table)\ndf1 <- rbindlist(dat_list, idcol = 'grp')[is.na(ID), ID := 99 + .I]\nsplit(df1[,-1], df1$grp)\n$`1`\n ID somevar\n1: 100 4\n2: 101 3\n3: 2 5\n\n$`2`\n ID somevar\n1: 7 4\n2: 102 3\n3: 103 5\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,674,245
<p>this is the code I'm trying to implement for the dataset file and as I mentioned before the result just gives a 0 and the error :</p> <p><strong>RuntimeWarning: overflow encountered in exp predictions = 1 / (1 + np.exp(-predictions))</strong></p> <p>I tried many solutions for other codes related with this prediction but still the same</p> <pre><code>`import numpy as np import pandas as pd dataset = pd.read_csv('data.csv') dataset = (dataset - dataset.mean()) / dataset.std() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(dataset.iloc[:, :-1], dataset.iloc[:, -1], test_size=0.25, random_state=42) def logisticRegression_model(X, y, learning_rate, num_epochs): weights = np.zeros(X.shape[1]) for epoch in range(num_epochs): logisticRegression_update_weights(X, y, weights, learning_rate) return weights def logisticRegression_update_weights(X, y, weights, learning_rate): gradient = logisticRegression_calculate_gradient(X, y, weights) weights += learning_rate * gradient return weights def logisticRegression_calculate_gradient(X, y, weights): #calculating the predictions predictions = logisticRegression_predict(X, weights) #calculating the errors error = y - predictions gradient = np.dot(X.T, error) return gradient def logisticRegression_predict(X, weights): predictions = np.dot(X, weights) predictions = 1 / (1 + np.exp(-predictions)) return predictions def logisticRegression_accuracy(y_true, y_pred): accuracy = np.sum(y_true == y_pred) / len(y_true) return accuracy def logisticRegression_train(X_train, y_train, learning_rate, num_epochs): weights = logisticRegression_model(X_train, y_train, learning_rate, num_epochs) return weights weights = logisticRegression_train(X_train, y_train, 0.1, 1000) y_pred_train = logisticRegression_predict(X_train, weights) y_pred_test = logisticRegression_predict(X_test, weights) y_pred_train = (y_pred_train &gt; 0.5).astype(int) y_pred_test = (y_pred_test &gt; 0.5).astype(int) acc_train = logisticRegression_accuracy(y_train, y_pred_train) acc_test = logisticRegression_accuracy(y_test, y_pred_test) print('Train accuracy:', acc_train) print('Test accuracy:', acc_test)` </code></pre>
[ { "answer_id": 74674270, "author": "Ishan Kumar", "author_id": 11472268, "author_profile": "https://Stackoverflow.com/users/11472268", "pm_score": 1, "selected": false, "text": "import numpy as np\n\n# Define a large input value\nx = 1e100\n\n# Compute the exponential of the input value\ny = np.exp(x)\n\n# Print the result\nprint(y)\n\n inf\n import numpy as np\n\n# Define a large input value\nx = 1e100\n\n# Use the numpy.clip function to limit the input value\nx = np.clip(x, -np.inf, np.inf)\n\n# Compute the exponential of the input value\ny = np.exp(x)\n\n# Print the result\nprint(y)\n\n" }, { "answer_id": 74674800, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "inf nan 0 import numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(1/np.exp(999999999999))\n numpy.seterr(all='raise') \n print(1/np.exp(999999999999))\nFloatingPointError: overflow encountered in exp\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15165506/" ]
74,674,267
<p>I have 2 objects where I want the second one to be in the same order as the first one.</p> <p>Ex:</p> <pre><code>const obj1 = [ { key: 1, id: 1, name: &quot;John&quot; }, { key: 2, id: 2, name: &quot;Ann&quot; }, { key: 3, id: 3, name: &quot;Kate&quot; } ]; const obj2 = [ { key: 2, id: 2, name: &quot;Ann&quot; }, { key: 1, id: 1, name: &quot;John&quot; }, { key: 3, id: 3, name: &quot;Kate&quot; } ]; </code></pre> <p>The purpose is to have <code>obj2</code> in same order as <code>obj1</code>, but only sort with keys. I'm trying to make an helper function which will pass 3 argument:</p> <pre><code>function helper(obj1, obj2, key) { // return new object with sorted array do not modify existing } </code></pre> <p>I can sort one of this, but cant combine 2object together</p>
[ { "answer_id": 74674270, "author": "Ishan Kumar", "author_id": 11472268, "author_profile": "https://Stackoverflow.com/users/11472268", "pm_score": 1, "selected": false, "text": "import numpy as np\n\n# Define a large input value\nx = 1e100\n\n# Compute the exponential of the input value\ny = np.exp(x)\n\n# Print the result\nprint(y)\n\n inf\n import numpy as np\n\n# Define a large input value\nx = 1e100\n\n# Use the numpy.clip function to limit the input value\nx = np.clip(x, -np.inf, np.inf)\n\n# Compute the exponential of the input value\ny = np.exp(x)\n\n# Print the result\nprint(y)\n\n" }, { "answer_id": 74674800, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "inf nan 0 import numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(1/np.exp(999999999999))\n numpy.seterr(all='raise') \n print(1/np.exp(999999999999))\nFloatingPointError: overflow encountered in exp\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9832432/" ]
74,674,268
<p>I have written algorithm that solves the pluszle game matrix. Input is numpy array.</p> <p>Now I want to recognize the digits of matrix from screenshot. <a href="https://i.stack.imgur.com/WUmc7.jpg" rel="nofollow noreferrer">there are different levels, this is hard one</a></p> <p><a href="https://i.stack.imgur.com/s6z4G.png" rel="nofollow noreferrer">this is easy one</a></p> <p>the output of recognition should be numpy array</p> <pre><code>array([[6, 2, 4, 2], [7, 8, 9, 7], [1, 2, 4, 4], [7, 2, 4, 0]]) </code></pre> <p>I have tried to feed last image to tesseract</p> <pre><code>from PIL import Image import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' print(pytesseract.image_to_string(Image.open('C:/Users/79017/screen_plus.jpg'))) </code></pre> <p>The output is unacceptable</p> <pre><code>LEVEL 4 (}00:03 M0 J] —.°—@—@© </code></pre> <p>I think that I should use contours from opencv, because the font is always the same. maybe I should save contours for every digit, than save every countour that exist on screenshot than somehow make matrix from coordinates of every digit-contour. But I have no idea how to do it.</p>
[ { "answer_id": 74674861, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "(hard<240).any(axis=2) (hard>120).any(axis=2)\n (hard<240).any(axis=2) & (hard>120).any(axis=2)\n config='digits' pytesseract.image_to_string((hard>240).all(axis=2))\n# 'LEVEL10\\nNOVEMBER 2022\\n\\n™\\noe\\nOs\\nfoo)\\nso\\n‘|\\noO\\n\\n9949 6 2 2 8\\n\\nN W\\nN ©\\nOo w\\nVon\\n+? ah ®)\\nas\\noOo\\n©\\n\\n \\n\\x0c'\n\npytesseract.image_to_string((hard>240).all(axis=2), config='digits')\n# '10\\n2022\\n\\n99496228\\n\\n17\\n-\\n\\n \\n\\x0c'\n image_to_data image_to_boxes image_to_string image_to_data image_to_boxes image_to_string hard[740:1512, 132:910]\n print(pytesseract.image_to_boxes((hard[740:1512, 132:910]<240).any(axis=2), config='digits'))\n hard=hard[740:1512, 132:910]\nhard=(hard<240).any(axis=2)\nboxes=[s.split(' ') for s in pytesseract.image_to_boxes(hard, config='digits').split('\\n')[:-1]]\nout=255*np.stack([hard, hard, hard], axis=2).astype(np.uint8)\nH=len(hard)\nfor b in boxes:\n cv2.putText(out, b[0], (30+int(b[1]), H-int(b[2])), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 2)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18607862/" ]
74,674,289
<p>I would appreciate some help understanding the output of a small educational program I put together. I am new to OpenCV and don't have much C++ experience.</p> <p>The goal of the script is to perform the following:</p> <ul> <li>Load an image</li> <li>Perform DFT on the image</li> <li>Apply a circular binary mask to the spectrum, where the radius of the circle can be increased by hitting a key on the keyboard (essentially applying a very crude filter to the image)</li> <li>Display the result of the inverse transform of the spectrum after the mask was applied</li> </ul> <hr /> <p>I have the basic functionality working: I can load the image, perform DFT, view the output image and increase the radius of the circle (advancing through a for-loop with the circle radius following <code>i</code>), and see the result of the inverse transform of the modified spectrum.</p> <p>However I do not understand why the output is showing a vertically flipped copy of the input superimposed on the image (see example below with <code>Lena.png</code>). This is not my intended result. When I <code>imshow()</code> the inverse DFT result <em>without</em> applying the mask, I get a normal, non-doubled image. But after applying the mask, the IDFT output looks like this:</p> <p><a href="https://i.stack.imgur.com/FBUrx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FBUrx.png" alt="Output when normal &quot;Lena.png&quot; is given as input image" /></a></p> <p><strong>I am not looking for a quick solution: I would really appreciate if someone more experienced could ask leading questions to help me understand this result so that I can try to fix it myself.</strong></p> <hr /> <h4>My code:</h4> <pre class="lang-cpp prettyprint-override"><code>#include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui.hpp&gt; #include &lt;opencv2/imgcodecs.hpp&gt; #include &lt;opencv2/imgproc.hpp&gt; #include &lt;iostream&gt; using namespace cv; void expand_img_to_optimal(Mat &amp;padded, Mat &amp;img); void fourier_transform(Mat &amp;img); int main(int argc, char **argv) { Mat input_img; input_img = imread(&quot;Lena.png&quot; , IMREAD_GRAYSCALE); if (input_img.empty()) { fprintf(stderr, &quot;Could not Open image\n\n&quot;); return -1; } fourier_transform(input_img); return 0; } void fourier_transform(Mat &amp;img) { Mat padded; expand_img_to_optimal(padded, img); Mat planes[] = {Mat_&lt;float&gt;(padded), Mat::zeros(padded.size(), CV_32F)}; Mat complexI; merge(planes, 2, complexI); dft(complexI, complexI, DFT_COMPLEX_OUTPUT); // For-loop to increase mask circle radius incrementally for (int i=0; i&lt;400; i+=10) { Mat mask = Mat::ones(complexI.size(), complexI.type()); mask.convertTo(mask, CV_8U); Mat dest = Mat::ones(complexI.size(), complexI.type()); circle(mask, Point(mask.cols/2, mask.rows/2), i, 0, -1, 8, 0); complexI.copyTo(dest, mask); Mat inverseTransform; idft(dest, inverseTransform, DFT_INVERSE|DFT_REAL_OUTPUT); normalize(inverseTransform, inverseTransform, 0, 1, NORM_MINMAX); imshow(&quot;Reconstructed&quot;, inverseTransform); waitKey(0); } } void expand_img_to_optimal(Mat &amp;padded, Mat &amp;img) { int row = getOptimalDFTSize(img.rows); int col = getOptimalDFTSize(img.cols); copyMakeBorder(img, padded, 0, row - img.rows, 0, col - img.cols, BORDER_CONSTANT, Scalar::all(0)); } </code></pre>
[ { "answer_id": 74677413, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 2, "selected": false, "text": "mask.cols/2 mask.rows/2 ifftshift ifftshift ifftshift" }, { "answer_id": 74680367, "author": "avi", "author_id": 12872754, "author_profile": "https://Stackoverflow.com/users/12872754", "pm_score": 1, "selected": false, "text": "ifftshift Mat mask = Mat::ones(complexI.size(), complexI.type());\n complexI img Mat mask = Mat::ones(complexI.size(), img.type());\n #include <opencv2/core/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <iostream>\n\nusing namespace cv;\n\nvoid expand_img_to_optimal(Mat &padded, Mat &img);\nvoid fourier_transform(Mat &img);\nvoid ifft_shift(Mat &mask); \n\nint main(int argc, char **argv)\n{\n Mat input_img;\n input_img = imread(\"Lena.png\" , IMREAD_GRAYSCALE);\n\n if (input_img.empty())\n {\n fprintf(stderr, \"Could not Open image\\n\\n\");\n return -1;\n }\n\n fourier_transform(input_img);\n return 0;\n}\n\nvoid fourier_transform(Mat &img)\n{\n Mat padded;\n expand_img_to_optimal(padded, img);\n\n Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};\n Mat complexI;\n merge(planes, 2, complexI);\n\n dft(complexI, complexI, DFT_COMPLEX_OUTPUT);\n\n for (float i=0; i<4000; i+=2) {\n // Create disk mask matrix\n Mat mask = Mat::ones(complexI.size(), CV_8U);\n circle(mask, Point(mask.cols/2, mask.rows/2), i, 0, -1, 8, 0);\n\n // Perform ifft shift\n ifft_shift(mask);\n\n // Destination matrix for masked spectrum\n Mat dest;\n complexI.copyTo(dest, mask);\n\n // Perform inverse DFT\n Mat inverseTransform;\n idft(dest, inverseTransform, DFT_INVERSE|DFT_REAL_OUTPUT);\n normalize(inverseTransform, inverseTransform, 0, 1, NORM_MINMAX);\n imshow(\"Reconstructed\", inverseTransform);\n waitKey(0);\n }\n}\n\nvoid expand_img_to_optimal(Mat &padded, Mat &img) {\n int row = getOptimalDFTSize(img.rows);\n int col = getOptimalDFTSize(img.cols);\n copyMakeBorder(img, padded, 0, row - img.rows, 0, col - img.cols, BORDER_CONSTANT, Scalar::all(0));\n}\n\nvoid ifft_shift(Mat &mask) {\n // input sizes\n int sx = mask.cols;\n int sy = mask.rows;\n\n // input origin\n int cx = sx / 2;\n int cy = sy / 2;\n\n // split the quadrants\n Mat top_left(mask, Rect(0, 0, cx, cy));\n Mat top_right(mask, Rect(cx, 0, sx - cx, cy));\n Mat bottom_left(mask, Rect(0, cy, cx, sy - cy));\n Mat bottom_right(mask, Rect(cx, cy, sx - cx, sy - cy));\n\n // merge the quadrants in right order\n Mat tmp1, tmp2;\n hconcat(bottom_right, bottom_left, tmp1);\n hconcat(top_right, top_left, tmp2);\n vconcat(tmp1, tmp2, mask);\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12872754/" ]
74,674,297
<p><strong>Linux bash</strong>: why the two shell script as follow had different result?</p> <pre><code>[root@yumserver ~]# data=&quot;a,b,c&quot;;IFS=&quot;,&quot;;for i in $data;do echo $i;done a b c [root@yumserver ~]# IFS=&quot;,&quot;;for i in a,b,c;do echo $i;done a b c </code></pre> <p>expect output: the second script also output:</p> <pre><code>a b c </code></pre> <p>I should understood what @M.NejatAydin means。Thanks also @EdMorton,@HaimCohen!</p> <pre><code>[root@k8smaster01 ~]# set -x;data=&quot;a,b,c&quot;;IFS=&quot;,&quot;;echo $data;echo &quot;$data&quot;;for i in $data;do echo $i;done + data=a,b,c + IFS=, + echo a b c a b c + echo a,b,c a,b,c + for i in '$data' + echo a a + for i in '$data' + echo b b + for i in '$data' + echo c c [root@k8smaster01 ~]# IFS=&quot;,&quot;;for i in a,b,c;do echo $i;done + IFS=, + for i in a,b,c + echo a b c a b c </code></pre>
[ { "answer_id": 74674452, "author": "arkascha", "author_id": 1248114, "author_profile": "https://Stackoverflow.com/users/1248114", "pm_score": 2, "selected": false, "text": "IFS=\",\";for i in ${var=\"a,b,c\"};do echo $i;done\n" }, { "answer_id": 74674566, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 3, "selected": true, "text": "a,b,c for $i echo $i IFS IFS read" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680709/" ]
74,674,308
<p>I found something in my search, which I don't understand. The goal is to read out the angle of a pointer in a pressure gauge. In my research, I found this example:</p> <p><a href="https://circuits-ninja.pl/reading-an-indication-from-an-analog-pressure-gauge-using-the-esp32-cam-module-with-an-ov2640-and-opencv-camera/" rel="nofollow noreferrer">https://circuits-ninja.pl/reading-an-indication-from-an-analog-pressure-gauge-using-the-esp32-cam-module-with-an-ov2640-and-opencv-camera/</a></p> <p>He's calculating the degree as follows:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code># Finding angle using the arc tan of y/x res = np.arctan(np.divide(float(y_angle), float(x_angle))) #Converting to degrees res = np.rad2deg(res) if x_angle &gt; 0 and y_angle &gt; 0: #in quadrant I final_angle = 270 - res if x_angle &lt; 0 and y_angle &gt; 0: #in quadrant II final_angle = 90 - res if x_angle &lt; 0 and y_angle &lt; 0: #in quadrant III final_angle = 90 - res if x_angle &gt; 0 and y_angle &lt; 0: #in quadrant IV final_angle = 270 - res</code></pre> </div> </div> </p> <p>I understand the reason of using quadrants in this case, but what i don't understand is why does he calculate 270 - res if x_angle and y_angle &gt; 0 and also calculate 270 - res if x_angle &gt; 0 and y_angle &lt; 0. He's using the same formula for two different quadrants?</p> <p>Thanks in forward</p>
[ { "answer_id": 74674452, "author": "arkascha", "author_id": 1248114, "author_profile": "https://Stackoverflow.com/users/1248114", "pm_score": 2, "selected": false, "text": "IFS=\",\";for i in ${var=\"a,b,c\"};do echo $i;done\n" }, { "answer_id": 74674566, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 3, "selected": true, "text": "a,b,c for $i echo $i IFS IFS read" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20136915/" ]
74,674,328
<p>I'm trying to reverse a string. I use the solution of <a href="https://stackoverflow.com/questions/27996430/reversing-a-string-in-rust">this post</a> and it works.</p> <p>But I would like to try with bytes instead of grapheme clusters as shown below:</p> <pre class="lang-rust prettyprint-override"><code>pub fn reverse2(input: &amp;str) -&gt; String { let s: String = input .as_bytes() .iter() .rev() .collect(); return s; } </code></pre> <p>Unfortunately, I can't run the function <code>collect()</code> after <code>rev()</code>. I don't know which method to use. How would you do it ?</p>
[ { "answer_id": 74674343, "author": "Haim Cohen", "author_id": 3752715, "author_profile": "https://Stackoverflow.com/users/3752715", "pm_score": 0, "selected": false, "text": ".chars() .collect() pub fn reverse2(input: &str) -> String {\n let s: String = input\n .chars()\n .rev()\n .collect();\n return s;\n}\n" }, { "answer_id": 74674671, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 1, "selected": false, "text": "chars() pub fn reverse2(input: &str) -> String {\n // Reversing on byte-level only works with ASCII strings.\n assert!(input.is_ascii());\n\n let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect();\n let reversed_string = unsafe {\n // SAFETY: This is guaranteed to be a valid UTF8 string, because:\n // - the input string is a valid ASCII string\n // - a reversed ASCII string is still a valid ASCII string\n // - an ASCII string is a valid UTF8 string\n String::from_utf8_unchecked(reversed_bytes)\n };\n\n return reversed_string;\n}\n unsafe pub fn reverse2(input: &str) -> String {\n // Reversing on byte-level only works with ASCII strings.\n assert!(input.is_ascii());\n\n let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect();\n let reversed_string = String::from_utf8(reversed_bytes).unwrap();\n\n return reversed_string;\n}\n is_ascii() 128 128 pub fn reverse2(input: &str) -> String {\n let reversed_bytes: Vec<u8> = input\n .as_bytes()\n .iter()\n .rev()\n .map(|&val| {\n if val < 128 {\n val\n } else {\n 0x1a // replacement char\n }\n })\n .collect();\n\n let reversed_string = unsafe {\n // SAFETY: This is guaranteed to be a valid UTF8 string, because:\n // - `reversed_bytes` is guaranteed to be an ASCII string\n // - an ASCII string is a valid UTF8 string\n String::from_utf8_unchecked(reversed_bytes)\n };\n\n return reversed_string;\n}\n\nfn main() {\n let s = \"abcdefghij\";\n println!(\"{:?}\", s.as_bytes());\n\n let reversed = reverse2(s);\n println!(\"{}\", reversed);\n println!(\"{:?}\", reversed.as_bytes());\n}\n [97, 98, 99, 100, 101, 240, 159, 152, 131, 102, 103, 104, 105, 106]\njihgfedcba\n[106, 105, 104, 103, 102, 26, 26, 26, 26, 101, 100, 99, 98, 97]\n .bytes() .as_bytes().iter()" }, { "answer_id": 74675542, "author": "Miiao", "author_id": 20028181, "author_profile": "https://Stackoverflow.com/users/20028181", "pm_score": 0, "selected": false, "text": ".bytes() .as_bytes().iter() &str .chars() .bytes() return pub fn reverse2(input: &str) -> String {\n input.chars()\n .rev()\n .collect()\n}\n" }, { "answer_id": 74679514, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 0, "selected": false, "text": "input reverse Vec pub fn reverse2(input: &str) -> String {\n let v = &mut input.to_string().into_bytes();\n v.reverse();\n std::str::from_utf8(v).unwrap().to_string()\n}\n input" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14553818/" ]
74,674,411
<p>I have the following vector called <code>input</code>:</p> <pre><code>input &lt;- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2) [1] 1 2 1 NA 3 2 NA 1 5 6 NA 2 2 </code></pre> <p>I would like to split this vector into multiple vectors by each NA. So the desired output should look like this:</p> <pre><code>&gt; output [[1]] [1] 1 2 1 [[2]] [1] 3 2 [[3]] [1] 1 5 6 [[4]] [1] 2 2 </code></pre> <p>As you can see every time a <code>NA</code> appears, it splits into a new vector. So I was wondering if anyone knows how to split a vector by each <code>NA</code> into multiple vectors?</p>
[ { "answer_id": 74674509, "author": "tpetzoldt", "author_id": 3677576, "author_profile": "https://Stackoverflow.com/users/3677576", "pm_score": 3, "selected": false, "text": "NA cumsum NA input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)\ntmp <- cumsum(is.na(input))\nlapply(split(input, tmp), na.omit)\n" }, { "answer_id": 74674545, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 4, "selected": true, "text": "split(na.omit(input), cumsum(is.na(input))[!is.na(input)])\n\n$`0`\n[1] 1 2 1\n\n$`1`\n[1] 3 2\n\n$`2`\n[1] 1 5 6\n\n$`3`\n[1] 2 2\n" }, { "answer_id": 74674852, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ntibble(input) %>% \n group_by(id = cumsum(is.na(input))) %>% \n na.omit %>% \n group_split() %>% \n map(.,~(.x %>%select(-id))) %>% \n map(.,~(.x %>%pull))\n\n [[1]]\n[1] 1 2 1\n\n[[2]]\n[1] 3 2\n\n[[3]]\n[1] 1 5 6\n\n[[4]]\n[1] 2 2\n" }, { "answer_id": 74675846, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "strsplit(paste(input, collapse = \" \"), \" NA \")\n[[1]]\n[1] \"1 2 1\" \"3 2\" \"1 5 6\" \"2 2\" \n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14282714/" ]
74,674,421
<p>I have a txt file that updates with new data every few seconds. It is stored and generated locally on a raspberry pi, which will also act as the server.</p> <p>I want its contents to be added to and html code for displaying.</p> <p>It should update without manual reloading of the page.</p> <p>Is there a way to do this? Maybe with AJAX, PHP, or something along those lines?</p> <p>Don't have to find/write any code for me, as I understand that it would be rather time consuming. just point me in the right direction so I can learn how to do it.</p>
[ { "answer_id": 74674509, "author": "tpetzoldt", "author_id": 3677576, "author_profile": "https://Stackoverflow.com/users/3677576", "pm_score": 3, "selected": false, "text": "NA cumsum NA input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)\ntmp <- cumsum(is.na(input))\nlapply(split(input, tmp), na.omit)\n" }, { "answer_id": 74674545, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 4, "selected": true, "text": "split(na.omit(input), cumsum(is.na(input))[!is.na(input)])\n\n$`0`\n[1] 1 2 1\n\n$`1`\n[1] 3 2\n\n$`2`\n[1] 1 5 6\n\n$`3`\n[1] 2 2\n" }, { "answer_id": 74674852, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ntibble(input) %>% \n group_by(id = cumsum(is.na(input))) %>% \n na.omit %>% \n group_split() %>% \n map(.,~(.x %>%select(-id))) %>% \n map(.,~(.x %>%pull))\n\n [[1]]\n[1] 1 2 1\n\n[[2]]\n[1] 3 2\n\n[[3]]\n[1] 1 5 6\n\n[[4]]\n[1] 2 2\n" }, { "answer_id": 74675846, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "strsplit(paste(input, collapse = \" \"), \" NA \")\n[[1]]\n[1] \"1 2 1\" \"3 2\" \"1 5 6\" \"2 2\" \n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17333122/" ]
74,674,440
<p>I want to send a data object with fetch api with keepalive to the current page and get the data through php. how can I do it.</p> <p>Data To Send</p> <pre><code>{ name: 'blabla', age: 432, type: 'pig' } </code></pre> <p>I want to recieve as a post variable</p> <pre><code>$_POST['name']; </code></pre> <p>I've tried this but it is not working</p> <pre><code>fetch('', { method: 'POST', body: {name: 'blabla'}, keepalive: true }); </code></pre> <p>Sorry for no code</p>
[ { "answer_id": 74674509, "author": "tpetzoldt", "author_id": 3677576, "author_profile": "https://Stackoverflow.com/users/3677576", "pm_score": 3, "selected": false, "text": "NA cumsum NA input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)\ntmp <- cumsum(is.na(input))\nlapply(split(input, tmp), na.omit)\n" }, { "answer_id": 74674545, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 4, "selected": true, "text": "split(na.omit(input), cumsum(is.na(input))[!is.na(input)])\n\n$`0`\n[1] 1 2 1\n\n$`1`\n[1] 3 2\n\n$`2`\n[1] 1 5 6\n\n$`3`\n[1] 2 2\n" }, { "answer_id": 74674852, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ntibble(input) %>% \n group_by(id = cumsum(is.na(input))) %>% \n na.omit %>% \n group_split() %>% \n map(.,~(.x %>%select(-id))) %>% \n map(.,~(.x %>%pull))\n\n [[1]]\n[1] 1 2 1\n\n[[2]]\n[1] 3 2\n\n[[3]]\n[1] 1 5 6\n\n[[4]]\n[1] 2 2\n" }, { "answer_id": 74675846, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "strsplit(paste(input, collapse = \" \"), \" NA \")\n[[1]]\n[1] \"1 2 1\" \"3 2\" \"1 5 6\" \"2 2\" \n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680889/" ]
74,674,513
<p>I'm new to springboot and fiddling around with DI.</p> <p>I'm having a Service</p> <pre><code>public class GreeterService { private ObjectMapper objectMapper; public GreeterService(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public String greeting() throws JsonProcessingException { return objectMapper.writeValueAsString(new HelloData()); } } </code></pre> <p>this Service is supposed to be created via <code>@Configuration</code></p> <pre><code>@Configuration public class Config { @Bean public GreeterService greeterService(@Autowired ObjectMapper objectMapper) { return new GreeterService(objectMapper); } } </code></pre> <p>I get the following exception:</p> <pre><code>java.lang.NullPointerException: Cannot invoke &quot;com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)&quot; because &quot;this.objectMapper&quot; is null </code></pre> <p>also making ObjectMapper <code>@Autowired</code> on a field does not work e.g.</p> <pre><code> @Autowired ObjectMapper objectMapper; @Bean public GreeterService greeterService() { return new GreeterService(objectMapper); } </code></pre> <p>main entry in com.example.demo</p> <pre><code>@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } </code></pre> <p>Controller</p> <pre><code> @GetMapping(path = &quot;methodInject&quot;) public Object methodInject(GreeterService greeterService) throws JsonProcessingException { return greeterService.greeting(); } </code></pre> <p>Further info:</p> <p>I added to main</p> <pre><code>System.out.println(&quot;Is &quot; + beanName + &quot; in ApplicationContext: &quot; + context.containsBean(beanName)); </code></pre> <p>which returns:</p> <pre><code>Is objectMapper in ApplicationContext: true Is greeterService in ApplicationContext: true </code></pre>
[ { "answer_id": 74674509, "author": "tpetzoldt", "author_id": 3677576, "author_profile": "https://Stackoverflow.com/users/3677576", "pm_score": 3, "selected": false, "text": "NA cumsum NA input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)\ntmp <- cumsum(is.na(input))\nlapply(split(input, tmp), na.omit)\n" }, { "answer_id": 74674545, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 4, "selected": true, "text": "split(na.omit(input), cumsum(is.na(input))[!is.na(input)])\n\n$`0`\n[1] 1 2 1\n\n$`1`\n[1] 3 2\n\n$`2`\n[1] 1 5 6\n\n$`3`\n[1] 2 2\n" }, { "answer_id": 74674852, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ntibble(input) %>% \n group_by(id = cumsum(is.na(input))) %>% \n na.omit %>% \n group_split() %>% \n map(.,~(.x %>%select(-id))) %>% \n map(.,~(.x %>%pull))\n\n [[1]]\n[1] 1 2 1\n\n[[2]]\n[1] 3 2\n\n[[3]]\n[1] 1 5 6\n\n[[4]]\n[1] 2 2\n" }, { "answer_id": 74675846, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "strsplit(paste(input, collapse = \" \"), \" NA \")\n[[1]]\n[1] \"1 2 1\" \"3 2\" \"1 5 6\" \"2 2\" \n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877383/" ]
74,674,559
<p>i need to truncate portions of a string that are found between a regex pattern.</p> <ul> <li>if a portion length is <code>&lt;=</code> to the given padding, leave the portion as it is.</li> <li>the starting portion should be truncated from the left.</li> <li>the ending portion should be truncated from the right.</li> <li>the portions in between should be truncated in the middle.</li> <li>if no pattern found, leave the string untouched</li> </ul> <p>code:</p> <pre class="lang-js prettyprint-override"><code>// note that the 'x' characters below could be any characters, even spaces or line breaks. const str = 'xxxxx&lt;mark&gt;foo&lt;/mark&gt;xx&lt;mark&gt;bar&lt;/mark&gt;xxxxxxxxx&lt;mark&gt;baz&lt;/mark&gt;xxxxxxxx' const truncateBetweenPattern = (str, pattern, padding=0, sep='...') =&gt; { // code } const pattern = '(&lt;mark&gt;.+&lt;/mark&gt;)' // (not sure if this is valid) const result = truncateBetweenPattern(str, pattern, 3) </code></pre> <p>output:</p> <pre class="lang-js prettyprint-override"><code>result === '...xxx&lt;mark&gt;foo&lt;/mark&gt;xx&lt;mark&gt;bar&lt;/mark&gt;xxx...xxx&lt;mark&gt;baz&lt;/mark&gt;xxx...' </code></pre>
[ { "answer_id": 74674607, "author": "Isfan Bogdan", "author_id": 2915547, "author_profile": "https://Stackoverflow.com/users/2915547", "pm_score": 0, "selected": false, "text": "const truncateBetweenPattern = (str, pattern, padding=0, sep='...') => {\n const regex = new RegExp(pattern, 'g');\n let result = '';\n let match;\n\n while ((match = regex.exec(str)) !== null) {\n // Truncate the left portion of the match if needed.\n const left = match.index;\n if (left > padding) {\n result += str.slice(0, left - padding) + sep;\n } else {\n result += str.slice(0, left);\n }\n\n // Truncate the middle portion of the match if needed.\n const middle = match[0].length;\n if (middle > padding * 2) {\n result += str.slice(left, left + padding) + sep + str.slice(left + middle - padding);\n } else {\n result += match[0];\n }\n\n // Truncate the right portion of the match if needed.\n const right = str.length - regex.lastIndex;\n if (right > padding) {\n result += sep + str.slice(regex.lastIndex, regex.lastIndex + padding);\n } else {\n result += str.slice(regex.lastIndex);\n }\n\n // Update the string for the next iteration.\n str = str.slice(regex.lastIndex);\n }\n\n return result;\n}\n const str = 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx';\nconst pattern = '(<mark>.+</mark>)';\nconst result = truncateBetweenPattern(str, pattern, 3);\n\nconsole.log(result);\n xxx<mark>foo</mark>x...<mark>ba...z</mark>...\n" }, { "answer_id": 74675305, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "mark const truncateBetweenPattern = (str, pattern, padding=0, sep='...') => {\n const re = [\n RegExp(`^().+?(.{${padding}})$`, \"s\"),\n RegExp(`^(.{${padding}}).+?(.{${padding}})$`, \"s\"),\n RegExp(`^(.{${padding}}).+?()$`, \"s\")\n ];\n const parts = str.split(RegExp(`(${pattern})`, \"s\"));\n return parts.length < 2 ? str\n : parts.map((part, i, {length}) =>\n i % 2 ? part : part.replace(re[(i > 0) + (i == length - 1)], `$1${sep}$2`)\n ).join(\"\");\n}\n\nconst pattern = '<mark>.+?</mark>'; // Make \"+\" lazy\nconst str = 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx'\nconst result = truncateBetweenPattern(str, pattern, 3);\nconsole.log(result);" }, { "answer_id": 74677296, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "<mark>....</mark> </mark>....</mark> <mark> const regex = /(<mark>[^]*?<\\/mark>)|(?<=<\\/mark>)([^]*?)(?=<mark>)|([^]*?)(?=<mark>)|(?<=<\\/mark>)([^]*)/g;\n\nconst truncateBetweenPattern = (str, pattern, padding = 0, sep = '...') => {\n if (padding <= 0) return str;\n\n return str.replace(regex, (m, g1, g2, g3, g4) => {\n if (g1) return g1;\n else if (g2 && g2.length > padding * 2) {\n return g2.slice(0, padding) + sep + g2.slice(-padding);\n } else if (g3 && g3.length > padding) {\n return sep + g3.slice(-padding);\n } else if (g4 && g4.length > padding) {\n return g4.slice(0, padding) + sep;\n } else return m;\n })\n}\n\nconst strings = [\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxx<mark>baz</mark>xxxxxxxx',\n 'xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxxxxxxxxxxxxx<mark>baz</mark>xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxxxxxxxxxxxxx<mark>baz</mark>'\n];\n\nstrings.forEach(s => console.log(truncateBetweenPattern(s, regex, 3)));" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428445/" ]
74,674,599
<p>I'm trying to run a python file that imports a module using other modules in the grandparent folder. The file structure is:</p> <pre><code>directory_0 | directory_1 | | | directory_2 | | | __init__.py (define the method A and import another method B from file_2.py) | | | file_1.py | directory_3 | file_2.py (define the method B) </code></pre> <p>I want to run <code>file_1.py</code> that <em>imports method A</em> defined in <code>__init__.py</code>, and <code>__init__.py</code> it <em>imports method B from file_2.py</em>. I'm currently at <code>/directory_0/directory_1/directory_2</code> to run the command <code>python file_1.py</code>. It throws <code>ModuleNotFoundError: No module named directory_3.file_2</code> How to make it run? and which path should I go to run this script (file_1.py).</p>
[ { "answer_id": 74674607, "author": "Isfan Bogdan", "author_id": 2915547, "author_profile": "https://Stackoverflow.com/users/2915547", "pm_score": 0, "selected": false, "text": "const truncateBetweenPattern = (str, pattern, padding=0, sep='...') => {\n const regex = new RegExp(pattern, 'g');\n let result = '';\n let match;\n\n while ((match = regex.exec(str)) !== null) {\n // Truncate the left portion of the match if needed.\n const left = match.index;\n if (left > padding) {\n result += str.slice(0, left - padding) + sep;\n } else {\n result += str.slice(0, left);\n }\n\n // Truncate the middle portion of the match if needed.\n const middle = match[0].length;\n if (middle > padding * 2) {\n result += str.slice(left, left + padding) + sep + str.slice(left + middle - padding);\n } else {\n result += match[0];\n }\n\n // Truncate the right portion of the match if needed.\n const right = str.length - regex.lastIndex;\n if (right > padding) {\n result += sep + str.slice(regex.lastIndex, regex.lastIndex + padding);\n } else {\n result += str.slice(regex.lastIndex);\n }\n\n // Update the string for the next iteration.\n str = str.slice(regex.lastIndex);\n }\n\n return result;\n}\n const str = 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx';\nconst pattern = '(<mark>.+</mark>)';\nconst result = truncateBetweenPattern(str, pattern, 3);\n\nconsole.log(result);\n xxx<mark>foo</mark>x...<mark>ba...z</mark>...\n" }, { "answer_id": 74675305, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 2, "selected": false, "text": "mark const truncateBetweenPattern = (str, pattern, padding=0, sep='...') => {\n const re = [\n RegExp(`^().+?(.{${padding}})$`, \"s\"),\n RegExp(`^(.{${padding}}).+?(.{${padding}})$`, \"s\"),\n RegExp(`^(.{${padding}}).+?()$`, \"s\")\n ];\n const parts = str.split(RegExp(`(${pattern})`, \"s\"));\n return parts.length < 2 ? str\n : parts.map((part, i, {length}) =>\n i % 2 ? part : part.replace(re[(i > 0) + (i == length - 1)], `$1${sep}$2`)\n ).join(\"\");\n}\n\nconst pattern = '<mark>.+?</mark>'; // Make \"+\" lazy\nconst str = 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx'\nconst result = truncateBetweenPattern(str, pattern, 3);\nconsole.log(result);" }, { "answer_id": 74677296, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "<mark>....</mark> </mark>....</mark> <mark> const regex = /(<mark>[^]*?<\\/mark>)|(?<=<\\/mark>)([^]*?)(?=<mark>)|([^]*?)(?=<mark>)|(?<=<\\/mark>)([^]*)/g;\n\nconst truncateBetweenPattern = (str, pattern, padding = 0, sep = '...') => {\n if (padding <= 0) return str;\n\n return str.replace(regex, (m, g1, g2, g3, g4) => {\n if (g1) return g1;\n else if (g2 && g2.length > padding * 2) {\n return g2.slice(0, padding) + sep + g2.slice(-padding);\n } else if (g3 && g3.length > padding) {\n return sep + g3.slice(-padding);\n } else if (g4 && g4.length > padding) {\n return g4.slice(0, padding) + sep;\n } else return m;\n })\n}\n\nconst strings = [\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xxxxx<mark>foo</mark>xx<mark>bar</mark>xxxxxx<mark>baz</mark>xxxxxxxx',\n 'xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxx<mark>baz</mark>xxxxxxxx',\n 'xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxxxxxxxxxxxxx<mark>baz</mark>xx<mark>foo</mark>xx<mark>bar</mark>xxxxxxxxxxxxxxxxxxxx<mark>baz</mark>'\n];\n\nstrings.forEach(s => console.log(truncateBetweenPattern(s, regex, 3)));" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6760729/" ]
74,674,601
<p><a href="https://stackoverflow.com/a/7486111/17273668">https://stackoverflow.com/a/7486111/17273668</a> ; from what I have seen here to make a class &quot;static&quot; , we have to make it final with private constructor and static fields and methods.</p> <p>Is there any difference between making the constructor private and making the class abstract?</p>
[ { "answer_id": 74674652, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": false, "text": "abstract Optional.of" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17273668/" ]
74,674,604
<p>I use fetch() to print labels. There are some scenario when I need to loop through the data and print multiple labels. The printing it's working fine, but after the first loop the script stop running.</p> <p>I use async function in order to slow down a printing.</p> <pre><code>async function printing() { for (let w = 0; w &lt; print_labels.length; w++) { const label = `data of the label` fetch('http://111.111.1.111:9100', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: label }) console.log(`${w}. label printed.`) await sleep(2000); } }; printing() </code></pre> <p>Ho can I cancel/stop the fetch() function? Or maybe any other solution how to use fetch() post in for loop?</p>
[ { "answer_id": 74674652, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": false, "text": "abstract Optional.of" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11117759/" ]
74,674,611
<p>I just finished implementing a working Python code for the Dijkstra-Pathfinding algorithm. I am applying this algorithm to a graph with edges, which I have written as a list of tuples:</p> <pre><code>graph = Graph([ (&quot;a&quot;, &quot;b&quot;, 2),(&quot;a&quot;, &quot;c&quot;, 5), (&quot;a&quot;, &quot;d&quot;, 2),(&quot;b&quot;, &quot;c&quot;, 3), (&quot;b&quot;, &quot;e&quot;, 1),(&quot;c&quot;, &quot;e&quot;, 1), (&quot;c&quot;, &quot;h&quot;, 1),(&quot;c&quot;, &quot;f&quot;, 1), (&quot;c&quot;, &quot;d&quot;, 3),(&quot;d&quot;, &quot;g&quot;, 2), (&quot;e&quot;, &quot;i&quot;, 7),(&quot;f&quot;, &quot;h&quot;, 3), (&quot;f&quot;, &quot;g&quot;, 2),(&quot;h&quot;, &quot;i&quot;, 1)]) </code></pre> <p>I don't want to leave it like that and rather fill the graph using a for-loop, but this is exactly where I fail.</p> <p>I have tried writing</p> <pre><code>graph.append((&quot;i&quot;, &quot;j&quot;, &quot;4&quot;)) </code></pre> <p>And several other variants using the append function but it just keeps giving me errors. I am aware that this isn't a for-loop, I am simply trying to add one edge for now.</p> <p>This is how I defined my add_edge function:</p> <pre><code>Edge = namedtuple('Edge', 'start, end, cost') def add_edge(start, end, cost): return Edge(start, end, cost) </code></pre>
[ { "answer_id": 74674652, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": false, "text": "abstract Optional.of" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681092/" ]
74,674,629
<pre class="lang-py prettyprint-override"><code>n=int(input(&quot;Enter a number: &quot;)) p=1 for i in range(n): p*=i print(p) </code></pre> <p>I wanted to find out the factorial of a number but I always get 0 as output.</p>
[ { "answer_id": 74674652, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": false, "text": "abstract Optional.of" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675377/" ]
74,674,649
<p>I'm writing a programme that converts complex numbers. Right now I'm having problems with this piece of code:</p> <pre><code>import numpy complexnr = 1+1j mod= numpy.absolute(complexnr) print(mod) </code></pre> <p>The output of this code is:</p> <pre><code>1.4142135623730951 </code></pre> <p>I would like to get √2 as the output.</p> <p>I have been advised to use the sympy module but I have had no luck with this either. What would be the easiest way to get this result?</p> <p>EDIT</p> <pre><code>input_list = [&quot;Enter your complex number (a+bi): &quot;, \ &quot;Degrees or radians?&quot;, \ &quot;To how many decimal places do you want to round the argument?&quot;] output = multenterbox(text, title, input_list) algebraline = output[0] choice = output[1] round2 = int(output[2]) #converting complex number to a suitable form for numpy if &quot;i&quot; in algebraline: j = algebraline.replace(&quot;i&quot;,&quot;j&quot;) indeks = algebraline.index(&quot;i&quot;) list = [] for element in algebraline: list.append(element) if &quot;i&quot; in algebraline and algebraline[indeks-1]==&quot;+&quot; or algebraline[indeks-1]==&quot;-&quot;: list.insert(indeks, 1) x = &quot;&quot;.join(str(e) for e in list) j = x.replace(&quot;i&quot;,&quot;j&quot;) arv = eval(j) elif &quot;i&quot; not in algebraline: arv = eval(algebraline) #let's find the module a = int(list[0]) b = int(list[2]) module = sqrt(a**2+b**2) </code></pre> <p>this method works well when the complex number is 1+i for example, however when i try to insert sqrt(3)-1i, the list looks like this ['s', 'q', 'r', 't', '(', '3', ')', '-', 1, 'i'] and my programme won't work. Same problem occurs when b is a root (for example 1-sqrt(3)i). What can be done to make it work for square roots as well? (I need numpy later on to calculate angles, that's why converting 'i' into 'j' is important)</p>
[ { "answer_id": 74674992, "author": "Davide_sd", "author_id": 2329968, "author_profile": "https://Stackoverflow.com/users/2329968", "pm_score": 0, "selected": false, "text": "from sympy import *\ncabs = lambda z: sqrt(re(z)**2 + im(z)**2)\ncomplexnr = 1 + 1j\nprint(cabs(complexnr))\n# out: 1.4142135623731\n complexnr complex float re im sqrt sympify complexnr = sympify(\"1 + 1j\")\nprint(cabs(complexnr))\n# out: sqrt(2)\n nsimplify complexnr = 1 + 1j\nresult = cabs(complexnr) # result is a Float number, 1.4142135623731\nprint(result.nsimplify())\n# out: sqrt(2)\n" }, { "answer_id": 74675174, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 1, "selected": false, "text": "from sympy import I\n\ncomplexnr = 1 + I # use I rather than 1j\nprint(abs(complexnr)) # also works with np.abs and np.absolute\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20396924/" ]
74,674,654
<p>I have a dataframe such as :</p> <pre><code>Names1 Gene_name Status SP1 GENE1 0 SP1 GENE1 1 SP1 GENE1 1 SP1 GENE1 2 SP1 GENE1 2 SP1 GENE2 0 SP3 GENE2 0 SP1 GENE2 1 SP2 GENE2 2 SP4 GENE3 1 SP4 GENE3 2 SP5 GENE3 0 SP5 GENE3 0 </code></pre> <p>Then I would like to fill a new dataframe where each <code>Gene_name</code> is a column, and each <code>Names</code> is a row :</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 SP2 SP3 SP4 SP5 </code></pre> <p>and fill cells <code>Values</code> depending on the <code>Satus</code> for each <code>Names</code> groups</p> <ul> <li>if only 0 &gt; value = 0</li> <li>if only 1 &gt; value = 1</li> <li>if both 0 &amp; 1 &gt; value = 0-1</li> <li>if both 0 &amp; 2 &gt; value = 0-2</li> <li>if both 1 &amp; 2 &gt; value = 1-2</li> <li>if both 0 &amp; 1 &amp; 2 &gt; value = 0-1-2</li> </ul> <p>So for example <code>GENE1</code> in <code>SP1</code> both present a 0,1 and 2 status, so I fill <code>0-1-2</code> within the cell:</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 SP2 SP3 SP4 SP5 </code></pre> <p>then, <code>SP2,SP3,SP4 and SP5</code> do not have value for the <code>GENE1</code>, so I put <code>NA</code> :</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 SP2 NA SP3 NA SP4 NA SP5 NA </code></pre> <hr /> <p>Then for the <code>GENE2:</code></p> <p><code>GENE2</code> in <code>SP1</code> both present a 0 and 1 status, so I fill <code>0-1</code> within the cell:</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 0-1 SP2 NA SP3 NA SP4 NA SP5 NA </code></pre> <p><code>GENE2</code> in <code>SP2</code> present only a value 2 status, so I fill <code>2</code> within the cell:</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 0-1 SP2 NA 2 SP3 NA SP4 NA SP5 NA </code></pre> <p><code>GENE2</code> in <code>SP3</code> present only a value 0 status, so I fill <code>0</code> within the cell:</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 0-1 SP2 NA 2 SP3 NA 0 SP4 NA SP5 NA </code></pre> <p>and the other Names have no <code>GENE2</code> values, so I put <code>NA</code>:</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 0-1 SP2 NA 2 SP3 NA 0 SP4 NA NA SP5 NA NA </code></pre> <p>and so on... At the end I should get a full dataframe such as :</p> <pre><code>Names GENE1 GENE2 GENE3 SP1 0-1-2 0-1 NA SP2 NA 2 NA SP3 NA 0 NA SP4 NA NA 0-2 SP5 NA NA 0 </code></pre> <p>Does someone have an idea please ?</p> <p>Here is the dict format of the dataframe if it can helps :</p> <pre><code>{'Names1': {0: 'SP1', 1: 'SP1', 2: 'SP1', 3: 'SP1', 4: 'SP1', 5: 'SP1', 6: 'SP3', 7: 'SP1', 8: 'SP2', 9: 'SP4', 10: 'SP4', 11: 'SP5', 12: 'SP5'}, 'Gene_name': {0: 'GENE1', 1: 'GENE1', 2: 'GENE1', 3: 'GENE1', 4: 'GENE1', 5: 'GENE2', 6: 'GENE2', 7: 'GENE2', 8: 'GENE2', 9: 'GENE3', 10: 'GENE3', 11: 'GENE3', 12: 'GENE3'}, 'Status': {0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 0, 6: 0, 7: 1, 8: 2, 9: 1, 10: 2, 11: 0, 12: 0}} </code></pre>
[ { "answer_id": 74674826, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 3, "selected": true, "text": "g = df.groupby(['Names1', 'Gene_name'])\ng['Status'].agg(lambda x: '-'.join(x.astype('str').sort_values().unique())).unstack()\n Gene_name GENE1 GENE2 GENE3\nNames1 \nSP1 0-1-2 0-1 NaN\nSP2 NaN 2 NaN\nSP3 NaN 0 NaN\nSP4 NaN NaN 1-2\nSP5 NaN NaN 0\n (g['Status'].agg(lambda x: '-'.join(x.astype('str').sort_values().unique()))\n .unstack().rename_axis(index='Name', columns=''))\n GENE1 GENE2 GENE3\nName \nSP1 0-1-2 0-1 NaN\nSP2 NaN 2 NaN\nSP3 NaN 0 NaN\nSP4 NaN NaN 1-2\nSP5 NaN NaN 0\n" }, { "answer_id": 74674929, "author": "ChaoS Adm", "author_id": 12575770, "author_profile": "https://Stackoverflow.com/users/12575770", "pm_score": 1, "selected": false, "text": "import numpy as np\n\nnames = df['Names1'].unique() \ngenes = df['Gene_name'].unique() \nresult_df = pd.DataFrame({'Names': names}) \n\nfor gene in genes: \n values = []\n for name in names: \n result = '-'.join(map(str, count_df.loc[(count_df['Names1'] == name) & (count_df['Gene_name'] == gene), ['Status']]['Status'].to_numpy()))\n if result == '':\n values.append(np.nan) \n else:\n values.append(result) \n\n result_df[gene] = values \n\nresult_df \n GENE1 GENE2 GENE3\nNames \nSP1 0-1-2 0-1 NaN\nSP2 NaN 2 NaN\nSP3 NaN 0 NaN\nSP4 NaN NaN 1-2\nSP5 NaN NaN 0\n" }, { "answer_id": 74675252, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 0, "selected": false, "text": "df.pivot_table('Status','Names1','Gene_name',\n aggfunc=lambda x: '-'.join(x.astype(str).unique())).rename_axis(columns=None)\n>>>\n'''\n GENE1 GENE2 GENE3\nNames1 \nSP1 0-1-2 0-1 NaN\nSP2 NaN 2 NaN\nSP3 NaN 0 NaN\nSP4 NaN NaN 1-2\nSP5 NaN NaN 0\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12559770/" ]
74,674,695
<p>Let's say I have a list of ints called <code>List&lt;int&gt; List1 = new() {1,2,3,4}</code> and <code>List&lt;int&gt; List2 = new() {2,3,4}</code>.</p> <p>I need to check if List2 has everything List1 has. Keep in mind that list lengths may vary.</p> <p>I have no idea on how to make it. Searching on the internet didnt really help.</p>
[ { "answer_id": 74674756, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 0, "selected": false, "text": "ls2 ls1 bool isSubset = !ls2.Except(ls1).Any();\n" }, { "answer_id": 74674767, "author": "stbychkov", "author_id": 6782769, "author_profile": "https://Stackoverflow.com/users/6782769", "pm_score": 1, "selected": false, "text": "var set = new HashSet<int>(list1);\nvar result = list2.All(item => set.Contains(item));\n var result = list2.All(il2 => list1.Any(il1 => il1 == il2));\n var result = !list2.Except(list1).Any();\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20192169/" ]
74,674,700
<p><br /> I want to filter and get the results of each index that</p> <p>it's name starts with <code>&quot;abc&quot;</code> and the state is <code>&quot;DISABLED&quot;</code>.</p> <p>My file looks like this:</p> <pre class="lang-json prettyprint-override"><code>➜ ~ cat test.json | head { &quot;Rules&quot;: [ { &quot;Name&quot;: &quot;abcd&quot;, &quot;Arn&quot;: &quot;arn:aws:events:eu-west-2:XXXXXX:rule/abcd&quot;, &quot;State&quot;: &quot;ENABLED&quot;, &quot;ScheduleExpression&quot;: &quot;rate(6 hours)&quot;, &quot;EventBusName&quot;: &quot;default&quot; }, { &quot;Name&quot;: &quot;abcxxx&quot;, &quot;Arn&quot;: &quot;arn:aws:events:eu-west-2:XXXXXX:rule/abcxxx&quot;, &quot;State&quot;: &quot;DISABLED&quot;, &quot;ScheduleExpression&quot;: &quot;rate(12 hours)&quot;, &quot;EventBusName&quot;: &quot;default&quot; } ] } </code></pre> <p>I tried to use this command:</p> <pre class="lang-bash prettyprint-override"><code>cat test.json | jq -r '.[] | .[] | select(.Name | startswith(&quot;abc&quot;))' </code></pre> <p>And it's giving me whatever starts with <code>&quot;abc&quot;</code> which is good but I want it to be also<br /> <code>.State == &quot;DISABLED&quot;</code> and I want the output to be regular and not JSON.<br /> (I need to get the names of whatever starts with <code>abc</code> and it's state is <code>DISABLED</code> into a file)</p>
[ { "answer_id": 74674801, "author": "mpromonet", "author_id": 3102264, "author_profile": "https://Stackoverflow.com/users/3102264", "pm_score": 3, "selected": true, "text": "cat test.json | jq -r '.[] | .[] | select((.Name | startswith(\"abc\")) and .State == \"DISABLED\") \n Name cat test.json | jq -r '.[] | .[] | select((.Name | startswith(\"abc\")) and .State == \"DISABLED\") | .Name'\n" }, { "answer_id": 74677785, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 1, "selected": false, "text": "and .Rules[] | select(.State == \"DISABLED\" and (.Name | startswith(\"abc\"))) | .Name\n .Rules[] | select(.State == \"DISABLED\") | .Name | select(startswith(\"abc\"))\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19364640/" ]
74,674,740
<p>Faced a problem. On the site, i need to generate such a number of certain lines (via document.write(&quot;Welcome to my page&quot;) ) that the user will tell through the dialog box, when dialog box opening on the page. All this happens through &lt;script&gt; ... &lt;/script&gt;. I tried it in different ways, but nothing works. Help me, please.</p> <pre><code> confirm(&quot;Specify how many times to repeat?'); var run() = promt(&quot;How many times? {value}') function run(){ let value = document.getElementById('count').value if(confirm(Run block ${value} times?)) { while(value &lt; 0){ document.write(Welcome to my page!&lt;br&gt;')} } } </code></pre> <p>A friend suggested this, but it doesn't work either.</p> <pre><code> let res = prompt('How many times?',1) if(!res || isNaN(Number(res)) || res &lt; 0) { alert('Invalid quantity entered') location.reload() return } res = Math.round(Number(res)) while (res &gt; 0){ document.write(`Welcome to my page!&lt;br&gt;')} res-- } </code></pre>
[ { "answer_id": 74674798, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": -1, "selected": true, "text": "function run() {\n // Ask the user how many times to repeat the line\n let count = prompt(\"How many times should I repeat the line?\");\n\n // Make sure the input is a number\n if (!count || isNaN(Number(count)) || count < 0) {\n alert(\"Invalid quantity entered\");\n return;\n }\n\n // Convert the input to a number and round it to the nearest integer\n count = Math.round(Number(count));\n\n // Use a for loop to repeat the line the specified number of times\n for (let i = 0; i < count; i++) {\n document.write(\"Welcome to my page!<br>\");\n }\n}\n run();\n" }, { "answer_id": 74674816, "author": "Aifos Si Prahs", "author_id": 19135131, "author_profile": "https://Stackoverflow.com/users/19135131", "pm_score": 0, "selected": false, "text": "alert('You`ll be prompted to specify how many times to repeat the cycle.');\nconst value = document.getElementById('count')?.value || 1;\n\nconst numOfRuns = confirm(`As many as this: ${value}`) ? value : (new Number(prompt('How many times to repeat the cycle?')));\n\nfor (let i = 0; i < numOfRuns; i++) {\n document.write('Welcome to my page!<br>');\n}" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681184/" ]
74,674,746
<p>In the plot, smaller bubbles will be hidden by bigger bubbles. if I use alpha, they will appear. I would like that small bubbles superpose the bigger ones without using alpha</p> <pre><code> library(ggplot2) library(dplyr) </code></pre> <h1>The dataset is provided in the gapminder library</h1> <pre><code> library(gapminder) data &lt;- gapminder %&gt;% filter(year==&quot;2007&quot;) %&gt;% dplyr::select(-year) # Most basic bubble plot data %&gt;% arrange(desc(pop)) %&gt;% mutate(country = factor(country, country)) %&gt;% ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent)) + geom_point(alpha=0.5) + scale_size(range = c(.1, 24), name=&quot;Population (M)&quot;) </code></pre>
[ { "answer_id": 74675173, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "shape = 21 library(ggplot2)\nlibrary(dplyr)\nlibrary(gapminder)\nlibrary(colorspace)\n\ndata <- gapminder %>% filter(year==\"2007\") %>% dplyr::select(-year)\n\ndata %>%\n arrange(desc(pop)) %>%\n mutate(country = factor(country, country)) %>%\n ggplot(aes(gdpPercap, lifeExp, size = pop, fill = continent,\n color = after_scale(darken(fill, 0.3)))) +\n geom_point(shape = 21) +\n scale_size(range = c(.1, 24), name = \"Population (M)\") +\n scale_x_continuous(\"GDP per Capita\", labels = scales::dollar) +\n ylab(\"Life Expectancy\") +\n theme_minimal(base_size = 20) +\n scale_fill_brewer(palette = \"Pastel1\") +\n ggtitle(\"Average life expectancy 2007\") +\n guides(size = \"none\",\n fill = guide_legend(override.aes = list(size = 6))) +\n theme(panel.background = element_rect(fill = \"gray95\", color = NA),\n legend.title = element_text(size = 25, face = 2),\n legend.text = element_text(size = 25, face = 2))\n" }, { "answer_id": 74677407, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "# Libraries\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(viridis)\nlibrary(gapminder)\n\ngapminder %>% \n filter(year==\"2007\") %>%\n select(-year) %>% \n arrange(desc(pop)) %>%\n mutate(country = factor(country, country)) %>%\n ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, fill=continent)) +\n geom_point(alpha=0.5, shape=21, color=\"black\") +\n scale_size(range = c(.1, 24), name=\"Population (M)\", guide=\"none\")+\n scale_fill_viridis(discrete=TRUE, option=\"A\") +\n theme_bw() +\n theme(legend.position=\"bottom\") +\n ylab(\"Life Expectancy\") +\n xlab(\"Gdp per Capita\") \n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11101169/" ]
74,674,764
<p>What is the default ARIA role of a <code>div</code> or <code>span</code> in HTML? Or, in other words, what is the ARIA role of non-interactive elements and the elements that don't have a specific ARIA role assigned to them? Is it <code>none</code> or <code>presentation</code>? Or is it not defined? And if it is, do they have any different meaning than <code>none</code> or <code>presentation</code>?</p>
[ { "answer_id": 74677412, "author": "Robin Zigmond", "author_id": 8475054, "author_profile": "https://Stackoverflow.com/users/8475054", "pm_score": 3, "selected": true, "text": "div span generic generic role none presentation presentation role div <div> aria-hidden=\"true\" generic none presentation presentation generic generic" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16333629/" ]
74,674,832
<p>I am getting picture from gallery using this code.i want to pass this image view to another activity and show it.In second activity i want to catch it.It is same as data passing through an activities but the images are not working in that method.Any suggetions?</p> <pre><code> val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -&gt; imageView.setImageURI(uri) } val button = findViewById&lt;Button&gt;(R.id.button) button.setOnClickListener { getContent.launch(&quot;image/*&quot;) } val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -&gt; imageView.setImageURI(uri) } val button = findViewById&lt;Button&gt;(R.id.button) button.setOnClickListener { getContent.launch(&quot;image/*&quot;) } </code></pre>
[ { "answer_id": 74677412, "author": "Robin Zigmond", "author_id": 8475054, "author_profile": "https://Stackoverflow.com/users/8475054", "pm_score": 3, "selected": true, "text": "div span generic generic role none presentation presentation role div <div> aria-hidden=\"true\" generic none presentation presentation generic generic" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5117918/" ]
74,674,850
<p>I'm trying to make a class in Delphi that handles files. I have a property that returns the size of the file and another one that returns the position of the file. I don't know if any error can happen with these calls. Should I raise an exception?</p> <p>My code is:</p> <pre><code>function TFile.GetSize: Int64; var FileSizeHi, FileSizeLo: Cardinal; begin FileSizeLo := GetFileSize(FHandle, @FileSizeHi); if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FileSizeLo or Int64(FileSizeHi) shl 32; end; function TFile.GetPosition: Int64; var FilePosHi, FilePosLo: Cardinal; begin FilePosHi := 0; FilePosLo := 0; FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT); if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError = NO_ERROR) then Result := $FFFFFFFF else Result := FilePosLo or Int64(FilePosHi) shl 32; end; </code></pre> <p>I don't know what error could happen when I call GetFileSize or SetFilePointer (without moving the file pointer).</p>
[ { "answer_id": 74675019, "author": "Eirik A.", "author_id": 2022963, "author_profile": "https://Stackoverflow.com/users/2022963", "pm_score": 0, "selected": false, "text": "SetFilePointer() GetFileSize()" }, { "answer_id": 74678532, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "$FFFFFFFF -1 $FFFFFFFFFFFFFFFF GetLastError() <> = $FFFFFFFF GetLastError() $FFFFFFFF GetLastError() function TFile.GetSize: Int64;\nvar\n FileSizeHi, FileSizeLo: DWORD;\nbegin\n FileSizeLo := GetFileSize(FHandle, @FileSizeHi);\n if (FileSizeLo = INVALID_FILE_SIZE) and (GetLastError <> NO_ERROR) then\n RaiseLastOSError // or: Result := -1\n else\n Result := FileSizeLo or (Int64(FileSizeHi) shl 32);\nend;\n\nfunction TFile.GetPosition: Int64;\nvar\n FilePosHi, FilePosLo: DWORD;\nbegin\n FilePosHi := 0;\n FilePosLo := 0;\n FilePosLo := SetFilePointer(FHandle, FilePosLo, @FilePosHi, FILE_CURRENT);\n if (FilePosLo = INVALID_SET_FILE_POINTER) and (GetLastError <> NO_ERROR) then\n RaiseLastOSError // or: Result := -1\n else\n Result := FilePosLo or (Int64(FilePosHi) shl 32);\nend;\n GetFileSizeEx() SetFilePointerEx()" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681380/" ]
74,674,894
<p>In cpp, <br /> I know <code>&amp;</code> is used to get the address<br /> and <code>::</code> is used to get the member of class,<br /> but, what's the usage of <code>&amp;::</code> ?</p> <p>Here is the example of the function <code>connect</code> of qt5:</p> <pre><code>QtWidgetsApplication2::QtWidgetsApplication2(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(ui.pushButton_select, &amp;QPushButton::clicked,this,&amp;::QtWidgetsApplication2::select_file); } void QtWidgetsApplication2::select_file() { file_path = QFileDialog::getOpenFileName(NULL, QStringLiteral(&quot;选择文件&quot;), &quot;D:&quot;, QStringLiteral(&quot;音频文件(*wav)&quot;)); } </code></pre> <p>what's the meaning of <code>&amp;::</code> in this line :</p> <blockquote> <p>connect(ui.pushButton_select, &amp;QPushButton::clicked,this,<strong>&amp;::QtWidgetsApplication2::select_file</strong>);</p> </blockquote> <p>why not <code>&amp;QtWidgetsApplication2::select_file</code>?</p>
[ { "answer_id": 74674926, "author": "Mohsin Mehmood", "author_id": 12248102, "author_profile": "https://Stackoverflow.com/users/12248102", "pm_score": 0, "selected": false, "text": "connect(ui.pushButton_select, &QPushButton::clicked, std::bind(&QtWidgetsApplication2::select_file, this));\n" }, { "answer_id": 74674928, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 1, "selected": false, "text": "&:: &QtWidgetsApplication2::select_file QtWidetsApplication2 namespace P\n{\n struct C\n {\n constexpr static int i = 0;\n };\n}\n\nstruct C\n{\n constexpr static int i = 0;\n};\n//-------------vvv-------->uses global class C\nconst int *j = &::C::i;\n//-------------vv-------->uses class C in namespace P\nconst int *k = &P::C::i;\n" }, { "answer_id": 74674953, "author": "Teivaz", "author_id": 3344612, "author_profile": "https://Stackoverflow.com/users/3344612", "pm_score": 2, "selected": false, "text": ":: :: & & ( (::QtWidgetsApplication2) ::select_file)" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17774109/" ]
74,674,898
<p>I ran into a problem with Redshift. I'm generating a sequence of dates and want to embed it in a table to work with the range. But Redshift only supports generation on the leader node. It is not possible to insert the data on the nodes. Nowhere in the documentation have I found information on how to insert the generated sequences into tables. Maybe someone has encountered such a problem and can share their experience in solving it? My sequence:</p> <pre><code>SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL; </code></pre> <p>My query:</p> <pre><code>CREATE TABLE public.date_sequence AS ( SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL ); </code></pre> <p>I also tried inserting data from cte. Insert data into a temporary table. The result is the same: ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables.</p>
[ { "answer_id": 74674944, "author": "Breezer", "author_id": 260640, "author_profile": "https://Stackoverflow.com/users/260640", "pm_score": 1, "selected": false, "text": "create table INSERT INTO public.date_sequence\nSELECT date '2019-12-31' + INTERVAL AS date_range\nFROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL;\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20680866/" ]
74,674,908
<p>I am trying to add a underline like symbol below the active link for that purpose i am used ::after element and set it's width to 100% to get its parent element's width but the psudo element is way much bigger when width is 100%;</p> <p>my html code is </p> <pre><code>&lt;header class=&quot;main-header&quot;&gt; &lt;a class=&quot;category-name&quot;&gt; &lt;span&gt; Sneakers &lt;/span&gt; &lt;/a&gt; &lt;nav class=&quot;main-nav&quot;&gt; &lt;ul class=&quot;main-nav-list&quot;&gt; &lt;li class=&quot;m&quot;&gt; &lt;a class=&quot;main-nav-link&quot; href=&quot;#how&quot;&gt;Collections&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a class=&quot;main-nav-link&quot; href=&quot;#meals&quot;&gt;Men&lt;/a&gt;&lt;/li&gt; &lt;li&gt; &lt;a class=&quot;main-nav-link&quot; href=&quot;#testimonials&quot;&gt;Women&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a class=&quot;main-nav-link&quot; href=&quot;#pricing&quot;&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class=&quot;main-nav-link nav-cta&quot; href=&quot;#cta&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;ul class=&quot;my__ac-list&quot;&gt; &lt;li class=&quot;nav--cart_icon&quot; id=&quot;cartBtn&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;cart-icon&quot; &gt;&lt;img src=&quot;./images/icon-cart.svg&quot; alt=&quot;cart icon&quot; srcset=&quot;&quot; /&gt;&lt;/a&gt; &lt;p class=&quot;cart--strip&quot;&gt;3&lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#&quot;&gt; &lt;img class=&quot;profile-thumbnail&quot; src=&quot;./images/image-avatar.png&quot; alt=&quot;image-avatar&quot; srcset=&quot;&quot; /&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/header&gt; </code></pre> <p>my css code is bit lengthier i couldnot format correctly so i have created code containg my html and css</p> <p>codepen link = <a href="https://codepen.io/sinan-m/pen/abKQaxp" rel="nofollow noreferrer">https://codepen.io/sinan-m/pen/abKQaxp</a></p> <p>i want to add a underline below the active navigation link like in design</p> <p>my design image <a href="https://github.com/front-end-mentor-works/e-com-product-page/blob/main/design/active-states-basket-filled.jpg" rel="nofollow noreferrer">https://github.com/front-end-mentor-works/e-com-product-page/blob/main/design/active-states-basket-filled.jpg</a></p>
[ { "answer_id": 74675063, "author": "ctrl-alt-delor", "author_id": 537980, "author_profile": "https://Stackoverflow.com/users/537980", "pm_score": 0, "selected": false, "text": ".main-nav-list li.m {\n border-bottom: 5px solid tomato;\n}\n .main-nav-list li.m .main-nav-list li.m {\n border-bottom: 5px solid tomato;\n padding-bottom: 1ex;\n}\n .main-nav-list {\n …\n align-items: top;\n …\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300178/" ]
74,674,910
<p>Is there a neat way to simplify this if statement? I need n to be &gt;= 2 and &lt;= 100 and value to increase by one for every seventh step (except the first one which should be between 2 and 7 and last one which should be between 98 and 100).</p> <pre><code>if n &gt;= 2 and n &lt;= 7: value = 1 elif n &gt; 7 and n &lt;= 14: value = 2 elif n &gt; 14 and n &lt;= 21: value = 3 elif n &gt; 21 and n &lt;= 28: value = 4 elif n &gt; 28 and n &lt;= 35: value = 5 elif n &gt; 35 and n &lt;= 42: value = 6 elif n &gt; 42 and n &lt;= 49: value = 7 elif n &gt; 49 and n &lt;= 56: value = 8 elif n &gt; 56 and n &lt;= 63: value = 9 elif n &gt; 63 and n &lt;= 70: value = 10 elif n &gt; 70 and n &lt;= 77: value = 11 elif n &gt; 77 and n &lt;= 84: value = 12 elif n &gt; 84 and n &lt;= 91: value = 13 elif n &gt; 91 and n &lt;= 98: value = 14 elif n &gt; 98 and n &lt;= 100: value = 15 </code></pre> <p>EDIT: Furthermore I'm having trouble finding the smallest number possible from the following question:</p> <hr /> <p>Matchsticks are ideal tools to represent numbers. A common way to represent the ten decimal digits with matchsticks is the following:</p> <p><a href="https://i.stack.imgur.com/7PkZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7PkZJ.png" alt="enter image description here" /></a></p> <p>This is identical to how numbers are displayed on an ordinary alarm clock. With a given number of matchsticks you can generate a wide range of numbers. We are wondering what the smallest and largest numbers are that can be created by using all your matchsticks.</p> <p><em>Input:</em></p> <p>On the first line one positive number: the number of testcases, at most 100. After that per testcase:</p> <p>One line with an integer n (2 &lt;= n &lt;= 100): the number of matchsticks you have.</p> <p><em>Output:</em></p> <p>Per testcase:</p> <p>One line with the smallest and largest numbers you can create, separated by a single space. Both numbers should be positive and contain no leading zeroes.</p> <hr /> <p>I've tried multiple different ways to try to solve this problem, I'm currently trying to:</p> <ol> <li>find the minimal number of digits (value) for the smallest number:</li> </ol> <p>#Swifty</p> <pre><code>def values(n): if 2 &lt;= n &lt;= 100: value = (n + 6) // 7 minimum(n, value) </code></pre> <ol start="2"> <li>now i want to send value to a function minimum() which should generate all the different combinations of numbers that are the length of value. I want to store all these numbers in a list and then take min() to get the smallest one. I'm not getting this part to work, and would appreciate some inspiration.</li> </ol> <p>Something to remember is that the number can't start with a 0.</p>
[ { "answer_id": 74674973, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "if 2 <= n <= 100:\n value = (n+6)//7\n numdict = {2:1,3:7,4:4,5:2,6:0,7:8,8:10,9:18,10:22,11:20,12:28,13:68}\n\ndef min_stick(n):\n if 2 <= n <= 13:\n return numdict[n]\n digits = (n + 6) // 7\n base = str(numdict[7+n%7])\n return int(base+\"8\"*(digits - len(base)))\n def max_stick(n):\n if n%2:\n return int(\"7\"+\"1\"*((n-3)//2))\n return int(\"1\"*(n//2))\n" }, { "answer_id": 74675463, "author": "Jiao Dian", "author_id": 8883383, "author_profile": "https://Stackoverflow.com/users/8883383", "pm_score": 0, "selected": false, "text": "value = (n // 7) + 1 if 2 <= n <= 100 else None\n # n = 14\nvalue = (14 // 7) + 1 # This evaluates to 2\n\n# n = 100\nvalue = (100 // 7) + 1 # This evaluates to 15\n\n# n = 101\nvalue = (101 // 7) + 1 # This evaluates to None\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14898307/" ]
74,674,913
<p><a href="https://i.stack.imgur.com/w3vXI.png" rel="nofollow noreferrer">enter image description here</a> Getting issues with my code unable to understand what to do next can anyone help me out</p> <pre><code># Importing the libraries import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding, LSTM, SpatialDropout1D from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical import pickle import re # Importing the dataset filename = &quot;MoviePlots.csv&quot; data = pd.read_csv(filename, encoding= 'unicode_escape') # Keeping only the neccessary columns data = data[['Plot']] # Clean the data data['Plot'] = data['Plot'].apply(lambda x: x.lower()) data['Plot'] = data['Plot'].apply((lambda x: re.sub('[^a-zA-z0-9\s]', '', x))) # Create the tokenizer tokenizer = Tokenizer(num_words=5000, split=&quot; &quot;) tokenizer.fit_on_texts(data['Plot'].values) # Save the tokenizer with open('tokenizer.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) # Create the sequences X = tokenizer.texts_to_sequences(data['Plot'].values) X = pad_sequences(X) # Create the model model = Sequential() model.add(Embedding(5000, 256, input_length=X.shape[1])) model.add(Bidirectional(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))) model.add(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1)) model.add(LSTM(256, dropout=0.1, recurrent_dropout=0.1)) model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01))) model.add(Dense(5000, activation='softmax')) # Compile the model model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.01), metrics=['accuracy']) # Train the model model.fit(X, X, epochs=100, batch_size=128, verbose=1) # Saving the model model.save('visioniser.h5') </code></pre> <p>This is my code and error in the image attached</p> <p>Anyone please help me out solve this problem of my code please diagnose it</p>
[ { "answer_id": 74674973, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 2, "selected": true, "text": "if 2 <= n <= 100:\n value = (n+6)//7\n numdict = {2:1,3:7,4:4,5:2,6:0,7:8,8:10,9:18,10:22,11:20,12:28,13:68}\n\ndef min_stick(n):\n if 2 <= n <= 13:\n return numdict[n]\n digits = (n + 6) // 7\n base = str(numdict[7+n%7])\n return int(base+\"8\"*(digits - len(base)))\n def max_stick(n):\n if n%2:\n return int(\"7\"+\"1\"*((n-3)//2))\n return int(\"1\"*(n//2))\n" }, { "answer_id": 74675463, "author": "Jiao Dian", "author_id": 8883383, "author_profile": "https://Stackoverflow.com/users/8883383", "pm_score": 0, "selected": false, "text": "value = (n // 7) + 1 if 2 <= n <= 100 else None\n # n = 14\nvalue = (14 // 7) + 1 # This evaluates to 2\n\n# n = 100\nvalue = (100 // 7) + 1 # This evaluates to 15\n\n# n = 101\nvalue = (101 // 7) + 1 # This evaluates to None\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681432/" ]
74,674,917
<p>I'm building my first app using RTK query. I need to set my authorization token in my headers. It is stored in a cookie, but they can't be accessed from the apiSlice, which means I need to store the token in my states which I'd have access to when setting my headers.</p> <p>I get the token from my cookies when the app first starts, but I'm failing to understand how do I store it in my state, now that I use RTK query? I'm not making any API call, I already have the data. How do I store it in my slice?</p>
[ { "answer_id": 74674952, "author": "odnualam", "author_id": 10875688, "author_profile": "https://Stackoverflow.com/users/10875688", "pm_score": -1, "selected": false, "text": "const authSlice = createSlice({\n name: 'auth',\n initialState: {\n token: null\n },\n reducers: {\n // Add your reducer functions here\n }\n});\n\n// Get your authorization token from the cookie\nconst token = getTokenFromCookie();\n\n// Update the state with the new token\nauthSlice.update(state => {\n state.token = token;\n return state;\n});\n const token = authSlice.select(state => state.token);\n const headers = {\n Authorization: `Bearer ${token}`\n};\n" }, { "answer_id": 74679063, "author": "phry", "author_id": 2075944, "author_profile": "https://Stackoverflow.com/users/2075944", "pm_score": 2, "selected": true, "text": "credentials: \"include\"" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774624/" ]
74,674,948
<pre><code> int a[] = {1, 6, 3, 4, 5, 8, 7}; for(int i = 0; i &lt; a.length; i++){ if (a[i] % 2 == 0) { int b = new int[3]; b[i] = a[i]; System.out.print(b[i] + &quot; &quot;); } } </code></pre> <p>//I want a new array b, to have the even values of a. How can I make this work?</p>
[ { "answer_id": 74674952, "author": "odnualam", "author_id": 10875688, "author_profile": "https://Stackoverflow.com/users/10875688", "pm_score": -1, "selected": false, "text": "const authSlice = createSlice({\n name: 'auth',\n initialState: {\n token: null\n },\n reducers: {\n // Add your reducer functions here\n }\n});\n\n// Get your authorization token from the cookie\nconst token = getTokenFromCookie();\n\n// Update the state with the new token\nauthSlice.update(state => {\n state.token = token;\n return state;\n});\n const token = authSlice.select(state => state.token);\n const headers = {\n Authorization: `Bearer ${token}`\n};\n" }, { "answer_id": 74679063, "author": "phry", "author_id": 2075944, "author_profile": "https://Stackoverflow.com/users/2075944", "pm_score": 2, "selected": true, "text": "credentials: \"include\"" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20177615/" ]
74,674,950
<p>I'm building a Formula1 race simulator in python and I'm trying to make a overtake function, basically, i've all the drivers stored in a list and once one of the drivers surpasses the other I need to invert their position in the list</p> <pre><code>['hamilton','vertsappen','perez','sainz'] ['hamilton','perez','verstappen','sainz'] </code></pre> <p>is there any way to do so?</p> <p>since now I have tried to store the original positions in a temporary variable but I keep finding myself with duplicates in the list</p> <p>original temporary variables</p> <pre><code>overtaken temp = Valteri Bottas overtaker temp = Nicholas Latifi </code></pre> <p>after the inverting</p> <pre><code>overtaken temp = Valteri Bottas overtaker temp = Valteri Bottas </code></pre>
[ { "answer_id": 74674965, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "def overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n" }, { "answer_id": 74674989, "author": "william serangeli", "author_id": 19994378, "author_profile": "https://Stackoverflow.com/users/19994378", "pm_score": 0, "selected": false, "text": "grid[0], grid[1] = grid[1] = grid[0]\n" }, { "answer_id": 74675028, "author": "ricogordo", "author_id": 19366374, "author_profile": "https://Stackoverflow.com/users/19366374", "pm_score": 1, "selected": false, "text": "a = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19994378/" ]
74,674,956
<p>I tried to create several maps and saved as png files. In cycle I got all mapes per <code>year</code>. I want to add which year on the map, and I tried <code>title=i</code> and <code>fig.update_layout(title_text=i, title_x=0.5)</code>, but it does not work.</p> <pre><code>import plotly.express as px import pandas as pd year = [1980,1981,1983] lat = [60.572959, 60.321403, 56.990280] lon = [40.572759, 41.321203, 36.990299] dataframe = pd.DataFrame(list(zip(year,lat,lon)), columns =['year', 'lat', 'lon']) for idx, i in enumerate(sorted(dataframe['year'].unique())): #for x in range(1980,2022): sp = sp1[sp1['year']==i] fig = px.scatter_mapbox(dataframe, lat='lat', lon=&quot;lon&quot;, color_discrete_sequence=[&quot;fuchsia&quot;], zoom=2, height=400, opacity=0.3, title = i) fig.update_layout(mapbox_style=&quot;open-street-map&quot;) fig.update_layout(margin={&quot;r&quot;:0,&quot;t&quot;:0,&quot;l&quot;:0,&quot;b&quot;:0}) fig.update_layout(title_text=i, title_x=0.5) fig.write_image(&quot;all/plot{idx}.png&quot;.format(idx=idx)) </code></pre> <p>I put the picture of one map as example. I want to add <code>year</code> for every map in any place. <a href="https://i.stack.imgur.com/ejcbL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ejcbL.png" alt="my_example" /></a></p>
[ { "answer_id": 74674965, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "def overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n" }, { "answer_id": 74674989, "author": "william serangeli", "author_id": 19994378, "author_profile": "https://Stackoverflow.com/users/19994378", "pm_score": 0, "selected": false, "text": "grid[0], grid[1] = grid[1] = grid[0]\n" }, { "answer_id": 74675028, "author": "ricogordo", "author_id": 19366374, "author_profile": "https://Stackoverflow.com/users/19366374", "pm_score": 1, "selected": false, "text": "a = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17418636/" ]
74,674,960
<pre><code> </code></pre> <pre><code>import java.text.BreakIterator; import java.util.*; public class Main { public static void main(String args[]) { Scanner in= new Scanner(System.in); System.out.println(&quot;nomber&quot;); int n= in.nextInt(); int s= n*n; int l = (&quot;&quot;+s).length(); System.out.println(l); } } </code></pre> <pre><code> </code></pre> <p>how can I extract last digit from input in a simple way. Not so complicated like while loop.... java</p>
[ { "answer_id": 74674965, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "def overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n" }, { "answer_id": 74674989, "author": "william serangeli", "author_id": 19994378, "author_profile": "https://Stackoverflow.com/users/19994378", "pm_score": 0, "selected": false, "text": "grid[0], grid[1] = grid[1] = grid[0]\n" }, { "answer_id": 74675028, "author": "ricogordo", "author_id": 19366374, "author_profile": "https://Stackoverflow.com/users/19366374", "pm_score": 1, "selected": false, "text": "a = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18397913/" ]
74,674,974
<p>I'm using OpenTok RTC. And I need to only grant permission for Mic only.</p> <p>I have been reading the documentations and I'm using the getDevices which asks for camera and mic permissions. And I only need Mic permission</p> <p>I can't find a way around this yet</p> <p>Link for getDevices <a href="https://tokbox.com/developer/sdks/js/reference/OT.html#getDevices" rel="nofollow noreferrer">here</a></p>
[ { "answer_id": 74674965, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "def overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n" }, { "answer_id": 74674989, "author": "william serangeli", "author_id": 19994378, "author_profile": "https://Stackoverflow.com/users/19994378", "pm_score": 0, "selected": false, "text": "grid[0], grid[1] = grid[1] = grid[0]\n" }, { "answer_id": 74675028, "author": "ricogordo", "author_id": 19366374, "author_profile": "https://Stackoverflow.com/users/19366374", "pm_score": 1, "selected": false, "text": "a = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16843374/" ]
74,674,980
<p>I'm trying to remove all the unnecessary words and characters from the values in this column. I want the rows to contain 'Entry level', 'Mid-Senior level' etc. Also is there anyway to translate the arabic to english or shall I use replace function?</p> <p>df_africa.seniority_level.value_counts()</p> <pre><code>{'Seniority level': 'Entry level'} 1073 {'Seniority level': 'Mid-Senior level'} 695 {'Seniority level': 'Associate'} 481 {'Seniority level': 'Not Applicable'} 150 {'مستوى الأقدمية': 'مستوى متوسط الأقدمية'} 115 {'مستوى الأقدمية': 'مستوى المبتدئين'} 82 {'نوع التوظيف': 'دوام كامل'} 73 {'مستوى الأقدمية': 'مساعد'} 48 {'مستوى الأقدمية': 'غير مطبق'} 42 {'Seniority level': 'Internship'} 39 {'Employment type': 'Contract'} 21 {'Employment type': 'Full-time'} 1 I've tried the split function but i couldn't get it to work properly. </code></pre>
[ { "answer_id": 74674965, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "def overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n" }, { "answer_id": 74674989, "author": "william serangeli", "author_id": 19994378, "author_profile": "https://Stackoverflow.com/users/19994378", "pm_score": 0, "selected": false, "text": "grid[0], grid[1] = grid[1] = grid[0]\n" }, { "answer_id": 74675028, "author": "ricogordo", "author_id": 19366374, "author_profile": "https://Stackoverflow.com/users/19366374", "pm_score": 1, "selected": false, "text": "a = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19697147/" ]
74,674,996
<p>I have a nested list like:</p> <pre><code>[[&quot;bla&quot;,&quot;blabla&quot;,&quot;x=17&quot;],[&quot;bla&quot;,&quot;x=13&quot;,&quot;z=13&quot;,&quot;blabla&quot;],[&quot;x=27&quot;,&quot;blabla&quot;,&quot;bla&quot;,&quot;y=24&quot;]] </code></pre> <p>I need to have this sorted by x (from least to most) as (other strings should stay where they are):</p> <pre><code>[[&quot;bla&quot;,&quot;x=13&quot;,&quot;z=13&quot;,&quot;blabla&quot;],[&quot;bla&quot;,&quot;blabla&quot;,&quot;x=17&quot;],[&quot;x=27&quot;,&quot;blabla&quot;,&quot;bla&quot;,&quot;y=24&quot;]] </code></pre> <p>and also from most to least:</p> <pre><code>[[&quot;x=27&quot;,&quot;blabla&quot;,&quot;bla&quot;,&quot;y=24&quot;],[&quot;bla&quot;,&quot;blabla&quot;,&quot;x=17&quot;],[&quot;bla&quot;,&quot;x=13&quot;,&quot;z=13&quot;,&quot;blabla&quot;]] </code></pre> <p>I think I have to use key=lambda but I just couldn't figure out how to do it. Searched through the web and this website but I just can't do it.</p>
[ { "answer_id": 74675035, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "sort_this_list = [\n [\"bla\",\"blabla\",\"x=17\"],\n [\"bla\",\"x=13\",\"z=13\",\"blabla\"],\n [\"x=27\",\"blabla\",\"bla\",\"y=24\"]\n]\n x def get_x(list):\n # Iterate over the items in the given list\n for item in list:\n # Check if the item starts with \"x=\"\n if item.startswith(\"x=\"):\n # Extract the value of x and return it as an integer\n return int(item.split(\"=\")[1])\n sorted_ascending = sorted(sort_this_list, key=get_x) sorted(..)" }, { "answer_id": 74675100, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 0, "selected": false, "text": "mylist = [[\"bla\",\"blabla\",\"x=17\"],[\"bla\",\"x=13\",\"z=13\",\"blabla\"],[\"x=27\",\"blabla\",\"bla\",\"y=24\"]]\n\nmylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True)\n\n# [['x=27', 'blabla', 'bla', 'y=24'],\n# ['bla', 'blabla', 'x=17'],\n# ['bla', 'x=13', 'z=13', 'blabla']]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17788139/" ]
74,674,998
<p>Fair Warning: I'm a student trying to build an app for our research.</p> <p>So I'm Trying to build an app where the user Defines the amount of Q/A he/she wants, then the app will ask for the user to put different Q/A until it reaches the an equal amount where it will then open up a new page to make the user answer those Q/A.</p> <p>The Problem is that the Loop fails to repeat at the stated amount by user making the app not being able to store let's say 10 Q/A to the JShared / Shared Preference.</p> <p>Here's the loop code:</p> <pre><code>package com.prgr.quizards.canary; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.widget.AppCompatButton; import com.google.android.material.textfield.TextInputEditText; import com.google.gson.Gson; import java.util.HashMap; import java.util.Objects; public class question extends Activity { private HashMap&lt;String, Object&gt; map = new HashMap&lt;&gt;(); private TextView text; private EditText inop; private TextInputEditText ans; private AppCompatButton btn; private SharedPreferences jshared2; private SharedPreferences jshared; @Override protected void onCreate(Bundle _savedInstanceState) { super.onCreate(_savedInstanceState); setContentView(R.layout.activity_question); initializedata(); AppCompatButton btn2 = findViewById(R.id.button3); btn = findViewById(R.id.button); btn2.setOnClickListener(v -&gt; gotoback()); btn.setOnClickListener(view -&gt; logicg()); } public void gotoback(){ Intent intent = new Intent(question.this, activity_home_screen.class); startActivity(intent); } private void initializedata(){ jshared = getSharedPreferences(&quot;j&quot;, Activity.MODE_PRIVATE); jshared2 = getSharedPreferences(&quot;j2&quot;, Activity.MODE_PRIVATE); inop = findViewById(R.id.inop); ans = findViewById(R.id.ans); text = findViewById(R.id.text1); } private void logicg() { String mount = jshared.getString(&quot;amount&quot;, &quot;&quot;); int amounts = Integer.parseInt(mount); for (int i = 1; i &lt; amounts; i++) { //String shite = Integer.toString(qloop); //Toast.makeText(getApplicationContext(), shite, Toast.LENGTH_SHORT).show(); if (i == amounts) { Intent intent = new Intent(question.this, answerscrn.class); startActivity(intent); } else{ map = new HashMap&lt;&gt;(); map.put(&quot;answer&quot;, Objects.requireNonNull(ans.getText()).toString()); map.put(&quot;question&quot;, inop.getText().toString()); jshared2.edit().putString(&quot;data&quot;, new Gson().toJson(map)).commit(); } } } } </code></pre> <p>I tried to do a <code>for loop + if else</code> inside the for loop and that only returns the error of <code>Condition 'i == amounts' is always 'false'</code> what i expect is for it to loop till it reaches the same number stated by the <code>amounts</code> (which is the user defined value) to open up a new page using intent.</p>
[ { "answer_id": 74675035, "author": "J. M. Arnold", "author_id": 14852784, "author_profile": "https://Stackoverflow.com/users/14852784", "pm_score": 1, "selected": false, "text": "sort_this_list = [\n [\"bla\",\"blabla\",\"x=17\"],\n [\"bla\",\"x=13\",\"z=13\",\"blabla\"],\n [\"x=27\",\"blabla\",\"bla\",\"y=24\"]\n]\n x def get_x(list):\n # Iterate over the items in the given list\n for item in list:\n # Check if the item starts with \"x=\"\n if item.startswith(\"x=\"):\n # Extract the value of x and return it as an integer\n return int(item.split(\"=\")[1])\n sorted_ascending = sorted(sort_this_list, key=get_x) sorted(..)" }, { "answer_id": 74675100, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 0, "selected": false, "text": "mylist = [[\"bla\",\"blabla\",\"x=17\"],[\"bla\",\"x=13\",\"z=13\",\"blabla\"],[\"x=27\",\"blabla\",\"bla\",\"y=24\"]]\n\nmylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True)\n\n# [['x=27', 'blabla', 'bla', 'y=24'],\n# ['bla', 'blabla', 'x=17'],\n# ['bla', 'x=13', 'z=13', 'blabla']]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74674998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15408335/" ]
74,675,002
<p>I have an array of objects with some car data inside :</p> <pre><code>const cars = [ { &quot;id&quot;: 1, &quot;car_make&quot;: &quot;Lincoln&quot;, &quot;car_model&quot;: &quot;Navigator&quot;, &quot;car_year&quot;: 2009, &quot;data&quot;: { &quot;rating&quot;: 4.9, &quot;engines&quot;: [3, 4, 5, 6] } }, { &quot;id&quot;: 2, &quot;car_make&quot;: &quot;Mazda&quot;, &quot;car_model&quot;: &quot;Miata MX-5&quot;, &quot;car_year&quot;: 2001, &quot;data&quot;: { &quot;rating&quot;: 4.1, &quot;engines&quot;: [1, 2] } },] </code></pre> <p>Next I need to sum all the engines numbers inside the data object in car: So I made the next function but everytime I try to console the array it remains unchanged.</p> <pre><code>cars.forEach(car =&gt; { car.data.engines.reduce((a,b) =&gt; a+b,0) }) console.log(cars); </code></pre>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19434894/" ]
74,675,009
<p>Here I am trying to retrieve the IP address of the user, and with the timezone that I got from the IP address, I want to check if the date is 1/01/2023 for that country and then if it is, I want to redirect the user to another subdomain which has a Happy New Year Page:</p> <pre><code>&lt;?php $ip = $_SERVER['REMOTE_ADDR']; $ipInfo = file_get_contents('http://ip-api.com/json/' . $ip); $ipInfo = json_decode($ipInfo); $timezone = $ipInfo-&gt;timezone; if (date('d') == '01' &amp;&amp; date('m') == '01' &amp;&amp; date('Y') == '2023') { header('Location: https://2023.blogsaffair.com/'); } if (date('d') == '1' &amp;&amp; date('m') == '11') { header('Location: https://blogsaffair.com'); }*/ ?&gt; </code></pre> <p>My scripts.js code for countdown</p> <pre><code>const secondsText = document.getElementById('seconds'); const minutesText = document.getElementById('minutes'); const hoursText = document.getElementById('hours'); const daysText = document.getElementById('days'); function countDown () { var deadlineDate = new Date(&quot;Jan 1, 2023 00:00:00&quot;).getTime(); var presentDate= new Date().getTime(); var timeLeft = deadlineDate - presentDate; var daysValue = Math.floor(timeLeft / (1000 * 60 * 60 * 24)); var hoursValue = Math.floor(timeLeft % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)); var minutesValue = Math.floor(timeLeft % (1000 * 60 * 60) / (1000 * 60)); var secondsValue = Math.floor(timeLeft % (1000 * 60) / (1000)); secondsText.textContent = secondsValue; minutesText.textContent = minutesValue; hoursText.textContent = hoursValue; daysText.textContent = daysValue; if(timeLeft &lt; 0){ clearInterval(); } } setInterval(countDown, 1000); </code></pre> <p>I am trying to achieve what timeanddate.com shows on this link <a href="https://www.timeanddate.com/countdown/newyear" rel="nofollow noreferrer">https://www.timeanddate.com/countdown/newyear</a></p> <p>How can I display the countdown for that country using IP. I couldn't find this anywhere on the internet so please help if you can? Thanks!</p>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14735936/" ]
74,675,135
<p>which tag we will use for adding the background image and how to remake it's size full length</p> <p>I tried by using style tag in html of head section background-image:url;</p>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20655393/" ]
74,675,137
<p>I'm trying to better understand how to work with nested JSON objects in JavaScript/React. I am getting data through the GitLab API in the following form:</p> <pre><code>const merge_requests = [ { &quot;id&quot;: 39329289, &quot;iid&quot;: 156, &quot;project_id&quot;: 231, &quot;title&quot;: &quot;Repaired some Links&quot;, &quot;description&quot;: &quot;&quot;, &quot;state&quot;: &quot;merged&quot;, &quot;created_at&quot;: &quot;2022-12-03T12:22:14.690Z&quot;, &quot;updated_at&quot;: &quot;2022-12-03T12:22:20.060Z&quot;, &quot;merged_by&quot;: { &quot;id&quot;: 1000, &quot;username&quot;: &quot;test.user&quot;, &quot;name&quot;: &quot;test.user@gmail.de&quot;, &quot;state&quot;: &quot;active&quot;, &quot;avatar_url&quot;: &quot;&quot;, &quot;web_url&quot;: &quot;&quot; }, &quot;merge_user&quot;: { &quot;id&quot;: 2802, &quot;username&quot;: &quot;tes.user&quot;, &quot;name&quot;: &quot;test.user@gmail.de&quot;, &quot;state&quot;: &quot;active&quot;, &quot;avatar_url&quot;: &quot;&quot;, &quot;web_url&quot;: &quot;&quot; }, &quot;merged_at&quot;: &quot;2022-12-03T12:22:20.072Z&quot;, &quot;closed_by&quot;: null, &quot;closed_at&quot;: null, &quot;assignees&quot;: [], &quot;assignee&quot;: null, &quot;reviewers&quot;: [], &quot;source_project_id&quot;: 231, &quot;target_project_id&quot;: 231, &quot;labels&quot;: [], &quot;squash_commit_sha&quot;: null, &quot;discussion_locked&quot;: null, &quot;should_remove_source_branch&quot;: null, &quot;force_remove_source_branch&quot;: null, &quot;reference&quot;: &quot;!156&quot;, &quot;references&quot;: { &quot;short&quot;: &quot;!156&quot;, &quot;relative&quot;: &quot;!156&quot;, &quot;full&quot;: &quot;&quot; }, &quot;web_url&quot;: &quot;&quot;, &quot;time_stats&quot;: { &quot;time_estimate&quot;: 0, &quot;total_time_spent&quot;: 0, &quot;human_time_estimate&quot;: null, &quot;human_total_time_spent&quot;: null }, &quot;squash&quot;: false, &quot;task_completion_status&quot;: { &quot;count&quot;: 0, &quot;completed_count&quot;: 0 }, &quot;has_conflicts&quot;: false, &quot;blocking_discussions_resolved&quot;: true, &quot;approvals_before_merge&quot;: null }, { &quot;id&quot;: 39329289, &quot;iid&quot;: 156, &quot;project_id&quot;: 231, &quot;title&quot;: &quot;Repaired some Links&quot;, &quot;description&quot;: &quot;&quot;, &quot;state&quot;: &quot;merged&quot;, &quot;created_at&quot;: &quot;2022-12-03T12:22:14.690Z&quot;, &quot;updated_at&quot;: &quot;2022-12-03T12:22:20.060Z&quot;, &quot;merged_by&quot;: { &quot;id&quot;: 1000, &quot;username&quot;: &quot;test.user&quot;, &quot;name&quot;: &quot;test.user@gmail.de&quot;, &quot;state&quot;: &quot;active&quot;, &quot;avatar_url&quot;: &quot;&quot;, &quot;web_url&quot;: &quot;&quot; }, &quot;merge_user&quot;: { &quot;id&quot;: 2802, &quot;username&quot;: &quot;test.user&quot;, &quot;name&quot;: &quot;test.user@gmail.de&quot;, &quot;state&quot;: &quot;active&quot;, &quot;avatar_url&quot;: &quot;&quot;, &quot;web_url&quot;: &quot;&quot; }, &quot;merged_at&quot;: &quot;2022-12-03T12:22:20.072Z&quot;, &quot;closed_by&quot;: null, &quot;closed_at&quot;: null, &quot;assignees&quot;: [], &quot;assignee&quot;: null, &quot;reviewers&quot;: [], &quot;source_project_id&quot;: 231, &quot;target_project_id&quot;: 231, &quot;labels&quot;: [], &quot;squash_commit_sha&quot;: null, &quot;discussion_locked&quot;: null, &quot;should_remove_source_branch&quot;: null, &quot;force_remove_source_branch&quot;: null, &quot;reference&quot;: &quot;!156&quot;, &quot;references&quot;: { &quot;short&quot;: &quot;!156&quot;, &quot;relative&quot;: &quot;!156&quot;, &quot;full&quot;: &quot;&quot; }, &quot;web_url&quot;: &quot;&quot;, &quot;time_stats&quot;: { &quot;time_estimate&quot;: 0, &quot;total_time_spent&quot;: 0, &quot;human_time_estimate&quot;: null, &quot;human_total_time_spent&quot;: null }, &quot;squash&quot;: false, &quot;task_completion_status&quot;: { &quot;count&quot;: 0, &quot;completed_count&quot;: 0 }, &quot;has_conflicts&quot;: false, &quot;blocking_discussions_resolved&quot;: true, &quot;approvals_before_merge&quot;: null },] </code></pre> <p>I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.</p> <pre><code>console.log(merge_requests[0].merge_user.name); console.log(merge_requests[1].merge_user.name); </code></pre> <p>The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:</p> <pre><code> const arrTest = []; for(var i = 0; i &lt; Object.keys(merge_requests).length; i++) { var mergeUserName = merge_requests[i].merge_user.name; arrTest.push(mergeUserName); } console.log(arrTest); } </code></pre> <p>The code above leads to the following error: <code>Uncaught (in promise) TypeError: resultData[i].merge_user is null</code></p> <p>Here is a picture: <a href="https://i.stack.imgur.com/p5SaZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p5SaZ.png" alt="enter image description here" /></a></p> <p>I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.</p>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13382276/" ]
74,675,152
<p>I wrote a code like this:</p> <pre><code>Age: &lt;input type=&quot;text&quot; id=&quot;age&quot;&gt; </code></pre> <p>And JavaScript:</p> <pre><code>&lt;script&gt; function validateForm() { let age = document.getElementById(&quot;age&quot;).value; if (age) // is number? } &lt;/script&gt; </code></pre> <p>I want the input to give an error if the value entered is a letter, I will only accept numbers. How can I tell if the entered value is not a number?</p>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18003111/" ]
74,675,163
<p>I have tried changing a bunch of things in the CSS with classes and id's, but nothing seems to make it so that both images will be on the far side of the screen (logo on the far left and profile on the far right).</p> <p>Tried lots of different things like <code>text-align</code> and different <code>justify-contents</code> but nothing appears to work.</p> <p>Here is the code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.top-nav { display: flex; position: absolute; background-color: blue; opacity: 0.5; height: 10%; top: 0; width: 100%; left: 0; padding: 0; border: 0; margin: 0; list-style: none; } .top-nav div { display: flex; justify-content: space-between; height: 100%; margin: 0px; padding: 0; border: 0; margin: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="top-nav"&gt; &lt;div style="flex-grow: 1"&gt;&lt;img src="/textures/logo.svg"&gt;&lt;/div&gt; &lt;div style="flex-grow: 1"&gt;&lt;img src="/textures/profile.svg"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74675083, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "engines car.data.engines.reduce((a,b) => a+b,0)\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n const cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);" }, { "answer_id": 74675089, "author": "Metgher Andrei", "author_id": 19434894, "author_profile": "https://Stackoverflow.com/users/19434894", "pm_score": 0, "selected": false, "text": "const newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681660/" ]
74,675,191
<p>I am calling rest api which expects nonce header. The nonce must be unique timestamp and every consecutive call should have <em>timestamp &gt; previous one</em>. My goal is to launch 10 go routines and from each one do a call to the web api. Since we do not have control over the routine execution order we might end up doing a webapi call with a <em>nonce &lt; previous one</em>. I do not have control over the api implementation.</p> <p>I have stripped down my code to something very simple which illustrate the problem:</p> <pre><code>package main import ( &quot;fmt&quot; &quot;time&quot; ) func main() { count := 10 results := make(chan string, count) for i := 0; i &lt; 10; i++ { go someWork(results) // Enabling the following line would give the // expected outcome but does look like a hack to me. // time.Sleep(time.Millisecond) } for i := 0; i &lt; count; i++ { fmt.Println(&lt;-results) } } func someWork(done chan string) { // prepare http request, do http request, send to done chan the result done &lt;- time.Now().Format(&quot;15:04:05.00000&quot;) } </code></pre> <p>From the output you can see how we have timestamps which are not chronologically ordered:</p> <pre><code>13:18:26.98549 13:18:26.98560 13:18:26.98561 13:18:26.98553 13:18:26.98556 13:18:26.98556 13:18:26.98557 13:18:26.98558 13:18:26.98559 13:18:26.98555 </code></pre> <p>What would be the idiomatic way to achieve the expected outcome without adding the <em>sleep</em> line?</p> <p>Thanks!</p>
[ { "answer_id": 74675339, "author": "techdobycon", "author_id": 20681475, "author_profile": "https://Stackoverflow.com/users/20681475", "pm_score": 0, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nvar wg sync.WaitGroup = sync.WaitGroup{}\nvar ct int = 0\n\nfunc hello() {\n fmt.Printf(\"Hello Go %v\\n\", time.Now().Format(\"15:04:05.00000\"))\n // when you are done, call done:\n time.Sleep(time.Duration(10 * int(time.Second)))\n wg.Done()\n}\n\nfunc main() {\n for i := 0; i < 10; i++ {\n wg.Add(1)\n go hello()\n wg.Wait()\n }\n\n}\n" }, { "answer_id": 74678268, "author": "s3vt", "author_id": 19812413, "author_profile": "https://Stackoverflow.com/users/19812413", "pm_score": -1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nfunc main() {\n count := 10\n results := make(chan string, count)\n var mutex sync.Mutex\n for i := 0; i < count; i++ {\n go someWork(&mutex, results)\n }\n\n for i := 0; i < count; i++ {\n fmt.Println(<-results)\n }\n}\n\nfunc someWork(mut *sync.Mutex, done chan string) {\n // Lock the mutex, go routine getting lock here, \n // is guarranteed to create the timestamp and \n // perform the request before any other\n mut.Lock()\n // Get the timestamp\n myTimeStamp := time.Now().Format(\"15:04:05.00000\")\n //prepare http request, do http request\n //free the mutex\n mut.Unlock()\n\n // Process response\n // send to done chan the result\n done <- myTimeStamp\n}\n 21:24:03.36582\n21:24:03.36593\n21:24:03.36595\n21:24:03.36596\n21:24:03.36597\n21:24:03.36597\n21:24:03.36598\n21:24:03.36598\n21:24:03.36599\n21:24:03.36600\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3585843/" ]
74,675,207
<p>I'm trying to reload page with new params on state changed:</p> <pre><code>@Watch('workspace') onWorkspaceChanged(o: Workspace, n: Workspace){ if(o.type === n.type &amp;&amp; o.id === n.id) return; this.$router.push({name: this.$route.name as string, params: {id: `${n.id}`, type: `${ n.type == WorkspaceType.COMPANY ? COMPANY : PERSON }`}}); } </code></pre> <p>but receive error <code>Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: &quot;previous location&quot;.</code></p> <p>I expect path to be changed from /profile/c/123, where 'c' is type param and 123 is id param, to /profile/p/321 and vice versa</p>
[ { "answer_id": 74675339, "author": "techdobycon", "author_id": 20681475, "author_profile": "https://Stackoverflow.com/users/20681475", "pm_score": 0, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nvar wg sync.WaitGroup = sync.WaitGroup{}\nvar ct int = 0\n\nfunc hello() {\n fmt.Printf(\"Hello Go %v\\n\", time.Now().Format(\"15:04:05.00000\"))\n // when you are done, call done:\n time.Sleep(time.Duration(10 * int(time.Second)))\n wg.Done()\n}\n\nfunc main() {\n for i := 0; i < 10; i++ {\n wg.Add(1)\n go hello()\n wg.Wait()\n }\n\n}\n" }, { "answer_id": 74678268, "author": "s3vt", "author_id": 19812413, "author_profile": "https://Stackoverflow.com/users/19812413", "pm_score": -1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nfunc main() {\n count := 10\n results := make(chan string, count)\n var mutex sync.Mutex\n for i := 0; i < count; i++ {\n go someWork(&mutex, results)\n }\n\n for i := 0; i < count; i++ {\n fmt.Println(<-results)\n }\n}\n\nfunc someWork(mut *sync.Mutex, done chan string) {\n // Lock the mutex, go routine getting lock here, \n // is guarranteed to create the timestamp and \n // perform the request before any other\n mut.Lock()\n // Get the timestamp\n myTimeStamp := time.Now().Format(\"15:04:05.00000\")\n //prepare http request, do http request\n //free the mutex\n mut.Unlock()\n\n // Process response\n // send to done chan the result\n done <- myTimeStamp\n}\n 21:24:03.36582\n21:24:03.36593\n21:24:03.36595\n21:24:03.36596\n21:24:03.36597\n21:24:03.36597\n21:24:03.36598\n21:24:03.36598\n21:24:03.36599\n21:24:03.36600\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7727553/" ]
74,675,239
<p>I'm running Python 3.9.2 on a Raspberry Pi and I've written a script that will read water temperatures from my boiler and write them to a CSV file. However, each data item in the output file appears on a new line.</p> <p>Here's my code:</p> <pre><code>from subprocess import check_output import csv header = ['Flow', 'Return'] cmd = [&quot;/usr/bin/ebusctl&quot;, &quot;read&quot;, &quot;-f&quot;] data = [ [float(check_output([*cmd, &quot;FlowTemp&quot;, &quot;temp&quot;]))], [float(check_output([*cmd, &quot;ReturnTemp&quot;, &quot;temp&quot;]))] ] with open('sandbox.csv', 'w', encoding='utf8', newline='') as f: writer = csv.writer(f) writer.writerow(header) writer.writerows(data) </code></pre> <p>And here's the content of sandbox.csv:</p> <pre class="lang-none prettyprint-override"><code>Flow,Return 57.19 43.12 </code></pre> <p>How could I fix this?</p>
[ { "answer_id": 74675339, "author": "techdobycon", "author_id": 20681475, "author_profile": "https://Stackoverflow.com/users/20681475", "pm_score": 0, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nvar wg sync.WaitGroup = sync.WaitGroup{}\nvar ct int = 0\n\nfunc hello() {\n fmt.Printf(\"Hello Go %v\\n\", time.Now().Format(\"15:04:05.00000\"))\n // when you are done, call done:\n time.Sleep(time.Duration(10 * int(time.Second)))\n wg.Done()\n}\n\nfunc main() {\n for i := 0; i < 10; i++ {\n wg.Add(1)\n go hello()\n wg.Wait()\n }\n\n}\n" }, { "answer_id": 74678268, "author": "s3vt", "author_id": 19812413, "author_profile": "https://Stackoverflow.com/users/19812413", "pm_score": -1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nfunc main() {\n count := 10\n results := make(chan string, count)\n var mutex sync.Mutex\n for i := 0; i < count; i++ {\n go someWork(&mutex, results)\n }\n\n for i := 0; i < count; i++ {\n fmt.Println(<-results)\n }\n}\n\nfunc someWork(mut *sync.Mutex, done chan string) {\n // Lock the mutex, go routine getting lock here, \n // is guarranteed to create the timestamp and \n // perform the request before any other\n mut.Lock()\n // Get the timestamp\n myTimeStamp := time.Now().Format(\"15:04:05.00000\")\n //prepare http request, do http request\n //free the mutex\n mut.Unlock()\n\n // Process response\n // send to done chan the result\n done <- myTimeStamp\n}\n 21:24:03.36582\n21:24:03.36593\n21:24:03.36595\n21:24:03.36596\n21:24:03.36597\n21:24:03.36597\n21:24:03.36598\n21:24:03.36598\n21:24:03.36599\n21:24:03.36600\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681553/" ]
74,675,245
<p>I know there a bazillion question like this, but I couldn't find a good answer. I'm compiling a source with preprocessor tokens defined in CFLAGS:</p> <p>-D X=string1 -D Y=string2</p> <p>I'm trying to create a string literal in my header file that combines these two values and use it in my sources like:</p> <pre><code>printf(&quot;%s&quot;, COMBINED); </code></pre> <p>But this doesn't work:</p> <pre><code> #define _COMBINED(x, y) x ## y #define COMBINED _COMBINED(X, Y) </code></pre> <p>Thanks</p>
[ { "answer_id": 74675339, "author": "techdobycon", "author_id": 20681475, "author_profile": "https://Stackoverflow.com/users/20681475", "pm_score": 0, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nvar wg sync.WaitGroup = sync.WaitGroup{}\nvar ct int = 0\n\nfunc hello() {\n fmt.Printf(\"Hello Go %v\\n\", time.Now().Format(\"15:04:05.00000\"))\n // when you are done, call done:\n time.Sleep(time.Duration(10 * int(time.Second)))\n wg.Done()\n}\n\nfunc main() {\n for i := 0; i < 10; i++ {\n wg.Add(1)\n go hello()\n wg.Wait()\n }\n\n}\n" }, { "answer_id": 74678268, "author": "s3vt", "author_id": 19812413, "author_profile": "https://Stackoverflow.com/users/19812413", "pm_score": -1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nfunc main() {\n count := 10\n results := make(chan string, count)\n var mutex sync.Mutex\n for i := 0; i < count; i++ {\n go someWork(&mutex, results)\n }\n\n for i := 0; i < count; i++ {\n fmt.Println(<-results)\n }\n}\n\nfunc someWork(mut *sync.Mutex, done chan string) {\n // Lock the mutex, go routine getting lock here, \n // is guarranteed to create the timestamp and \n // perform the request before any other\n mut.Lock()\n // Get the timestamp\n myTimeStamp := time.Now().Format(\"15:04:05.00000\")\n //prepare http request, do http request\n //free the mutex\n mut.Unlock()\n\n // Process response\n // send to done chan the result\n done <- myTimeStamp\n}\n 21:24:03.36582\n21:24:03.36593\n21:24:03.36595\n21:24:03.36596\n21:24:03.36597\n21:24:03.36597\n21:24:03.36598\n21:24:03.36598\n21:24:03.36599\n21:24:03.36600\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11881725/" ]
74,675,273
<p>I have a function below that returns a random INTERVAL between a range of hours, which appears to be working fine but is currently limited to hours only.</p> <p>I would would like to expand this functionality to also support returning a random INTERVAL for days, minutes by passing in a literal (ie 'DAY', 'MINUTE' or 'SECOND')</p> <p>For example if I call random_interval (1,4, 'DAY') I would get something like this +000000002 11:24:43.000000000 or if i call random_interval (20,40, 'MINUTE') I would get something like +000000000 00:24:44.000000000</p> <p>Thanks in advance to all who answer and for your time and expertise.</p> <pre><code> CREATE OR REPLACE FUNCTION random_interval( p_min_hours IN NUMBER, p_max_hours IN NUMBER ) RETURN INTERVAL DAY TO SECOND IS BEGIN RETURN floor(dbms_random.value(p_min_hours, p_max_hours)) * interval '1' hour + floor(dbms_random.value(0, 60)) * interval '1' minute + floor(dbms_random.value(0, 60)) * interval '1' second; END random_interval; / SELECT random_interval(1, 10) as random_val FROM dual CONNECT BY level &lt;= 10 order by 1 RANDOM_VAL +000000000 01:04:03.000000000 +000000000 03:14:52.000000000 +000000000 04:39:42.000000000 +000000000 05:00:39.000000000 +000000000 05:03:28.000000000 +000000000 07:03:19.000000000 +000000000 07:06:13.000000000 +000000000 08:50:55.000000000 +000000000 09:10:02.000000000 +000000000 09:26:44.000000000 </code></pre>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16771377/" ]
74,675,276
<p>Hello I have a dataframe such as :</p> <pre><code>Species COL1 COL2 COL3 COL4 COL5 SP1 0 0 0 1-2 0-1-2 SP2 1-2 2 0 1 0 SP3 0-1 1 2 0 1-2 </code></pre> <p>and I would like to add new columns to count for each row the number of specific unique values such as :</p> <pre><code>Species COL1 COL2 COL3 COL4 COL5 count_0 count_1-2 count_0-1-2 count_1 count_2 SP1 0 0 0 1-2 0-1-2 3 1 1 0 0 SP2 1-2 2 0 1 0 2 1 0 1 1 SP3 0-1 1 2 0 1-2 1 1 0 2 1 </code></pre> <p>Does someone have na idea please ?</p>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12559770/" ]
74,675,330
<p>I'm trying to upload some files, but when I upload a file that already exists in the path, it overwrites the existing file. I'm trying to get the files renamed if a file with same name exists in the path, such that if file.pdf gets uploaded, it gets renamed file(1).pdf if there is an existing file that goes by file.pdf.</p> <p><code>Code</code></p> <pre><code>public async Task OnInputFile(InputFileChangeEventArgs e) { selectedFiles = e.GetMultipleFiles(); Message = $&quot;{selectedFiles.Count} file(s) selected&quot;; this.StateHasChanged(); foreach (var file in selectedFiles) { Stream stream = file.OpenReadStream(maxAllowedSize: 10_000_000); var path = Path.Combine(Directory.GetCurrentDirectory(), &quot;FilePath&quot;, file.Name); FileStream fs = File.Create(path); await stream.CopyToAsync(fs); fs.Close(); stream.Close(); } Message = $&quot;{selectedFiles.Count} file(s) uploaded on server&quot;; this.StateHasChanged(); } </code></pre> <p>Can anyone help me resolve this problem?</p>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20373344/" ]
74,675,349
<p>I got some error but I couldnt fix it. I want to add a new city with a country name but country id (if exists) will not change in database(it wont add with a new id).</p> <p>Here is my City class;</p> <pre><code> [Table(&quot;Cities&quot;)] public class City { [Key] public int Id { get; set; } [Required] [StringLength(30)] public string Name { get; set; } [ForeignKey(&quot;Countries&quot;)] public int CountryId { get; set; } public Country Country { get; set; } } </code></pre> <p>And here is my Country class;</p> <pre><code>[Table(&quot;Countries&quot;)] public class Country { [Key] public int Id { get; set; } [Required] [StringLength(30)] public string Name { get; set; } public ICollection&lt;City&gt; Cities { get; set; } } </code></pre> <p>I used CQRS and Mediator design patterns.</p> <p>This is my Create Command;</p> <pre><code> public class CreateCityCommand : IRequest&lt;City&gt; { public City City { get; set; } } </code></pre> <p>This is my Create Command Handler;</p> <pre><code>public class CreateCityCommandHandler : IRequestHandler&lt;CreateCityCommand, City&gt; { private readonly EssoContext _context; public CreateCityCommandHandler(EssoContext context) { _context = context; } public async Task&lt;City&gt; Handle(CreateCityCommand request, CancellationToken cancellationToken) { var check = await _context.City.FirstOrDefaultAsync(c =&gt; c.Name == request.City.Name); if (check != null) { throw new InvalidOperationException(&quot;You cannot add the same value!!!&quot;); } _context.City.Add(request.City); await _context.SaveChangesAsync(); return request.City; } } </code></pre> <p>And here is my controller;</p> <pre><code>[HttpPost(&quot;Create&quot;)] public async Task&lt;ActionResult&lt;City&gt;&gt; PostCity([FromBody] City city) { try { var command = new CreateCityCommand() { City = city }; var result = await _mediator.Send(command); return Ok(result); } catch(Exception ex) { return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message); } } </code></pre> <p><a href="https://i.stack.imgur.com/jDumY.jpg" rel="nofollow noreferrer">This is swagger output (seeing countries)</a></p> <p>Every city has a country, and each country may have many cities. That's why i used CountryId and property (as FK) in City class. In country class, i defined collection(list) of cities. But I dont know what is the problem. Thanks for help...</p>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13038711/" ]
74,675,378
<p>Increammentally derive ID from a **name ** column and on next load if there are new values added to that <strong>name</strong> column then assign ned ID which is not already assigned to previous data <strong>Example:</strong> <strong>first load</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>a</td> </tr> <tr> <td>b</td> </tr> <tr> <td>b</td> </tr> <tr> <td>a</td> </tr> </tbody> </table> </div> <p>result</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th style="text-align: center;">Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: center;">a</td> </tr> <tr> <td>2</td> <td style="text-align: center;">b</td> </tr> <tr> <td>2</td> <td style="text-align: center;">b</td> </tr> <tr> <td>1</td> <td style="text-align: center;">a</td> </tr> </tbody> </table> </div> <p><strong>next load</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>a</td> </tr> <tr> <td>b</td> </tr> <tr> <td>b</td> </tr> <tr> <td>a</td> </tr> <tr> <td>c</td> </tr> <tr> <td>d</td> </tr> <tr> <td>c</td> </tr> </tbody> </table> </div> <p>result</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th style="text-align: center;">Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: center;">a</td> </tr> <tr> <td>2</td> <td style="text-align: center;">b</td> </tr> <tr> <td>2</td> <td style="text-align: center;">b</td> </tr> <tr> <td>1</td> <td style="text-align: center;">a</td> </tr> <tr> <td>3</td> <td style="text-align: center;">c</td> </tr> <tr> <td>4</td> <td style="text-align: center;">d</td> </tr> <tr> <td>3</td> <td style="text-align: center;">c</td> </tr> </tbody> </table> </div> <p>As described in question looking for a solution in PySpark</p>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13249628/" ]
74,675,391
<p>I want to make a wavy text animation why when the script I made the animation doesn't run. I use mark aiming to mark 1 sentence, that's why I don't use span.</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>// Wrap every letter in a span var textWrapper2 = document.querySelector(".ml7 .letters2"); textWrapper2.innerHTML = textWrapper2.textContent.replace(/\S/g, "&lt;mark class='letters2'&gt;$&amp;&lt;/mark&gt;"); anime .timeline({ loop: true }) .add({ targets: ".ml7 .letters2", translateY: ["1.1em", 0], translateZ: 0, duration: 750, delay: (el, i) =&gt; 50 * i, }) .add({ targets: ".ml7", opacity: 0, duration: 1000, easing: "easeOutExpo", delay: 1000, });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.m17 .letters2 { display: inline-block; line-height: 1em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="m17"&gt; &lt;h1 class="text-wrapper2"&gt;text &lt;mark&gt;wrapper&lt;/mark class=letters2&gt; dropDown&lt;/h1&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>I want to make an animation in the text that I have marked. Can you help me to correct my wrong script, or additional scripts or new scripts.</p>
[ { "answer_id": 74675309, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 3, "selected": true, "text": "\nCREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER, \n p_period VARCHAR2\n ) RETURN INTERVAL DAY TO SECOND\n IS\n BEGIN\n IF p_period = 'HOUR' THEN \n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second;\n ELSE IF p_period = 'DAY' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' day\n + floor(dbms_random.value(0, 24)) * interval '1' hour\n + floor(dbms_random.value(0, 60)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'MINUTE' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' minute\n + floor(dbms_random.value(0, 60)) * interval '1' second; \n ELSE IF p_period = 'SECOND' THEN\n RETURN floor(dbms_random.value(p_min, p_max)) * interval '1' second;\n ELSE \n RETURN NULL;\n END IF;\nEND random_interval;\n/\n\nSELECT random_interval(1, 10, 'DAY') as random_val FROM dual CONNECT BY level <= 10 order by 1\n\nRANDOM_VAL\n+000000003 02:46:09.000000000\n+000000004 19:19:56.000000000\n+000000002 11:24:43.000000000\n+000000002 16:20:44.000000000\n+000000001 22:24:30.000000000\n+000000002 15:14:38.000000000\n+000000003 00:48:03.000000000\n+000000003 18:08:13.000000000\n+000000002 01:05:34.000000000\n+000000002 08:12:19.000000000\n" }, { "answer_id": 74681421, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "DBMS_RANDOM.VALUE(lower_bound, upper_bound) NUMTODSINTERVAL(amount, duration) SELECT NUMTODSINTERVAL(\n DBMS_RANDOM.VALUE(1, 3),\n 'MINUTE'\n )\nFROM DUAL;\n CREATE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\nBEGIN\n RETURN NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nEND;\n/\n CREATE OR REPLACE FUNCTION random_interval(\n p_min IN NUMBER,\n p_max IN NUMBER,\n p_duration IN VARCHAR2\n) RETURN INTERVAL DAY TO SECOND\nIS\n v_interval INTERVAL DAY TO SECOND := NUMTODSINTERVAL(DBMS_RANDOM.VALUE(p_min, p_max), p_duration);\nBEGIN\n RETURN ( EXTRACT(DAY FROM v_interval) * 24 * 60 * 60\n + EXTRACT(HOUR FROM v_interval) * 60 * 60\n + EXTRACT(MINUTE FROM v_interval) * 60\n + FLOOR(EXTRACT(SECOND FROM v_interval))\n ) * INTERVAL '1' SECOND;\nEND;\n/\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802096/" ]
74,675,402
<p>What I want to do is to create string stream , and output stream, giving the buffer of string stream to output stream, so that it will output data to the string stream. Everything seems fine, but when I try to add data to buffer of the string stream it overrides the previous data. My question is why? and how can achieve a result, such that it does not override but simply adds to the string stream. Here is my code below:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;sstream&gt; using namespace std; int main () { stringstream s1(&quot;hello I am string stream&quot;); streambuf *s1_bfr = s1.rdbuf(); ostream my_stream (s1_bfr); my_stream &lt;&lt;&quot;hey&quot;&lt;&lt;endl; cout &lt;&lt;s1.rdbuf()&lt;&lt;endl; //gives the result : &quot; hey o I am string stream&quot;( seems to me overriden) return 0; } </code></pre>
[ { "answer_id": 74675723, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 3, "selected": true, "text": "stringstream ostream ostream ostream stringstream stringstream s1(\"hello I am string stream\");\nstreambuf *s1_bfr = s1.rdbuf();\nostream my_stream (s1_bfr);\nmy_stream.seekp(0, ios_base::end); // move the write position to the end of the stream\nmy_stream <<\"hey\"<<endl;\ncout <<s1.rdbuf()<<endl;\n stringstream::str stringstream string string stringstream s1(\"hello I am string stream\");\nstring str = s1.str();\nstr += \"hey\\n\";\ns1.str(str);\ncout <<s1.rdbuf()<<endl;\n" }, { "answer_id": 74675868, "author": "Sourabh Burse", "author_id": 14836744, "author_profile": "https://Stackoverflow.com/users/14836744", "pm_score": 1, "selected": false, "text": " #include <iostream>\n #include <iomanip>\n #include <string>\n #include <sstream>\n \n using namespace std;\n \n int main() {\n stringstream s1(\"hello I am string stream\");\n streambuf *s1_bfr = s1.rdbuf();\n stringstream temp; //Create a temp stringsteam\n temp << \"hey\"; //add desired string into the stream\n temp << s1_bfr; //then add your orignal stream\n s1 = move(temp); // or ss.swap(temp); \n cout <<s1_bfr<<endl;\n \n return 0;\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15431634/" ]
74,675,417
<p>I would like to count the number of color changes in a network using a function.</p> <p>A change would be <code>&quot;red&quot;</code> to <code>&quot;green&quot;</code> (from <code>a</code> to <code>b</code> in the example)</p> <p>Overlaps (e.g., <code>&quot;green&quot;</code> to <code>&quot;green&quot;</code> and <code>&quot;orange&quot;</code>, from <code>c</code> to <code>c1</code> in the example) should not count as a change.</p> <p>Example data:</p> <pre><code>library(tidyverse) network &lt;- tibble( from=c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;), to= c(&quot;b&quot;,&quot;c&quot;,&quot;c1&quot;,&quot;c2&quot;)) colors &lt;- list( a=list(&quot;red&quot;), b=list(&quot;red&quot;), c=list(&quot;green&quot;), c1=list(&quot;green&quot;,&quot;orange&quot;), c2=list(&quot;blue&quot;,&quot;black&quot;) ) </code></pre> <p>The correct output of the function would be 2 (from <code>b</code> to <code>c</code> and <code>c</code> to <code>c2</code>) in this example.</p>
[ { "answer_id": 74675723, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 3, "selected": true, "text": "stringstream ostream ostream ostream stringstream stringstream s1(\"hello I am string stream\");\nstreambuf *s1_bfr = s1.rdbuf();\nostream my_stream (s1_bfr);\nmy_stream.seekp(0, ios_base::end); // move the write position to the end of the stream\nmy_stream <<\"hey\"<<endl;\ncout <<s1.rdbuf()<<endl;\n stringstream::str stringstream string string stringstream s1(\"hello I am string stream\");\nstring str = s1.str();\nstr += \"hey\\n\";\ns1.str(str);\ncout <<s1.rdbuf()<<endl;\n" }, { "answer_id": 74675868, "author": "Sourabh Burse", "author_id": 14836744, "author_profile": "https://Stackoverflow.com/users/14836744", "pm_score": 1, "selected": false, "text": " #include <iostream>\n #include <iomanip>\n #include <string>\n #include <sstream>\n \n using namespace std;\n \n int main() {\n stringstream s1(\"hello I am string stream\");\n streambuf *s1_bfr = s1.rdbuf();\n stringstream temp; //Create a temp stringsteam\n temp << \"hey\"; //add desired string into the stream\n temp << s1_bfr; //then add your orignal stream\n s1 = move(temp); // or ss.swap(temp); \n cout <<s1_bfr<<endl;\n \n return 0;\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11482110/" ]
74,675,452
<p><a href="https://i.stack.imgur.com/lL4Sf.png" rel="nofollow noreferrer">the html tag</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class=""&gt;&lt;div&gt;Bengaluru, Karnataka&lt;/div&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Consider the above example for reference.</p> <p>I tried the following code but it doesn't work!!!</p> <p>driver.find_element(By.XPATH,'//div[@class=&quot;&quot;]').text.strip()</p>
[ { "answer_id": 74675723, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 3, "selected": true, "text": "stringstream ostream ostream ostream stringstream stringstream s1(\"hello I am string stream\");\nstreambuf *s1_bfr = s1.rdbuf();\nostream my_stream (s1_bfr);\nmy_stream.seekp(0, ios_base::end); // move the write position to the end of the stream\nmy_stream <<\"hey\"<<endl;\ncout <<s1.rdbuf()<<endl;\n stringstream::str stringstream string string stringstream s1(\"hello I am string stream\");\nstring str = s1.str();\nstr += \"hey\\n\";\ns1.str(str);\ncout <<s1.rdbuf()<<endl;\n" }, { "answer_id": 74675868, "author": "Sourabh Burse", "author_id": 14836744, "author_profile": "https://Stackoverflow.com/users/14836744", "pm_score": 1, "selected": false, "text": " #include <iostream>\n #include <iomanip>\n #include <string>\n #include <sstream>\n \n using namespace std;\n \n int main() {\n stringstream s1(\"hello I am string stream\");\n streambuf *s1_bfr = s1.rdbuf();\n stringstream temp; //Create a temp stringsteam\n temp << \"hey\"; //add desired string into the stream\n temp << s1_bfr; //then add your orignal stream\n s1 = move(temp); // or ss.swap(temp); \n cout <<s1_bfr<<endl;\n \n return 0;\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20327977/" ]
74,675,467
<p>I have a MSSQL database table <code>Events</code>. I am worried that performance could be improved.</p> <pre><code>EventId LocationId Start End Quantity Price Currency 1 4 2022-08-31 22:00:00.0000000 +02:00 2022-08-31 23:00:00.0000000 +02:00 7.50000 2.0 EUR 2 2 2022-04-04 19:00:00.0000000 +01:00 2022-04-04 20:00:00.0000000 +01:00 1.50000 7.5 EUR 3 2 2022-04-04 19:00:00.0000000 +01:00 2022-04-04 20:00:00.0000000 +01:00 4.00000 8.2 EUR </code></pre> <p>I already have the following index:</p> <pre><code>CREATE NONCLUSTERED INDEX [IDX__Events__Location_Start_End] on [Events] ( [LocationId] asc, [Start] asc, [End] asc ) </code></pre> <p>But Azure suggests that I create this index (medium impact):</p> <pre><code>CREATE NONCLUSTERED INDEX [IDX__Events__Location_End] ON [dbo].[Events] ([LocationId], [End]) INCLUDE ([Currency], [Price], [Quantity], [Start]) WITH (ONLINE = ON) </code></pre> <p>Hint: I do a lot of queries where I select Events greater than a start time and less than an end time.</p> <p>Why is this extra index useful? Should I change my first index instead?</p> <p><strong>EDIT</strong>:</p> <p>I run this code (EF Core) very often:</p> <pre><code>var relevantEvents = await _events.Where($@&quot; [{nameof(Events.LocationId)}] = @locationId and [{nameof(Events.End)}] &gt; @start and [{nameof(Events.Start)}] &lt; @end &quot;, args); </code></pre> <p>Besides that, I upsert to the table often as well.</p>
[ { "answer_id": 74677135, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 2, "selected": false, "text": "LocationId End Start LocationId, End LocationId, Start key LocationId, Start LocationId, End Start < @end INCLUDE ([Currency], [Price], [Quantity]) LocationId, End LocationId, Start CREATE TABLE dbo.Events\n(\nEventId INT IDENTITY PRIMARY KEY, \nLocationId INT, \nStart DATETIME2,\n[End] DATETIME2,\nQuantity DECIMAL(10,6),\nPrice DECIMAL(10,2),\nCurrency CHAR(3),\nINDEX IDX__Events__Location_Start_End(LocationId, Start, [End]),\nINDEX IDX__Events__Location_End(LocationId, [End]) INCLUDE (Start)\n)\n\n\nINSERT INTO dbo.Events\n(LocationId, Start,[End], Quantity, Price,Currency)\nSELECT LocationId = 1,\n Start = DATEADD(SECOND, -Num, GETDATE()),\n [End] = DATEADD(SECOND, 60-Num, GETDATE()),\n Qty = 7.5,\n Price = 2,\n Currency = 'EUR'\nFROM \n(\nSELECT TOP 1000000 Num = ROW_NUMBER() OVER (ORDER BY @@SPID)\nFROM sys.all_columns c1, sys.all_columns c2\n) Nums\n\n\nDECLARE @Start DATE = GETDATE(), @End DATE = DATEADD(DAY, 1, GETDATE())\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_Start_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331755/" ]
74,675,507
<p>Probably a dumb question but I'm using toTimestamp(now()) to retrieve the timestamp. Is there any way to offset the now() by my specified timeframe.</p> <p>What I have now:</p> <pre><code>&gt; print(session.execute('SELECT toTimestamp(now()) FROM system.local').one()) 2022-12-04 12:12:47.011000 </code></pre> <p>My goal:</p> <pre><code>&gt; print(session.execute('SELECT toTimestamp(now() - 1h) FROM system.local').one()) 2022-12-04 11:12:47.011000 </code></pre>
[ { "answer_id": 74677135, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 2, "selected": false, "text": "LocationId End Start LocationId, End LocationId, Start key LocationId, Start LocationId, End Start < @end INCLUDE ([Currency], [Price], [Quantity]) LocationId, End LocationId, Start CREATE TABLE dbo.Events\n(\nEventId INT IDENTITY PRIMARY KEY, \nLocationId INT, \nStart DATETIME2,\n[End] DATETIME2,\nQuantity DECIMAL(10,6),\nPrice DECIMAL(10,2),\nCurrency CHAR(3),\nINDEX IDX__Events__Location_Start_End(LocationId, Start, [End]),\nINDEX IDX__Events__Location_End(LocationId, [End]) INCLUDE (Start)\n)\n\n\nINSERT INTO dbo.Events\n(LocationId, Start,[End], Quantity, Price,Currency)\nSELECT LocationId = 1,\n Start = DATEADD(SECOND, -Num, GETDATE()),\n [End] = DATEADD(SECOND, 60-Num, GETDATE()),\n Qty = 7.5,\n Price = 2,\n Currency = 'EUR'\nFROM \n(\nSELECT TOP 1000000 Num = ROW_NUMBER() OVER (ORDER BY @@SPID)\nFROM sys.all_columns c1, sys.all_columns c2\n) Nums\n\n\nDECLARE @Start DATE = GETDATE(), @End DATE = DATEADD(DAY, 1, GETDATE())\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_Start_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17671554/" ]
74,675,512
<p>Update, I have created a signal file like this, so for example if an employer has created a shift, the admin will get an email notification like this:</p> <pre><code>from django.db.models.signals import post_save from django.dispatch import receiver from .models import Shift from django.core.mail import send_mail @receiver(post_save, sender=Shift) def send_mail_to_user(sender, instance, created, **kwargs): if created: send_mail( 'A new shift has been created by employer xxx', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) </code></pre> <p>Original post:</p> <p>Hi, I 'm trying to add signals when an employer or admin/staff has created a shift. Currently I have a view like this, I 'm wondering how should I modify it so I can have a post-save signal?</p> <pre><code>@login_required @admin_staff_employer_required def createShift(request): user=request.user employer=Employer.objects.all() form = CreateShiftForm() if request.method == 'POST': form = CreateShiftForm(request.POST) if form.is_valid(): form.save() messages.success(request, &quot;The shift has been created&quot;) return redirect('/shifts') else: messages.error(request,&quot;Please correct your input field and try again&quot;) context = {'form':form} return render(request, 'create_shift.html', context) </code></pre> <p>Thanks for your help!</p>
[ { "answer_id": 74677135, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 2, "selected": false, "text": "LocationId End Start LocationId, End LocationId, Start key LocationId, Start LocationId, End Start < @end INCLUDE ([Currency], [Price], [Quantity]) LocationId, End LocationId, Start CREATE TABLE dbo.Events\n(\nEventId INT IDENTITY PRIMARY KEY, \nLocationId INT, \nStart DATETIME2,\n[End] DATETIME2,\nQuantity DECIMAL(10,6),\nPrice DECIMAL(10,2),\nCurrency CHAR(3),\nINDEX IDX__Events__Location_Start_End(LocationId, Start, [End]),\nINDEX IDX__Events__Location_End(LocationId, [End]) INCLUDE (Start)\n)\n\n\nINSERT INTO dbo.Events\n(LocationId, Start,[End], Quantity, Price,Currency)\nSELECT LocationId = 1,\n Start = DATEADD(SECOND, -Num, GETDATE()),\n [End] = DATEADD(SECOND, 60-Num, GETDATE()),\n Qty = 7.5,\n Price = 2,\n Currency = 'EUR'\nFROM \n(\nSELECT TOP 1000000 Num = ROW_NUMBER() OVER (ORDER BY @@SPID)\nFROM sys.all_columns c1, sys.all_columns c2\n) Nums\n\n\nDECLARE @Start DATE = GETDATE(), @End DATE = DATEADD(DAY, 1, GETDATE())\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_Start_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11118289/" ]
74,675,514
<p>I have tried everything to serve my media file but yet getting same 404 error. Please guide.</p> <p>My docker-compose file:</p> <pre><code>version: &quot;3.9&quot; services: nginx: container_name: realestate_preprod_nginx_con build: ./nginx volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.8 expose: - 8000 depends_on: - realestate_frontend - realestate_backend real_estate_master_db: image: postgres:latest container_name: realestate_master_db_con env_file: - &quot;./database/master_env&quot; restart: &quot;always&quot; networks: glory1network: ipv4_address: 10.1.1.5 expose: - 5432 volumes: - real_estate_master_db_volume:/var/lib/postgresql/data real_estate_tenant1_db: image: postgres:latest container_name: realestate_tenant1_db_con env_file: - &quot;./database/tenant1_env&quot; restart: &quot;always&quot; networks: glory1network: ipv4_address: 10.1.1.9 expose: - 5432 volumes: - real_estate_tenant1_db_volume:/var/lib/postgresql/data realestate_frontend: image: realestate_web_frontend_service container_name: realestate_frontend_con restart: &quot;always&quot; build: ./frontend command: bash -c &quot;./realestate_frontend_ctl.sh&quot; expose: - 8092 networks: glory1network: ipv4_address: 10.1.1.6 depends_on: - real_estate_master_db - real_estate_tenant1_db realestate_backend: image: realestate_web_backend_service container_name: realestate_backend_con restart: &quot;always&quot; build: ./backend command: bash -c &quot;./realestate_backend_ctl.sh&quot; expose: - 8091 volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.7 env_file: - &quot;./database/env&quot; depends_on: - realestate_frontend - real_estate_master_db - real_estate_tenant1_db networks: glory1network: external: true volumes: real_estate_master_db_volume: real_estate_tenant1_db_volume: static_volume: media_volume: </code></pre> <p>My nginx configuration file:</p> <pre><code>upstream realestate_frontend_site { server realestate_frontend:8092; } server { listen 8000; access_log /home/inara/RealEstatePreProd/realestate_frontend-access.log; error_log /home/inara/RealEstatePreProd/realestate_frontend-error.log; client_max_body_size 0; location / { proxy_pass http://realestate_frontend_site; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 0; } } upstream realestate_backend_site { server realestate_backend:8091; } server { listen 8000; access_log /home/inara/RealEstatePreProd/realestate_backend-access.log; error_log /home/inara/RealEstatePreProd/realestate_backend-error.log; location / { proxy_pass http://realestate_backend_site; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { root /home/inara/RealEstatePreProd; } location /media/ { alias /home/inara/RealEstatePreProd/media/; } } </code></pre> <p>All the APIs are working fine but any media file gives 404.</p> <p>I have checked the volume and validated that files being accessed are present there. I logged in my docker container and validated file presence in media folder there too.</p> <p>Please guide what did I miss ??</p> <p>I expect to access my media files but getting 404</p>
[ { "answer_id": 74677135, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 2, "selected": false, "text": "LocationId End Start LocationId, End LocationId, Start key LocationId, Start LocationId, End Start < @end INCLUDE ([Currency], [Price], [Quantity]) LocationId, End LocationId, Start CREATE TABLE dbo.Events\n(\nEventId INT IDENTITY PRIMARY KEY, \nLocationId INT, \nStart DATETIME2,\n[End] DATETIME2,\nQuantity DECIMAL(10,6),\nPrice DECIMAL(10,2),\nCurrency CHAR(3),\nINDEX IDX__Events__Location_Start_End(LocationId, Start, [End]),\nINDEX IDX__Events__Location_End(LocationId, [End]) INCLUDE (Start)\n)\n\n\nINSERT INTO dbo.Events\n(LocationId, Start,[End], Quantity, Price,Currency)\nSELECT LocationId = 1,\n Start = DATEADD(SECOND, -Num, GETDATE()),\n [End] = DATEADD(SECOND, 60-Num, GETDATE()),\n Qty = 7.5,\n Price = 2,\n Currency = 'EUR'\nFROM \n(\nSELECT TOP 1000000 Num = ROW_NUMBER() OVER (ORDER BY @@SPID)\nFROM sys.all_columns c1, sys.all_columns c2\n) Nums\n\n\nDECLARE @Start DATE = GETDATE(), @End DATE = DATEADD(DAY, 1, GETDATE())\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_Start_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n\nSELECT COUNT(*)\nFROM dbo.Events WITH (INDEX = IDX__Events__Location_End)\nWHERE LocationId = 1 AND [End] > @Start AND Start < @End\nOPTION (RECOMPILE)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20681969/" ]
74,675,562
<p>I'm currently training on codewars, and today was multiples of 3 and 5. I tried with a casual solution using reduce + ternary, and it worked.</p> <p>I then tried to solve it with recusrive function. Instructions are as follow :</p> <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).</p> <p>Link is here</p> <p><a href="https://www.codewars.com/kata/514b92a657cdc65150000006" rel="nofollow noreferrer">https://www.codewars.com/kata/514b92a657cdc65150000006</a></p> <p>Here is my solution :</p> <pre><code>let res = 0 function solution(n){ if(n - 1 &lt;= 0) { return 0 } if((n - 1) % 3 &gt; 0) { if((n - 1) % 5 &gt; 0) { return solution(n - 1, res) } else { res += n - 1 solution(n - 1, res) } } else { res += n - 1 solution(n - 1, res) } return res } </code></pre> <p>It works on my computer but fails on codewars attemps, giving extravagant results, such as solution(6) = 9283 whereas on my computer 8 (correct answer)</p> <p>Also, I got the maximum call stack exceeded on codewars for 9513, but not on my computer.</p> <p>Ideas anyone ?</p>
[ { "answer_id": 74675592, "author": "yanai edri", "author_id": 5841996, "author_profile": "https://Stackoverflow.com/users/5841996", "pm_score": 3, "selected": true, "text": "function solution(number) {\n // Base case: return 0 if the number is negative\n if (number < 0) {\n return 0;\n }\n\n // Recursive case: if the number is a multiple of 3 or 5, add it to the sum of\n // the multiples of 3 or 5 below it, otherwise just return the sum of the\n // multiples of 3 or 5 below it\n return (number % 3 === 0 || number % 5 === 0)\n ? number + solution(number - 1)\n : solution(number - 1);\n}\n" }, { "answer_id": 74675629, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 0, "selected": false, "text": "res res function solution(n) {\n let res = 0;\n\n function _solution(n) {\n if(n <= 0) {\n return 0;\n }\n\n if(n % 3 != 0 && n % 5 != 0) {\n return _solution(n - 1);\n }\n\n res += n;\n _solution(n - 1);\n return res;\n }\n\n return _solution(n - 1);\n}\n res" }, { "answer_id": 74675788, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "const input = 10\n\nfunction sum35(num){\n num = num - 1\n const lastThree = num - num%3\n const threeQuantity = lastThree/3\n \n const lastFive = num - num%5\n const fiveQuantity = lastFive/5\n \n return getSum(threeQuantity,3,lastThree) + getSum(fiveQuantity, 5, lastFive)\n \n function getSum(n, first, last) {\n return (n/2)*(first + last)\n }\n}\n\nconsole.log(sum35(10))" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8002971/" ]
74,675,584
<p>I have a table like this-</p> <pre><code>Hotel Earning Abu 1000 Zain 400 Show 500 Zint 300 Abu 500 Zain 700 Abu 500 Abu 500 Abu 800 Abu 1600 Show 1300 Zint 600 </code></pre> <p>Using Panda, How to group by hotel and calculate the <strong>min, median and max</strong> of the earning on each hotel. And at the end print the aggregates values Hotel name &quot;Abu&quot;.</p> <p>Output:</p> <pre><code>[500.0, 650.0, 1600.0] </code></pre>
[ { "answer_id": 74675592, "author": "yanai edri", "author_id": 5841996, "author_profile": "https://Stackoverflow.com/users/5841996", "pm_score": 3, "selected": true, "text": "function solution(number) {\n // Base case: return 0 if the number is negative\n if (number < 0) {\n return 0;\n }\n\n // Recursive case: if the number is a multiple of 3 or 5, add it to the sum of\n // the multiples of 3 or 5 below it, otherwise just return the sum of the\n // multiples of 3 or 5 below it\n return (number % 3 === 0 || number % 5 === 0)\n ? number + solution(number - 1)\n : solution(number - 1);\n}\n" }, { "answer_id": 74675629, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 0, "selected": false, "text": "res res function solution(n) {\n let res = 0;\n\n function _solution(n) {\n if(n <= 0) {\n return 0;\n }\n\n if(n % 3 != 0 && n % 5 != 0) {\n return _solution(n - 1);\n }\n\n res += n;\n _solution(n - 1);\n return res;\n }\n\n return _solution(n - 1);\n}\n res" }, { "answer_id": 74675788, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "const input = 10\n\nfunction sum35(num){\n num = num - 1\n const lastThree = num - num%3\n const threeQuantity = lastThree/3\n \n const lastFive = num - num%5\n const fiveQuantity = lastFive/5\n \n return getSum(threeQuantity,3,lastThree) + getSum(fiveQuantity, 5, lastFive)\n \n function getSum(n, first, last) {\n return (n/2)*(first + last)\n }\n}\n\nconsole.log(sum35(10))" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538008/" ]
74,675,595
<p>This is the code I came up with so far. The goal is to generate a table 10x10 just like in the image <a href="https://i.stack.imgur.com/7yQ4s.jpg" rel="nofollow noreferrer">what i need</a></p> <p>The problem that I can't seem to understand is why it doesn't generate zeros and the last number 27 and just throws everything together.</p> <pre class="lang-java prettyprint-override"><code>public class Main { public static void main(String[] args) { int values[][] = new int[10][10]; int n = 1; for (int i=0; i&lt;=9; i++) { for (int j=9-i; j&gt;=7-i; j--){ if (j &gt;=0){ values[i][j] = n++; } System.out.printf(values[i][j] + &quot; &quot;); } System.out.println(); } } } </code></pre> <p>I would appreciate any suggestions, thanks!</p> <p>What is see/get -- &gt; <a href="https://i.stack.imgur.com/WxvrK.jpg" rel="nofollow noreferrer">what i see/ error</a></p>
[ { "answer_id": 74675705, "author": "shaham", "author_id": 15030723, "author_profile": "https://Stackoverflow.com/users/15030723", "pm_score": 0, "selected": false, "text": " values[i][j] = n++;\n\n System.out.printf(values[i][j] + \" \");\n \n" }, { "answer_id": 74675758, "author": "Mussemou", "author_id": 2585314, "author_profile": "https://Stackoverflow.com/users/2585314", "pm_score": -1, "selected": true, "text": "// don't forget to import java.util\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n int values[][] = new int [10][10];\n // here you fill the array with zeros\n for (int[] row : values) {\n for (int col : row) {\n row[col] = 0;\n }\n }\n \n // here is your algorithm\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=9-i; j>=7-i; j--){\n if (j >=0){\n values[i][j] = n++;\n }\n }\n }\n \n // here you print out the array\n for (int[] row : values) {\n System.out.println(Arrays.toString(row));\n }\n }\n \n}\n" }, { "answer_id": 74675784, "author": "Mihir B", "author_id": 6462302, "author_profile": "https://Stackoverflow.com/users/6462302", "pm_score": 0, "selected": false, "text": "if (j >=0){\n values[i][j] = n++;\n}\nSystem.out.println(values[i][j] + \" \"); // In this line after 26th loop you are getting error.\n if (j >=0){\n values[i][j] = n++;\n System.out.println(values[i][j] + \" \"); // Take this Print statement inside your if loop\n}\n" }, { "answer_id": 74675817, "author": "René Winkler", "author_id": 4461537, "author_profile": "https://Stackoverflow.com/users/4461537", "pm_score": -1, "selected": false, "text": "public class Main {\n\npublic static void main(String[] args) {\n int values[][] = new int [10][10];\n \n // Use a nested loop to iterate over all of the elements in the values array\n // and set each element to the corresponding value.\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++){\n // Check if the current element is part of the triangle\n if (i + j >= 9 && i + j <= 11) {\n values[i][j] = n++;\n }\n }\n }\n \n // Print the values array\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++) {\n System.out.printf(values[i][j] + \" \");\n }\n System.out.println();\n }\n}\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20616194/" ]
74,675,632
<p>I have the following code</p> <pre class="lang-py prettyprint-override"><code>(Pdb) set(range(2, 2)).issubset(set(range(10, 95))) True </code></pre> <p>and I don't understand why it's returning <code>True</code>. <code>issubset</code> is supposed to check if a set contains all the items of another set, but <code>2</code> can't be contained in a range from <code>10</code> to <code>95</code>.</p> <p>Am I misunderstanding Python's doc? Or is that a bug?</p>
[ { "answer_id": 74675705, "author": "shaham", "author_id": 15030723, "author_profile": "https://Stackoverflow.com/users/15030723", "pm_score": 0, "selected": false, "text": " values[i][j] = n++;\n\n System.out.printf(values[i][j] + \" \");\n \n" }, { "answer_id": 74675758, "author": "Mussemou", "author_id": 2585314, "author_profile": "https://Stackoverflow.com/users/2585314", "pm_score": -1, "selected": true, "text": "// don't forget to import java.util\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n int values[][] = new int [10][10];\n // here you fill the array with zeros\n for (int[] row : values) {\n for (int col : row) {\n row[col] = 0;\n }\n }\n \n // here is your algorithm\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=9-i; j>=7-i; j--){\n if (j >=0){\n values[i][j] = n++;\n }\n }\n }\n \n // here you print out the array\n for (int[] row : values) {\n System.out.println(Arrays.toString(row));\n }\n }\n \n}\n" }, { "answer_id": 74675784, "author": "Mihir B", "author_id": 6462302, "author_profile": "https://Stackoverflow.com/users/6462302", "pm_score": 0, "selected": false, "text": "if (j >=0){\n values[i][j] = n++;\n}\nSystem.out.println(values[i][j] + \" \"); // In this line after 26th loop you are getting error.\n if (j >=0){\n values[i][j] = n++;\n System.out.println(values[i][j] + \" \"); // Take this Print statement inside your if loop\n}\n" }, { "answer_id": 74675817, "author": "René Winkler", "author_id": 4461537, "author_profile": "https://Stackoverflow.com/users/4461537", "pm_score": -1, "selected": false, "text": "public class Main {\n\npublic static void main(String[] args) {\n int values[][] = new int [10][10];\n \n // Use a nested loop to iterate over all of the elements in the values array\n // and set each element to the corresponding value.\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++){\n // Check if the current element is part of the triangle\n if (i + j >= 9 && i + j <= 11) {\n values[i][j] = n++;\n }\n }\n }\n \n // Print the values array\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++) {\n System.out.printf(values[i][j] + \" \");\n }\n System.out.println();\n }\n}\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940158/" ]
74,675,639
<p>I am trying to set the <code>defaultValue</code> for on the <code>&lt;Select /&gt;</code> component from react-select package.</p> <p>However, when I do set the default value, using a react hook (useState), it does not render the default values.</p> <p>If I was to hard code the array, it renders he default values fine.</p> <p><strong>What I have so far</strong></p> <p><a href="https://codesandbox.io/s/codesandboxer-example-forked-2e3unk?file=/example.tsx:0-608" rel="nofollow noreferrer">https://codesandbox.io/s/codesandboxer-example-forked-2e3unk?file=/example.tsx:0-608</a></p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import Select from &quot;react-select&quot;; export default function AnimatedMulti() { const [values, setValues] = useState([]); const [defaultValues, setDefaultValues] = useState([]); useEffect(() =&gt; { const data = [ { value: 1, label: &quot;Label 1&quot; }, { value: 2, label: &quot;Label 2&quot; }, { value: 3, label: &quot;Label 3&quot; } ]; setValues(data); setDefaultValues([data[0], data[1]]); }, []); return ( &lt;Select closeMenuOnSelect={false} defaultValue={defaultValues} isMulti options={values} /&gt; ); } </code></pre> <p><strong>Output</strong></p> <p><a href="https://i.stack.imgur.com/bMbmv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bMbmv.png" alt="enter image description here" /></a></p> <p><strong>Expectation</strong></p> <p>I am expecting the select component to render <strong>two</strong> default values, however nothing has been rendered.</p> <p><strong>Question</strong></p> <p>How can I load the default values using react hook <code>useState</code>?</p>
[ { "answer_id": 74675870, "author": "Swaraj Gandhi", "author_id": 2125838, "author_profile": "https://Stackoverflow.com/users/2125838", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [selectedValues, setSelectedValues] = useState([]);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setSelectedValues([data[0]]);\n }, []);\n\n const onOptionChange = (options) => {\n // Selected options...\n console.log(\"options...\", options);\n setSelectedValues(options);\n };\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={selectedValues}\n isMulti\n options={values}\n onChange={onOptionChange}\n />\n );\n}\n" }, { "answer_id": 74675953, "author": "v1shva", "author_id": 4168998, "author_profile": "https://Stackoverflow.com/users/4168998", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [defaultValues, setDefaultValues] = useState(null);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setDefaultValues([data[0], data[1]]);\n }, []);\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={defaultValues}\n isMulti\n options={values}\n />\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12129150/" ]
74,675,664
<p>I need to check if 24 hours have passed between two dates. If 24 hours have passed, I will update the data in my room database, if not, I will not. How can I do that. I thought about keeping a date with shared preferences and comparing that date with the current date, but I don't know how to do that.</p>
[ { "answer_id": 74675870, "author": "Swaraj Gandhi", "author_id": 2125838, "author_profile": "https://Stackoverflow.com/users/2125838", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [selectedValues, setSelectedValues] = useState([]);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setSelectedValues([data[0]]);\n }, []);\n\n const onOptionChange = (options) => {\n // Selected options...\n console.log(\"options...\", options);\n setSelectedValues(options);\n };\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={selectedValues}\n isMulti\n options={values}\n onChange={onOptionChange}\n />\n );\n}\n" }, { "answer_id": 74675953, "author": "v1shva", "author_id": 4168998, "author_profile": "https://Stackoverflow.com/users/4168998", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [defaultValues, setDefaultValues] = useState(null);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setDefaultValues([data[0], data[1]]);\n }, []);\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={defaultValues}\n isMulti\n options={values}\n />\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18002913/" ]
74,675,698
<p>I have 2 scripts one on player :</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPositionCorrection : MonoBehaviour { Transform _playerTransform; public float _xAxys; public float _newXAxys; public GameObject _changerPlayerPosition; private void Start() { _playerTransform = GetComponent&lt;Transform&gt;(); } private void OnTriggerEnter(Collider other) { if (other.tag == &quot;ChangePlayerPosition&quot;) { float _newXAxys = this.GetComponent&lt;ChangePositionOn&gt;()._newPostion; } } private void LateUpdate() { if (transform.position.z != 0) { transform.position = new Vector3(_xAxys, _playerTransform.position.y, _playerTransform.position.z); } } </code></pre> <p>and second on object :</p> <pre><code>public class ChangePositionOn : MonoBehaviour { public float _newPostion = 5; void Start() { } // Update is called once per frame void Update() { } } </code></pre> <p>I using Unity 2022.1.19f1 and C#.</p> <p>Thank you for your healp, Michal</p> <p>I would like to have several object in my game and when player will collide with them change location on x axis.</p> <p>Unfortunately every time i have this error message:</p> <pre><code>NullReferenceException: Object reference not set to an instance of an object PlayerPositionCorrection.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/PlayerPositionCorrection.cs:23) </code></pre>
[ { "answer_id": 74675870, "author": "Swaraj Gandhi", "author_id": 2125838, "author_profile": "https://Stackoverflow.com/users/2125838", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [selectedValues, setSelectedValues] = useState([]);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setSelectedValues([data[0]]);\n }, []);\n\n const onOptionChange = (options) => {\n // Selected options...\n console.log(\"options...\", options);\n setSelectedValues(options);\n };\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={selectedValues}\n isMulti\n options={values}\n onChange={onOptionChange}\n />\n );\n}\n" }, { "answer_id": 74675953, "author": "v1shva", "author_id": 4168998, "author_profile": "https://Stackoverflow.com/users/4168998", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [defaultValues, setDefaultValues] = useState(null);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setDefaultValues([data[0], data[1]]);\n }, []);\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={defaultValues}\n isMulti\n options={values}\n />\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14730288/" ]
74,675,713
<p>Below is the problem I found on the internet.</p> <pre><code>int main() { int a[4] = { 10, 21, 32, 43}; int *p = a + 3; ++*--p; ++*p--; p[2] += p[1]; for (int i = 0; i &lt; 4; ++i) printf(&quot;%d - %d\t&quot;, a[i]); return 0; } </code></pre> <p>//What will be the output?</p> <p>answer : 10 21 34 77</p> <p>I understood a lot of things, but the only thing I'm stuck on:</p> <p>What is the difference between <code>(++*--p)</code> and <code>(++*p--)</code> ?</p> <p>Shouldn't these two give the same result? Because <code>(*p--)</code> and <code>(*--p)</code> give the same result in the compiler. The compiler I use is Code::Blocks</p>
[ { "answer_id": 74675870, "author": "Swaraj Gandhi", "author_id": 2125838, "author_profile": "https://Stackoverflow.com/users/2125838", "pm_score": 2, "selected": true, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [selectedValues, setSelectedValues] = useState([]);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setSelectedValues([data[0]]);\n }, []);\n\n const onOptionChange = (options) => {\n // Selected options...\n console.log(\"options...\", options);\n setSelectedValues(options);\n };\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={selectedValues}\n isMulti\n options={values}\n onChange={onOptionChange}\n />\n );\n}\n" }, { "answer_id": 74675953, "author": "v1shva", "author_id": 4168998, "author_profile": "https://Stackoverflow.com/users/4168998", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [defaultValues, setDefaultValues] = useState(null);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setDefaultValues([data[0], data[1]]);\n }, []);\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={defaultValues}\n isMulti\n options={values}\n />\n );\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74675713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13341238/" ]