qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,500,433
<p>How can I expand this to count all input boxes in a form that is <code>type=&quot;number&quot;</code> but is currently disabled?</p> <pre><code>let countIN = document.getElementsByTagName('input').length; </code></pre> <p>I can count all the input boxes (which included checkboxes) but I want to only count the specific disabled boxes only.</p>
[ { "answer_id": 74500465, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 3, "selected": true, "text": "querySelectorAll [type=\"number\"]:disabled input input[type=\"number\"]:disabled const selector = '[type=\"number\"]:disabled';\n\nconst disabled = document.querySelectorAll(selector);\n\nconsole.log(`Disabled number inputs: ${disabled.length}`); [type=\"number\"]:disabled { background-color: salmon; } <input type=\"number\" value=\"1\">\n<input type=\"number\" value=\"2\" disabled>\n<input type=\"number\" value=\"3\">\n<input type=\"number\" value=\"4\" disabled>\n<input type=\"number\" value=\"5\">" }, { "answer_id": 74500490, "author": "Paul Davis", "author_id": 13062685, "author_profile": "https://Stackoverflow.com/users/13062685", "pm_score": 1, "selected": false, "text": " let countIN = document.querySelectorAll(\"input:disabled\").length;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13062685/" ]
74,500,458
<p>I am currently working on a huge csv file with pandas, and I need to find and print similarity between the selected row and every other row. For example if the string is &quot;Card&quot; and the second string is &quot;Credit Card Debit Card&quot; it should return 2 or if the first string is &quot;Credit Card&quot; and the second string is &quot;Credit Card Debit Card&quot; it should return 3 because 3 of the words match with the first string. I tried solving this using sets but because of sets being unique and not containing duplicates in the first example instead of 2 it returns 1. Because in a set &quot;Credit Card Debit Card&quot; is {&quot;Credit&quot;, &quot;Card&quot;, &quot;Debit&quot;}. Is there anyway that I can calculate this? The formula of similarity is ((numberOfSameWords)/whichStringisLonger)*100 as explained in this photo:</p> <p><a href="https://i.stack.imgur.com/QHmJG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QHmJG.png" alt="" /></a></p> <p>I tried so many things like Jaccard Similarity but they all work with sets and return wrong answers. Thanks for any help. The code I tried running:</p> <pre><code>def test(row1, row2): return str(round(len(np.intersect1d(row1.split(), row2.split())) / max(len(row1.split()), len(row2.split()))*100, 2)) data = int(input(&quot;Which index should be tested:&quot;)) for j in range(0,10): print(test(dff['Product'].iloc[data], dff['Product'].iloc[j])) </code></pre> <p>and my dataframe currently looks like this:</p> <p><a href="https://i.stack.imgur.com/l4vXs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l4vXs.png" alt="" /></a></p> <p><code>print(df.sample(10).to_dict(&quot;list&quot;))</code> returned me:</p> <pre><code>{'Product': ['Bank account or service', 'Credit card', 'Credit reporting', 'Credit reporting credit repair services or other personal consumer reports', 'Credit reporting', 'Mortgage', 'Debt collection', 'Mortgage', 'Mortgage', 'Credit reporting'], 'Issue': ['Deposits and withdrawals', 'Billing disputes', 'Incorrect information on credit report', &quot;Problem with a credit reporting company's investigation into an existing problem&quot;, 'Incorrect information on credit report', 'Applying for a mortgage or refinancing an existing mortgage', 'Disclosure verification of debt', 'Loan servicing payments escrow account', 'Loan servicing payments escrow account', 'Incorrect information on credit report'], 'Company': ['CITIBANK NA', 'FIRST NATIONAL BANK OF OMAHA', 'EQUIFAX INC', 'Experian Information Solutions Inc', 'Experian Information Solutions Inc', 'BANK OF AMERICA NATIONAL ASSOCIATION', 'AllianceOne Recievables Management', 'SELECT PORTFOLIO SERVICING INC', 'OCWEN LOAN SERVICING LLC', 'Experian Information Solutions Inc'], 'State': ['CA', 'WA', 'FL', 'UT', 'MI', 'CA', 'WA', 'IL', 'TX', 'CA'], 'ZIP_code': ['92606', '98272', '329XX', '84321', '486XX', '94537', '984XX', '60473', '76247', '91401'], 'Complaint_ID': [90452, 2334443, 1347696, 2914771, 1788024, 2871939, 1236424, 1619712, 2421373, 1803691]} </code></pre>
[ { "answer_id": 74500465, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 3, "selected": true, "text": "querySelectorAll [type=\"number\"]:disabled input input[type=\"number\"]:disabled const selector = '[type=\"number\"]:disabled';\n\nconst disabled = document.querySelectorAll(selector);\n\nconsole.log(`Disabled number inputs: ${disabled.length}`); [type=\"number\"]:disabled { background-color: salmon; } <input type=\"number\" value=\"1\">\n<input type=\"number\" value=\"2\" disabled>\n<input type=\"number\" value=\"3\">\n<input type=\"number\" value=\"4\" disabled>\n<input type=\"number\" value=\"5\">" }, { "answer_id": 74500490, "author": "Paul Davis", "author_id": 13062685, "author_profile": "https://Stackoverflow.com/users/13062685", "pm_score": 1, "selected": false, "text": " let countIN = document.querySelectorAll(\"input:disabled\").length;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18693210/" ]
74,500,463
<p>I am using PostgreSQL 11.2. I have replication slots setup. I am able to commit to a table and see it on the standby. I have few more standbys. How can I see from the master what other standbys I have?</p>
[ { "answer_id": 74507709, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 2, "selected": true, "text": "pg_stat_replication client_addr" }, { "answer_id": 74507854, "author": "Ronak Jain", "author_id": 2718939, "author_profile": "https://Stackoverflow.com/users/2718939", "pm_score": 0, "selected": false, "text": "SELECT * FROM pg_stat_replication;\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3589054/" ]
74,500,468
<blockquote> <p>Using the Switch Statement, create a program that will ask the user to input number from 1 - 12, then each number corresponds a month in the calendar. If the number is not on the range display &quot;The value is not on the calendar.&quot; Then it will ask the user if they want to try again a number or it will close the program. If the user input Y for Yes then it will execute again the program. If the user chose N for No it will automatically terminate the program and it will display System is Terminated.</p> </blockquote> <pre><code>import java.util.Scanner; public class calendar { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print(&quot;Enter month's number: &quot;); int monthNumber; monthNumber = in.nextInt(); switch (monthNumber) { case 1: System.out.println(&quot;January&quot;); break; case 2: System.out.println(&quot;February&quot;); break; case 3: System.out.println(&quot;March&quot;); break; case 4: System.out.println(&quot;April&quot;); break; case 5: System.out.println(&quot;May&quot;); break; case 6: System.out.println(&quot;June&quot;); break; case 7: System.out.println(&quot;July&quot;); break; case 8: System.out.println(&quot;August&quot;); break; case 9: System.out.println(&quot;September&quot;); break; case 10: System.out.println(&quot;October&quot;); break; case 11: System.out.println(&quot;November&quot;); break; case 12: System.out.println(&quot;December&quot;); break; default: System.out.println(&quot;Invalid month.&quot;); break; } } } </code></pre>
[ { "answer_id": 74500641, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 1, "selected": false, "text": "System.out.print(\"Enter month's number: \");\ntry {\n int monthNumber = Integer.parseInt(in.nextLine()); \n if (monthNumber < 1 || monthNumber > 12) {\n throw new RuntimeException(\"out of bounds\");\n } \n System.out.println(monthName(monthNumber)); // extract your original logic to a method\n} catch (Exception e) {\n System.out.println(\"The value is not on the calendar.\");\n} \n String again = \"Y\";\nwhile (\"Y\".equals(again)) {\n System.out.print(\"Enter month's number: \");\n try {... \n} \n System.out.println(\"Try again? (Y/N)\"); \nagain = in.nextLine().strip();\n" }, { "answer_id": 74501395, "author": "kermitdafrog", "author_id": 20548517, "author_profile": "https://Stackoverflow.com/users/20548517", "pm_score": 0, "selected": false, "text": "boolean ch; \n for (ch = true; ch != false; ) {\n//insert code here\n}\n for (ch = true; ch != false; ) {\n System.out.println(\"Enter a number\");\n d = sc.nextInt();\n switch (d) \n {\n case 1: \n System.out.println(\"January\");\n break;\n case 2: \n System.out.println(\"February\");\n break;\n case 3: \n System.out.println(\"March\");\n break;\n case 4: \n System.out.println(\"April\");\n break;\n case 5: \n System.out.println(\"May\");\n break;\n case 6: \n System.out.println(\"June\");\n break;\n case 7: \n System.out.println(\"July\");\n break;\n case 8: \n System.out.println(\"August\");\n break;\n case 9: \n System.out.println(\"September\");\n break;\n case 10: \n System.out.println(\"October\");\n break;\n case 11: \n System.out.println(\"November\");\n break;\n case 12: \n System.out.println(\"December\");\n break;\n default: \n System.out.println(\"Invalid Number\");\n }\n System.out.println(\"Again?\");\n yn = sc.next().charAt(0);\n if (yn == 'Y' || yn == 'y') {\n ch = true;\n } else {\n ch = false;\n }\n \n }\n import java.util.*;\npublic class months {\n public static void main(String[] args)\n {\n Scanner sc = new Scanner(System.in);\n int d;\n boolean ch; \n char yn;\n for (ch = true; ch != false; ) {\n System.out.println(\"Enter a number\");\n d = sc.nextInt();\n switch (d) \n {\n case 1: \n System.out.println(\"January\");\n break;\n case 2: \n System.out.println(\"February\");\n break;\n case 3: \n System.out.println(\"March\");\n break;\n case 4: \n System.out.println(\"April\");\n break;\n case 5: \n System.out.println(\"May\");\n break;\n case 6: \n System.out.println(\"June\");\n break;\n case 7: \n System.out.println(\"July\");\n break;\n case 8: \n System.out.println(\"August\");\n break;\n case 9: \n System.out.println(\"September\");\n break;\n case 10: \n System.out.println(\"October\");\n break;\n case 11: \n System.out.println(\"November\");\n break;\n case 12: \n System.out.println(\"December\");\n break;\n default: \n System.out.println(\"Invalid Number\");\n }\n System.out.println(\"Again?\");\n yn = sc.next().charAt(0);\n if (yn == 'Y' || yn == 'y') {\n ch = true;\n } else {\n ch = false;\n }\n \n }\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20547923/" ]
74,500,484
<p>I have an array</p> <pre><code>[ a1, b1, c1, d1, a2, b2, c2, d2 ] </code></pre> <p>and I would like to convert it to:</p> <pre><code>{ 0: { name: a1, tel: b1, mail: c1, address: d1 }, 1: { name: a2, tel: b2, mail: c2, address: d2 } } </code></pre> <p>Basically group them every 4 array steps. What is the best way to do this?</p> <p>Appreciate any help. Thank you</p>
[ { "answer_id": 74500545, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\n\nconst f = ([name, tel, mail, address, ...rest]) =>\n [{name, tel, mail, address}, ...rest.length?f(rest):[]];\n\nconsole.log(Object.fromEntries(f(d).map((e,i)=>[i,e]))); const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\nconst keys = ['name','tel','mail','address'];\n\nconsole.log(d.reduce((a,c,i,r)=>(i%keys.length?0:a[i/keys.length|0]\n = Object.fromEntries(keys.map((k,j)=>[k,r[i+j]])),a),{}));" }, { "answer_id": 74500557, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "let data = [\n`a1`,\n`b1`,\n`c1`,\n`d1`,\n`a2`,\n`b2`,\n`c2`,\n`d2`\n]\n\nlet keys = ['name','tel','mail','address']\nlet result = {}\nfor(let i=0;i<data.length;i=i+keys.length){\n result[i/4] = {}\n for(key of keys){\n result[i/4][key] = data[i]\n }\n}\nconsole.log(result)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571949/" ]
74,500,500
<p>I am new to AWS and trying to deploy a GraphQL API written in NodeJS as an AWS Lambda using Serverless. I have followed several tutorials that are close to what I am doing but cannot get the handler to work. The closest tutorial to what I am doing was using JavaScript, where I am using TypeScript. I followed closely but using TypeScript. I am getting errors that it cannot find the handler module (Error: Cannot find module 'lambda').</p> <p>My handler file is named lambda.ts looks like this `</p> <pre><code>import {app} from './app'; import {serverless} from 'serverless-http'; export const handler = serverless(app); </code></pre> <p>`</p> <p>My serverless.yml looks like this `</p> <pre><code>service: graphql-api frameworkVersion: '3' provider: name: aws runtime: nodejs12.x region: us-east-1 functions: serverlessApi: handler: lambda.handler </code></pre> <p><code>app.ts</code></p> <pre><code>import express from 'express'; import cors from 'cors'; import { graphqlHTTP } from 'express-graphql'; import { schema, resolvers } from './api-schema/'; import { loginMiddleware } from './login-middleware'; const app = express(); app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(loginMiddleware); app.use( '/graphql', graphqlHTTP({ schema: schema, graphiql: true, rootValue: resolvers, }) ); export default app; </code></pre> <p>` The lambda.js, app.ts, and serverless.yml files are all in the same root directory.</p> <p>I have tried to convert the code to JavaScript and get errors that it cannot find the 'app' module. (Cannot find module './app')</p> <p>lambda.js and looks like this `</p> <pre><code>const app = require('./app'); const serverless = require('serverless-http'); module.exports.handler = serverless(app); </code></pre> <p>`</p> <p>I have also tried to export 'app' as default or named getting the same result. I am out of ideas. Any help is much appreciated.</p>
[ { "answer_id": 74500545, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\n\nconst f = ([name, tel, mail, address, ...rest]) =>\n [{name, tel, mail, address}, ...rest.length?f(rest):[]];\n\nconsole.log(Object.fromEntries(f(d).map((e,i)=>[i,e]))); const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\nconst keys = ['name','tel','mail','address'];\n\nconsole.log(d.reduce((a,c,i,r)=>(i%keys.length?0:a[i/keys.length|0]\n = Object.fromEntries(keys.map((k,j)=>[k,r[i+j]])),a),{}));" }, { "answer_id": 74500557, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "let data = [\n`a1`,\n`b1`,\n`c1`,\n`d1`,\n`a2`,\n`b2`,\n`c2`,\n`d2`\n]\n\nlet keys = ['name','tel','mail','address']\nlet result = {}\nfor(let i=0;i<data.length;i=i+keys.length){\n result[i/4] = {}\n for(key of keys){\n result[i/4][key] = data[i]\n }\n}\nconsole.log(result)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3349255/" ]
74,500,511
<p>I just want to know what is going on in this program</p> <pre><code> sum = 0 #setting sum to 0 for i in range(len(m)): for j in range(len(m[i])): if i &lt;= j: sum = sum + m[i][j] return sum print((sum_above_diagonal([[6, 2, 0, 6, 1], [6, 8, 2, 5, 8], [0, 6, 3, 2, 3]]))) </code></pre> <p>I understand the first part, but I am confused on the 'for i in range (len())' stuff.</p>
[ { "answer_id": 74500545, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\n\nconst f = ([name, tel, mail, address, ...rest]) =>\n [{name, tel, mail, address}, ...rest.length?f(rest):[]];\n\nconsole.log(Object.fromEntries(f(d).map((e,i)=>[i,e]))); const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\nconst keys = ['name','tel','mail','address'];\n\nconsole.log(d.reduce((a,c,i,r)=>(i%keys.length?0:a[i/keys.length|0]\n = Object.fromEntries(keys.map((k,j)=>[k,r[i+j]])),a),{}));" }, { "answer_id": 74500557, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "let data = [\n`a1`,\n`b1`,\n`c1`,\n`d1`,\n`a2`,\n`b2`,\n`c2`,\n`d2`\n]\n\nlet keys = ['name','tel','mail','address']\nlet result = {}\nfor(let i=0;i<data.length;i=i+keys.length){\n result[i/4] = {}\n for(key of keys){\n result[i/4][key] = data[i]\n }\n}\nconsole.log(result)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20311710/" ]
74,500,548
<p>There is an array for each id key that is not needed. That is kind of a group break.</p> <pre><code>const header = [ [ { id: &quot;1&quot;, text: &quot;A&quot;, }, ], [ { id: &quot;2&quot;, text: &quot;B&quot;, array:[1,2,3], }, { id: &quot;2&quot;, text: &quot;B1&quot;, }, ], [ { id: &quot;3&quot;, text: &quot;A&quot;, }, ], ]; </code></pre> <p>The result should be that below. The array between the same id should disapear. Only one array that contains the data as objects should remain.</p> <pre><code>const header = [ { id: &quot;1&quot;, text: &quot;A&quot;, }, { id: &quot;2&quot;, text: &quot;B&quot;, array:[1,2,3], }, { id: &quot;2&quot;, text: &quot;B1&quot;, }, { id: &quot;3&quot;, text: &quot;A&quot;, }, ]; </code></pre>
[ { "answer_id": 74500545, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\n\nconst f = ([name, tel, mail, address, ...rest]) =>\n [{name, tel, mail, address}, ...rest.length?f(rest):[]];\n\nconsole.log(Object.fromEntries(f(d).map((e,i)=>[i,e]))); const d = ['a1','b1','c1','d1','a2','b2','c2','d2']\nconst keys = ['name','tel','mail','address'];\n\nconsole.log(d.reduce((a,c,i,r)=>(i%keys.length?0:a[i/keys.length|0]\n = Object.fromEntries(keys.map((k,j)=>[k,r[i+j]])),a),{}));" }, { "answer_id": 74500557, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 2, "selected": false, "text": "let data = [\n`a1`,\n`b1`,\n`c1`,\n`d1`,\n`a2`,\n`b2`,\n`c2`,\n`d2`\n]\n\nlet keys = ['name','tel','mail','address']\nlet result = {}\nfor(let i=0;i<data.length;i=i+keys.length){\n result[i/4] = {}\n for(key of keys){\n result[i/4][key] = data[i]\n }\n}\nconsole.log(result)" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20547743/" ]
74,500,592
<p>I'm trying to come up with a function that gives me a &quot;factorial&quot; of a number but in a different way. For example:</p> <p><code>15! = 15*14/13+12-11*10/9... </code> and so on.</p> <p>I tried doing this by first creating an array and, then, a loop to get to the result. But it doesn't work as expected. The result expected from the code below is 13.</p> <pre><code>function createList(n) { let input = n let list = [input] for(i = input-1; i &gt;= 1; i--) { list.push(i) } return list } function factorialDiff() { let elements = createList(12) var res = elements.shift() while(elements.length &gt;= 1) { if(elements.length == 0) { return res } res *= elements.shift() if(elements.length == 0) { return res } res /= elements.shift() if(elements.length == 0) { return res } res += elements.shift() if(elements.length == 0) { return res } res -= elements.shift() if(elementos.length == 0) { return res } } return res } console.log(factorialDiff()) `` ` </code></pre>
[ { "answer_id": 74501085, "author": "André", "author_id": 13970434, "author_profile": "https://Stackoverflow.com/users/13970434", "pm_score": 2, "selected": false, "text": "console.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1); console.log(12*11/10+9-8*7/6+5-4*3/2+1); // returns 12.86\n\nconsole.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1); // returns 27.35 just like your function does\n function factorialDiff() {\n const elements = createList(12);\n let res1 = elements.shift();\n let res2 = elements.shift();\n let res3 = elements.shift();\n let res = (res1*res2/res3)\n while(elements.length >= 1) {\n res += elements.shift();\n if(elements.length == 0) {\n return res;\n }\n res1 = elements.shift();\n if(elements.length == 0) {\n return res*res1;\n }\n res2 = elements.shift();\n if(elements.length == 0) {\n return res*res1/res2;\n }\n res3 = elements.shift();\n res -= (res1*res2/res3);\n if(elements.length == 0) {\n return res;\n } \n }\n return res;\n}\n" }, { "answer_id": 74501099, "author": "Faezeh Keshmiri", "author_id": 14361493, "author_profile": "https://Stackoverflow.com/users/14361493", "pm_score": 0, "selected": false, "text": "function myFactorial(num) {\n var result = num;\n operatorNum = 0;\n for(i = num - 1; i >= 1; i--){\n if(operatorNum % 4 == 0){ // \"*\"\n result = result * i;\n }else if (operatorNum % 4 == 1){ // \"/\"\n result = result / i;\n }else if (operatorNum % 4 == 2){ // \"+\"\n result = result + i;\n }else{ // \"-\"\n result = result - i;\n }\n operatorNum++;\n }\n return result;\n }\n console.log(myFactorial(4)); // logs 7\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544020/" ]
74,500,624
<p>I want to build a self updating filter with checkboxes.</p> <p>My Data:</p> <pre class="lang-js prettyprint-override"><code> const Shooting= [ { name: &quot;John &amp; Johna &quot;, tag: [&quot;wedding&quot;, &quot;couple&quot;], img: [ src1 , src2, ...] //irrelevant }, { name: &quot;Mario &amp; Marie&quot;, tag: [&quot;couple&quot;, &quot;NSFW&quot;], img: [ src1 , src2, ...] //irrelevant }, ]; export default Shooting; </code></pre> <p>how my output should look like that:</p> <pre><code>Filter: []wedding []couple []NSFW // [] are checkboxes, &quot;couple&quot; is a duplicate in the array </code></pre> <p>My code idea:</p> <ol> <li>Get all tags into a new array</li> <li>Build function to remove duplicates from new array</li> <li>list the filtered array with map-function -&gt; Obj.map((tag))=&gt;{...}</li> </ol> <p>My question:</p> <p>How can I get all tags in a new list?</p>
[ { "answer_id": 74501085, "author": "André", "author_id": 13970434, "author_profile": "https://Stackoverflow.com/users/13970434", "pm_score": 2, "selected": false, "text": "console.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1); console.log(12*11/10+9-8*7/6+5-4*3/2+1); // returns 12.86\n\nconsole.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1); // returns 27.35 just like your function does\n function factorialDiff() {\n const elements = createList(12);\n let res1 = elements.shift();\n let res2 = elements.shift();\n let res3 = elements.shift();\n let res = (res1*res2/res3)\n while(elements.length >= 1) {\n res += elements.shift();\n if(elements.length == 0) {\n return res;\n }\n res1 = elements.shift();\n if(elements.length == 0) {\n return res*res1;\n }\n res2 = elements.shift();\n if(elements.length == 0) {\n return res*res1/res2;\n }\n res3 = elements.shift();\n res -= (res1*res2/res3);\n if(elements.length == 0) {\n return res;\n } \n }\n return res;\n}\n" }, { "answer_id": 74501099, "author": "Faezeh Keshmiri", "author_id": 14361493, "author_profile": "https://Stackoverflow.com/users/14361493", "pm_score": 0, "selected": false, "text": "function myFactorial(num) {\n var result = num;\n operatorNum = 0;\n for(i = num - 1; i >= 1; i--){\n if(operatorNum % 4 == 0){ // \"*\"\n result = result * i;\n }else if (operatorNum % 4 == 1){ // \"/\"\n result = result / i;\n }else if (operatorNum % 4 == 2){ // \"+\"\n result = result + i;\n }else{ // \"-\"\n result = result - i;\n }\n operatorNum++;\n }\n return result;\n }\n console.log(myFactorial(4)); // logs 7\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749827/" ]
74,500,631
<p><img src="https://i.stack.imgur.com/Yofg3.png" alt="enter image description here" /></p> <p>I tried use this:</p> <pre><code>border: 1px solid #7BE34A; box-shadow: 0px 4px 25px rgba(123, 227, 74, 0.25); border: 1px solid #28780D; box-shadow: 0px 4px 25px rgba(40, 120, 13, 0.25); </code></pre> <p>from figma, but it doesn't work</p>
[ { "answer_id": 74500694, "author": "Abdullah Sami", "author_id": 14248251, "author_profile": "https://Stackoverflow.com/users/14248251", "pm_score": 2, "selected": false, "text": ".line {\n border-top : 1px solid #000;\n position : relative;\n width : 100px\n }\n.line:after {\n content : \"\";\n position : absolute;\n border-right : 1px solid #000;\n height : 10px;\n right : 0;\n bottom : 0;\n }\n.line:before {\n content : \"\";\n position : absolute;\n border-top : 1px solid #000;\n height : 10px;\n width : 100px;\n right : -100%;\n bottom : 110%;\n } <br>\n<div class=\"line\">\n</div>" }, { "answer_id": 74500800, "author": "Mehdi Dehghani", "author_id": 3367974, "author_profile": "https://Stackoverflow.com/users/3367974", "pm_score": 1, "selected": false, "text": ".container {\n background-color: #01383a;\n width: 600px;\n height: 140px;\n overflow: hidden;\n display: flex;\n align-items: center; \n}\n.line {\n height: 10px;\n width: 1px;\n background: #4fa445;\n position: relative;\n margin-left: 50%;\n box-shadow: 4px 4px 0 rgba(79, 164, 69, 0.5);\n}\n\n.line:before,\n.line:after {\n content: \"\";\n display: block;\n height: 1px;\n width: 304px;\n background: #4fa445;\n position: absolute;\n box-shadow: 4px 4px 0 rgba(79, 164, 69, 0.5);\n}\n\n.line:before {\n right: 0;\n bottom: 0;\n} <div class=\"container\"> \n <div class=\"line\"></div>\n</div>" }, { "answer_id": 74500993, "author": "Louys Patrice Bessette", "author_id": 2159528, "author_profile": "https://Stackoverflow.com/users/2159528", "pm_score": 2, "selected": false, "text": "body{\n background-color: #01383A;\n}\n.myHeader {\n width: 100%;\n display: grid;\n grid-template-columns: 30% 6px 1fr; /* Adjust horizontal dimentions here - particularly for the title */\n grid-template-rows: 2.5em 6px 10px 6px; /* Adjust vertical dimentions here */\n grid-auto-flow: column;\n}\n.title {\n grid-column: 1;\n grid-row: 1;\n text-align: right;\n padding-right: 10px;\n font-size: 2em;\n color: #ffffff;\n}\n.lines-part-a {\n grid-column: 1;\n grid-row: 2 / 4;\n border-bottom: 1px solid #358341;\n border-right: 1px solid #358341;\n}\n.lines-part-b {\n grid-column: 2 / 5;\n grid-row: 2 / 4;\n border-top: 1px solid #358341;\n}\n.lines-part-c {\n grid-column: 1 / 3;\n grid-row: 3 / 5;\n border-bottom: 1px solid #10512A;\n border-right: 1px solid #10512A;\n}\n.lines-part-d {\n grid-column: 3 / 5;\n grid-row: 3 / 5;\n border-top: 1px solid #10512A;\n} <div class=\"myHeader\">\n <div class=\"title\">Take order</div>\n <div class=\"lines-part-a\"></div>\n <div class=\"lines-part-b\"></div>\n <div class=\"lines-part-c\"></div>\n <div class=\"lines-part-d\"></div>\n</div> body{\n background-color: #01383A;\n}\n.myHeader {\n width: 100%;\n display: grid;\n grid-template-columns: 100px 20% 4px 1fr 100px;\n grid-template-rows: 2.5em 4px 10px 4px;\n grid-auto-flow: column;\n}\n.title {\n grid-column: 1 / 3;\n grid-row: 1;\n text-align: right;\n padding-right: 10px;\n font-size: 2em;\n color: #ffffff;\n}\n.lines-dashed-a {\n grid-column: 1;\n grid-row: 3 / 4;\n border-bottom: 1px dashed #358341;\n}\n.lines-part-a {\n grid-column: 2 / 3;\n grid-row: 3 / 4;\n border-bottom: 1px solid #358341;\n border-right: 1px solid #358341;\n border-radius: 0 0 4px 0;\n}\n.lines-part-b {\n grid-column: 3 / 5;\n grid-row: 2 / 3;\n border-top: 1px solid #358341;\n border-left: 1px solid #358341;\n border-radius: 6px 0 0 0;\n margin-left: -1px;\n}\n.lines-dashed-b {\n grid-column: 5;\n grid-row: 2 / 3;\n border-top: 1px dashed #358341;\n}\n.lines-dashed-c {\n grid-column: 1;\n grid-row: 4 / 5;\n border-bottom: 1px dashed #10512A;\n}\n.lines-part-c {\n grid-column: 2 / 4;\n grid-row: 4 / 5;\n border-bottom: 1px solid #10512A;\n border-right: 1px solid #10512A;\n border-radius: 0 0 6px 0;\n}\n.lines-part-d {\n grid-column: 4 / 5;\n grid-row: 3 / 4;\n border-top: 1px solid #10512A;\n border-left: 1px solid #10512A;\n border-radius: 4px 0 0 0;\n margin-left: -1px;\n}\n.lines-dashed-d {\n grid-column: 5;\n grid-row: 3 / 4;\n border-top: 1px dashed #10512A;\n} <div class=\"myHeader\">\n <div class=\"title\">Take order</div>\n <div class=\"lines-dashed-a\"></div>\n <div class=\"lines-part-a\"></div>\n <div class=\"lines-part-b\"></div>\n <div class=\"lines-dashed-b\"></div>\n <div class=\"lines-dashed-c\"></div>\n <div class=\"lines-part-c\"></div>\n <div class=\"lines-part-d\"></div>\n <div class=\"lines-dashed-d\"></div>\n</div>" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548061/" ]
74,500,654
<p>I have a tricky problem and I'm working on it for several hours but can't find a cause and solution of it. Hope someone help me.</p> <p>I have to demonstrate function being called inside another function( pls see the comment in seminar.cpp)</p> <p>Below are the files ( I have separated it into header and code files)</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; #include &quot;seminar.h&quot; int main() { Tom::Car::Car car; Nor::Driving drivingnow; std::vector&lt;uint8_t&gt; X = car.road(drivingnow); for(int i = 0 ; i &lt; X.size() ; i++){ std::cout&lt;&lt;unsigned(X[i])&lt;&lt;&quot; &quot;; } return 0; } </code></pre> <p><strong>seminar.h</strong></p> <pre><code>#pragma once #include &quot;dist.h&quot; #include &lt;vector&gt; #include &lt;bits/stdc++.h&gt; namespace Tom { namespace Car { class Car { public: std::vector&lt;uint8_t&gt; road(Nor::Driving &amp;driving); }; } // namespace Car } // namespace Tom </code></pre> <p><strong>seminar.cpp</strong></p> <pre><code>#include &quot;seminar.h&quot; #include &lt;algorithm&gt; #include &lt;functional&gt; namespace Tom { namespace Car { std::vector&lt;uint8_t&gt; drive(Nor::Range &amp;range) { std::vector&lt;uint8_t&gt; s; s.push_back(range.z); s.push_back(range.zz); return s; } template &lt;typename T, typename B, typename L&gt; std::vector&lt;uint8_t&gt; Content(T Sec, B Byte, L Func) { Nor::Range Rom; std::vector&lt;uint8_t&gt; z = Func(Rom); return z; } std::vector&lt;uint8_t&gt; Car::road(Nor::Driving &amp;driving) { std::function&lt;std::vector&lt;uint8_t&gt;(Nor::Range &amp;)&gt; Func = &amp;drive; return Content(driving, 1, Func); // passing drive function into content } } // namespace Car } // namespace Tom </code></pre> <p><strong>dist.h</strong></p> <pre><code>namespace Nor { class Driving{ public: int x = 1; }; class Range{ public: int z = 50; int zz = 100; }; } </code></pre> <p>The above code and file structure works correctly and give me the correct expected output ie <code>50 100</code> <strong>Live</strong> <a href="https://www.onlinegdb.com/elzbMBnYR#" rel="nofollow noreferrer">here</a></p> <hr /> <p>Now I want to do more separation ie I want the implementation of <code>drive</code> function to move in another file ie in <code>type.cpp</code></p> <p><strong>type.cpp</strong></p> <pre><code>#include &lt;algorithm&gt; #include &quot;seminar.h&quot; #include &lt;functional&gt; namespace Tom { namespace Car { std::vector&lt;uint8_t&gt; Car::drive(Nor::Range &amp;range) { std::vector&lt;uint8_t&gt; s; s.push_back(range.z); return s; } } // namespace Car } // namespace Tom </code></pre> <p><strong>seminar.h</strong></p> <pre><code>#pragma once #include &quot;dist.h&quot; #include &lt;vector&gt; #include &lt;bits/stdc++.h&gt; namespace Tom { namespace Car { class Car { public: std::vector&lt;uint8_t&gt; road(Nor::Driving &amp;driving); std::vector&lt;uint8_t&gt; drive(Nor::Range &amp;range); }; } // namespace Car } // namespace Tom </code></pre> <p><strong>seminar.cpp</strong></p> <pre><code>#include &quot;seminar.h&quot; #include &lt;algorithm&gt; #include &lt;functional&gt; namespace Tom { namespace Car { template &lt;typename T, typename B, typename L&gt; std::vector&lt;uint8_t&gt; Content(T Sec, B Byte, L Func) { Nor::Range Rom; std::vector&lt;uint8_t&gt; z = Func(Rom); return z; } std::vector&lt;uint8_t&gt; Car::road(Nor::Driving &amp;driving) { std::function&lt;std::vector&lt;uint8_t&gt;(Nor::Range &amp;)&gt; Func = &amp;drive; return Content(driving, 1, Func); } } // namespace Car } // namespace Tom </code></pre> <p><strong>Live</strong> <a href="https://www.onlinegdb.com/msLCsdyQd" rel="nofollow noreferrer">here</a> After doing this I am getting an below error:</p> <pre><code>seminar.cpp: In member function ‘std::vector&lt;unsigned char&gt; Tom::Car::Car::road(Nor::Driving&amp;)’: seminar.cpp:22:71: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&amp;Tom::Car::Car::drive’ [-fpermissive] 22 | std::function&lt;std::vector&lt;uint8_t&gt;(Nor::Range &amp;)&gt; Func = &amp;drive; | ^~~~~ seminar.cpp:22:71: error: conversion from ‘std::vector (Tom::Car::Car::*)(Nor::Range&amp;)’ to non-scalar type ‘std::function(Nor::Range&amp;)&gt;’ requested </code></pre> <hr /> <p>Taking reference from <a href="https://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class">this</a> answer</p> <p>I tried this way :</p> <pre><code>std::function&lt;std::vector&lt;uint8_t&gt;(Nor::Range)&gt; f = std::bind(&amp;Car::drive, this); </code></pre> <p>And Got this error:</p> <pre><code>/usr/include/c++/9/functional:775:7: error: static assertion failed: Wrong number of arguments for pointer-to-member 774 | static_assert(_Varargs::value | ~~~~~ 775 | ? sizeof...(_BoundArgs) &gt;= _Arity::value + 1 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 776 | : sizeof...(_BoundArgs) == _Arity::value + 1, | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ seminar.cpp: In member function ‘std::vector&lt;unsigned char&gt; Tom::Car::Car::road(Nor::Driving&amp;)’: seminar.cpp:23:73: error: conversion from ‘std::_Bind_helper (Tom::Car::Car::*)(Nor::Range&amp;), Tom::Car::Car*&gt;::type’ {aka ‘std::_Bind (Tom::Car::Car::*(Tom::Car::Car*))(Nor::Range&amp;)&gt;’} to non-scalar type ‘std::function(Nor::Range)&gt;’ requested 23 | std::function&lt;std::vector&lt;uint8_t&gt;(Nor::Range)&gt; f = std::bind(&amp;Car::drive, this); | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~ seminar.cpp:25:40: error: ‘Func’ was not declared in this scope 25 | return Content(driving, 1, Func); </code></pre> <p>See here <a href="https://onlinegdb.com/GqRdzfxinV" rel="nofollow noreferrer">live</a></p> <hr /> <p>I don't know correctly what I am doing wrong in moving the implementation of <code>drive</code> function can someone please help with implementing the corrrect way.</p> <p>Note:: I'm fine if the solution uses another way to pass the function ie by not using <code>std::function</code> . Thanks</p>
[ { "answer_id": 74500762, "author": "Nelfeal", "author_id": 3854570, "author_profile": "https://Stackoverflow.com/users/3854570", "pm_score": 3, "selected": true, "text": "std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;\n drive this std::function<std::vector<uint8_t>(Nor::Range &)> Func = [this](Nor::Range & r) {\n return this->drive(r);\n};\n std::bind Nor::Range& std::function<std::vector<uint8_t>(Nor::Range &)> Func = std::bind(&Car::drive, this, std::placeholders::_1);\n std::function auto auto Func = [this](Nor::Range & r) {\n return this->drive(r);\n};\n" }, { "answer_id": 74501066, "author": "Shuangcheng Ni", "author_id": 19782707, "author_profile": "https://Stackoverflow.com/users/19782707", "pm_score": 1, "selected": false, "text": "return_type (class_name::*pointer_name)(arg_types...) = &class_name::function_name;\n (instance_name.*pointer_name)(args...);\n function bind function function auto auto Func = std::bind(&Car::drive, this, std::placeholders::_1);\n std::placeholders::_1 Nor::Range &range Car::drive" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483318/" ]
74,500,670
<p>I am new to selenium, and I get the following error: <code>element click intercepted: Element is not clickable at point (774, 8907)</code> whenever I run this code on the webpage that has the show more button. My goal is to get every element of the &quot;table&quot; on the webpage, but in order to do so I need to click &quot;show more&quot; button if it is present:</p> <pre><code>driver = webdriver.Chrome(options=chrome_options) driver.maximize_window() for el in states_pages: driver.get(el) err = False i = 0 while not err: try: more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content') more_button.click() except selexp.NoSuchElementException as e: err = True print(e) except selexp.ElementClickInterceptedException as e: err = True print(e) i+=1 </code></pre> <p>I have tried using javascript executor, waiting until the button is clickable and crolling to the button by using actions, but this didn't work at all.</p> <p>Sample website: <a href="https://www.privateschoolreview.com/sat-score-stats/california" rel="nofollow noreferrer">https://www.privateschoolreview.com/sat-score-stats/california</a> <a href="https://i.stack.imgur.com/JSZZF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JSZZF.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74500984, "author": "AbiSaran", "author_id": 7671727, "author_profile": "https://Stackoverflow.com/users/7671727", "pm_score": 0, "selected": false, "text": "show_more_lnk = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\ndriver.execute_script(\"arguments[0].scrollIntoView(true)\", show_more_lnk)\ntime.sleep(2)\nshow_more_lnk.click()\n" }, { "answer_id": 74501070, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 3, "selected": true, "text": " import time\n while not err:\n try:\n more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')\n driver.execute_script(\"arguments[0].click();\" ,more_button)\n time.sleep(1)\n except selexp.NoSuchElementException as e:\n err = True\n print(e)\n except selexp.ElementClickInterceptedException as e:\n err = True\n print(e)\n break\n from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument('--disable-blink-features=AutomationControlled')\noptions.add_argument(\"start-maximized\")\n#options.add_experimental_option(\"detach\", True)\n\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s, options=options)\nurl='https://www.privateschoolreview.com/sat-score-stats/california'\ndriver.get(url)\ntime.sleep(3)\n\ndata =[]\nfor x in range(4):\n try:\n soup = BeautifulSoup(driver.page_source, 'lxml')\n cards = soup.select('[class=\"tp-list-row list-row-border-2 bg_hover_change\"]')\n print(len(cards))\n for x in cards:\n title = x.select_one('a[class=\"tpl-school-link top-school\"]')\n title = title.get_text(strip=True) if title else 'None'\n data.append(title)\n\n \n loadMoreButton = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\n \n if loadMoreButton:\n driver.execute_script(\"arguments[0].click();\" ,loadMoreButton)\n time.sleep(1)\n\n \n except Exception as e:\n pass\n #print(e)\n break\n\ndf= pd.DataFrame(set(data))\nprint(df)\n 0\n0 St. Lucys Priory High School\n1 Glendale Adventist Academy\n2 The Webb Schools\n3 Desert Christian Academy\n4 New Covenant Academy\n.. ...\n113 Renaissance Academy\n114 Oak Grove School\n115 Francis Parker School\n116 Rolling Hills Preparatory School\n117 Lake Tahoe Preparatory School\n\n[118 rows x 1 columns]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16317247/" ]
74,500,683
<p>`</p> <pre><code>router.post(&quot;/login&quot;, (req, res) =&gt; { console.log(req.body.username) console.log(req.body.password) res.redirect(&quot;/&quot;) }) </code></pre> <p><code> </code></p> <pre><code>&lt;body&gt; &lt;form action=&quot;/register&quot; method=&quot;post&quot;&gt; &lt;label for=&quot;username&quot;&gt; &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Username&quot; id=&quot;username&quot; required&gt; &lt;label for=&quot;password&quot;&gt; &lt;i class=&quot;fas fa-lock&quot;&gt;&lt;/i&gt; &lt;/label&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Password&quot; id=&quot;password&quot; required&gt; &lt;input type=&quot;submit&quot; value=&quot;Login&quot;&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>`</p> <p>I just started learning express but already have a problem and I can't find any fixes. Somehow the req.body variable is undefined in the post. This is going to be a login system. (Sorry for my bad english)</p> <p>I first tried to do it like here on github: <a href="https://github.com/WebDevSimplified/express-crash-course" rel="nofollow noreferrer">https://github.com/WebDevSimplified/express-crash-course</a> but i still had the &quot;TypeError: Cannot read properties of undefined&quot; error in my console. So I was looking for something else and found this: <a href="https://codeshack.io/basic-login-system-nodejs-express-mysql/" rel="nofollow noreferrer">https://codeshack.io/basic-login-system-nodejs-express-mysql/</a> My code is based on the codeshack example but I'm still getting the error.</p>
[ { "answer_id": 74500984, "author": "AbiSaran", "author_id": 7671727, "author_profile": "https://Stackoverflow.com/users/7671727", "pm_score": 0, "selected": false, "text": "show_more_lnk = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\ndriver.execute_script(\"arguments[0].scrollIntoView(true)\", show_more_lnk)\ntime.sleep(2)\nshow_more_lnk.click()\n" }, { "answer_id": 74501070, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 3, "selected": true, "text": " import time\n while not err:\n try:\n more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')\n driver.execute_script(\"arguments[0].click();\" ,more_button)\n time.sleep(1)\n except selexp.NoSuchElementException as e:\n err = True\n print(e)\n except selexp.ElementClickInterceptedException as e:\n err = True\n print(e)\n break\n from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument('--disable-blink-features=AutomationControlled')\noptions.add_argument(\"start-maximized\")\n#options.add_experimental_option(\"detach\", True)\n\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s, options=options)\nurl='https://www.privateschoolreview.com/sat-score-stats/california'\ndriver.get(url)\ntime.sleep(3)\n\ndata =[]\nfor x in range(4):\n try:\n soup = BeautifulSoup(driver.page_source, 'lxml')\n cards = soup.select('[class=\"tp-list-row list-row-border-2 bg_hover_change\"]')\n print(len(cards))\n for x in cards:\n title = x.select_one('a[class=\"tpl-school-link top-school\"]')\n title = title.get_text(strip=True) if title else 'None'\n data.append(title)\n\n \n loadMoreButton = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\n \n if loadMoreButton:\n driver.execute_script(\"arguments[0].click();\" ,loadMoreButton)\n time.sleep(1)\n\n \n except Exception as e:\n pass\n #print(e)\n break\n\ndf= pd.DataFrame(set(data))\nprint(df)\n 0\n0 St. Lucys Priory High School\n1 Glendale Adventist Academy\n2 The Webb Schools\n3 Desert Christian Academy\n4 New Covenant Academy\n.. ...\n113 Renaissance Academy\n114 Oak Grove School\n115 Francis Parker School\n116 Rolling Hills Preparatory School\n117 Lake Tahoe Preparatory School\n\n[118 rows x 1 columns]\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548073/" ]
74,500,726
<p>How to find smallest element of array V(12,9) and its number?</p> <pre><code>Private Sub Command2_Click() Dim V(1 To 12, 1 To 9) As Integer Randomize For i = 1 To 12 For j = 1 To 9 V(i, j) = Rnd * 50 Next j Next i </code></pre>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20356699/" ]
74,500,748
<p>I am creating a simple blogging application and would like users to be able to like a post.</p> <p>In terms of scalability I've decided it would be best to have likes as a separate table made up of pointers to both the user and post.</p> <p>I have managed to enable the post request adding a like to the model however the <code>likes</code> field in the post model is not incrementing.</p> <p>I've tried using a simple <code>likes += 1</code> technique in the serializer but that made no changes and have now used an <code>F</code> string but still no changes are being made. I am still fairly new to Django and suspect it may be because I'm trying to update a field on a different model within a <code>CreateAPIView</code> serializer but I'm not sure.</p> <p>This is what I have so far</p> <pre><code># views.py class LikeView(generics.CreateAPIView): permission_classes = [ permissions.IsAuthenticated, ] queryset = Like.objects.all() serializer_class = LikeSerializer def like(self, request, format=None): serializer = self.serializer_class(data=request.data) if(serializer.is_valid()): user_id = serializer.data.get('user_id') post_id = serializer.data.get('post_id') l = Like(user_id=user_id, post_id=post_id) l.save() # likes field not updating with this post = Post.objects.get(id=post_id) post.likes = F('likes') + 1 post.save() return Response(LikeSerializer(l).data, status=status.HTTP_200_OK) return Response(serializer.errors(), status=status.HTTP_400_BAD_REQUEST) </code></pre> <pre><code>#models.py class Post(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) content = models.TextField() likes = models.IntegerField(default=0, blank=True) pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Like(models.Model): user_id = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE) post_id = models.ForeignKey(Post, related_name='post_id', on_delete=models.CASCADE) def __str__(self): return &quot;%s %s&quot; % (self.user_id, self.post_id) </code></pre> <pre><code>#serializers.py class LikeSerializer(serializers.ModelSerializer): class Meta: fields= ( 'user_id', 'post_id' ) model = Like </code></pre> <p>Thank you</p>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14611431/" ]
74,500,765
<p>So I am getting a list of strings from a server,</p> <pre><code>let a=&quot;18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]&quot;; </code></pre> <p>and with every set of data I am adding a close bracket, which means the set of data is now complete.</p> <p>So The data look like this</p> <pre><code>mac = &quot;18647AF0D0&quot;; TTL = &quot;59&quot; TIME = &quot;6&quot; </code></pre> <p>And the server continues to send the data, which is added to the variable <code>a</code></p> <p>Now This data I need to display on the web server on a HTML site, which has already been designed.</p> <p>So The issue is here when the server sends sometime it sends a same mac value with a updated TTL and TIME</p> <pre><code>1864726A,85,5]1864726A,75,5] </code></pre> <p>Here, if you see, I am getting the same mac value, so what I want to do is if the mac value already exists, then just update the TTL and TIME values on the same position; it should not be creating another entry.</p> <p>So I was trying to store this value into an array using a split function, but it's getting too complicated, so I am stuck here.</p> <p>Here is my html page :- <a href="https://codepen.io/kanxababu/pen/KKeZKQZ" rel="nofollow noreferrer">https://codepen.io/kanxababu/pen/KKeZKQZ</a></p>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14461920/" ]
74,500,767
<p>I am trying to create a dynamodb table from yml file to make a microservice, but it tells me that the table does not exist</p> <p>Error: UPDATE_FAILED: productGroupTable (AWS::DynamoDB::Table) Resource handler returned message: &quot;Table: productGroupTableDev does not exist.&quot; (RequestToken: bdc2ae26-5fde-6965-8609-bdaddff79ddf, HandlerErrorCode: NotFound)</p> <p>this is my yml file</p> <pre><code>custom: product: wms modelName: productGroups microServiceAction: create microServiceVersion: v1 microService: wms-productGroups-create-v1 capacities: - table: productGroupTable read: minimum: 5 # Minimum read capacity maximum: 100 # Maximum read capacity usage: 0.60 # Targeted usage percentage write: minimum: 5 # Minimum write capacity maximum: 50 # Maximum write capacity usage: 0.60 # Targeted usage percentage resources: Resources: productGroupTable: Type: AWS::DynamoDB::Table DeletionPolicy: Retain Properties: TableName: productGroupTableDev AttributeDefinitions: - AttributeName: id AttributeType: S - AttributeName: external_id AttributeType: S KeySchema: - AttributeName: id KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 GlobalSecondaryIndexes: - IndexName: &quot;external_id-index&quot; KeySchema: - AttributeName: external_id KeyType: HASH Projection: NonKeyAttributes: ProjectionType: KEYS_ONLY ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 provider: environment: MICROSERVICE_CREATE_PRODUCT_GROUP: wms-productGroups-create-v1-lambda-dev plugins: - serverless-dynamodb-autoscaling functions: P_1_3_1_productGroup_create: name: wms-productGroups-create-v1-lambda-dev handler: src.P_1_3_1_productGroup_create.core.handler.product_groups_create environment: DB_NAME: productGroupTableDev JSON_SCHEMA_PATH: ./src/P_1_3_1_productGroup_create/core/wms-productGroups-create-v1-schema.json timeout: 30 events: - http: method: POST path: products/create/groups/ cors: true # request: # schemas: # application/json: ${self:provider.apiGateway.request.schemas.model} # if you want to raise schema validator error from api gateway # application/json: ${self:provider.apiGateway.request.schemas.model.schema} - eventBridge: pattern: source: - wms-serverless.dev.event detail-type: - CREATE_PRODUCT_GROUP </code></pre> <p>my iam policities</p> <pre><code>Policies: - PolicyName: ${self:custom.microService}-${opt:stage, 'dev'}-lambda PolicyDocument: Version: '2012-10-17' Statement: [ { Effect: 'Allow', Action: [ 'cognito-idp:AdminInitiateAuth', 'events:PutEvents', 'lambda:InvokeFunction' ], Resource: '*' }, { Effect: 'Allow', Action: [ 'dynamodb:GetItem', 'dynamodb:Scan', 'dynamodb:PutItem' ], Resource: 'arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/*' }, { Effect: 'Allow', Action: [ 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents' ], Resource: 'arn:aws:logs:${aws:region}:${aws:accountId}:log-group:/aws/lambda/*' } ] </code></pre>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457279/" ]
74,500,779
<p>I have written some type conversion operators which only make sense in the context of a subset of types.</p> <p>An example is below</p> <pre><code>explicit virtual operator DataId&lt;float&gt;() const { static_assert(std::is_same_v&lt;T, DataId&lt;float&gt;&gt;, &quot;std::is_same_v&lt;T, DataId&lt;float&gt;&gt;&quot;); return data; // T data } </code></pre> <p>This class contains an object of type <code>T=DataId&lt;U&gt;</code>, where <code>U=float, int, double, std::string</code>.</p> <p><code>static_assert</code> seems to demand that the argument passed to it to create the error message is a <code>const char*</code>.</p> <p>Is there a way to print the type of <code>T</code> in the message?</p> <p>I tried, but failed, with this attempt:</p> <pre><code>constexpr auto message( (std::string(&quot;std::is_same_v&lt;T=&quot;) + typeid(T).name() + &quot;, DataId&lt;float&gt;&gt;&quot;).c_str() ); static_assert&lt;..., message&gt;; </code></pre>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893254/" ]
74,500,810
<p>I have the following query:</p> <pre><code>MATCH (n) WHERE n.uid IN $uids WITH n as nodes, apoc.agg.minItems(n, n.level).items as highestNode MATCH (nodes)-[:TRANSLATES_TO]-(a) where a.tree_id = apoc.agg.first(highestNode).tree_id return nodes, a </code></pre> <p>I'm getting the error <code>Aggregations should not be used like this.</code> This is happening when introducing the <code>first</code> function on the third line of the query. <code>minItems</code> returns a map with the same key for each node so I need to get the first element of the map somehow. What <code>minItems</code> returns:</p> <p><a href="https://i.stack.imgur.com/eJtoo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJtoo.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14790871/" ]
74,500,818
<h1>Problem Statement</h1> <p>I am trying to run a JavaScript code inside Python using <a href="https://github.com/cloudflare/stpyv8" rel="nofollow noreferrer">stpyv8</a>. However, I am getting the following error:</p> <pre><code>Traceback (most recent call last): File &quot;/home/bobby/uni_balances_stpyv8/main.py&quot;, line 4, in &lt;module&gt; output = ctxt.eval(&quot;&quot;&quot; SyntaxError: SyntaxError: Cannot use import statement outside a module ( @ 3 : 0 ) -&gt; import { JSBI } from &quot;@uniswap/sdk&quot;; </code></pre> <p>I do have a <code>package.json</code> file and my hunch is that the Python code isn't considering the json file because the error above is actually solved by the <code>package.json</code> file <a href="https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import">Fixing module error in JS</a>:</p> <pre><code>{ &quot;type&quot;: &quot;module&quot;, &quot;devDependencies&quot;: { &quot;@babel/cli&quot;: &quot;^7.19.3&quot;, &quot;@babel/core&quot;: &quot;^7.20.2&quot;, &quot;@babel/preset-env&quot;: &quot;^7.20.2&quot; }, &quot;dependencies&quot;: { &quot;@uniswap/sdk&quot;: &quot;^3.0.3&quot;, &quot;ethers&quot;: &quot;^5.7.2&quot; } } </code></pre> <p>I do have package.json</p> <p>The JavaScript does run and outputs the following:</p> <p>Here is the JavaScript file:</p> <p><a href="https://i.stack.imgur.com/r2vv2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r2vv2.png" alt="js output" /></a></p> <pre><code>import { JSBI } from &quot;@uniswap/sdk&quot;; import { ethers } from 'ethers'; import * as fs from 'fs'; // ERC20 json abi file let ERC20Abi = fs.readFileSync('Erc20.json'); const ERC20 = JSON.parse(ERC20Abi); // V3 pool abi json file let pool = fs.readFileSync('V3PairAbi.json'); const IUniswapV3PoolABI = JSON.parse(pool); // V3 factory abi json let facto = fs.readFileSync('V3factory.json'); const IUniswapV3FactoryABI = JSON.parse(facto); let NFT = fs.readFileSync('UniV3NFT.json'); const IUniswapV3NFTmanagerABI = JSON.parse(NFT); const provider = new ethers.providers.JsonRpcProvider(ALCHEMY_API_ID) // V3 standard addresses (different for celo) const factory = &quot;0x1F98431c8aD98523631AE4a59f267346ea31F984&quot;; const NFTmanager = &quot;0xC36442b4a4522E871399CD717aBDD847Ab11FE88&quot;; async function getData(tokenID){ let FactoryContract = new ethers.Contract(factory, IUniswapV3FactoryABI, provider); let NFTContract = new ethers.Contract(NFTmanager, IUniswapV3NFTmanagerABI, provider); let position = await NFTContract.positions(tokenID); let token0contract = new ethers.Contract(position.token0, ERC20, provider); let token1contract = new ethers.Contract(position.token1, ERC20, provider); let token0Decimal = await token0contract.decimals(); let token1Decimal = await token1contract.decimals(); let token0sym = await token0contract.symbol(); let token1sym = await token1contract.symbol(); let V3pool = await FactoryContract.getPool(position.token0, position.token1, position.fee); let poolContract = new ethers.Contract(V3pool, IUniswapV3PoolABI, provider); let slot0 = await poolContract.slot0(); let pairName = token0sym +&quot;/&quot;+ token1sym; let dict = {&quot;SqrtX96&quot; : slot0.sqrtPriceX96.toString(), &quot;Pair&quot;: pairName, &quot;T0d&quot;: token0Decimal, &quot;T1d&quot;: token1Decimal, &quot;tickLow&quot;: position.tickLower, &quot;tickHigh&quot;: position.tickUpper, &quot;liquidity&quot;: position.liquidity.toString()} return dict } const Q96 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(96)); const MIN_TICK = -887272; const MAX_TICK = 887272; function getTickAtSqrtRatio(sqrtPriceX96){ let tick = Math.floor(Math.log((sqrtPriceX96/Q96)**2)/Math.log(1.0001)); return tick; } async function getTokenAmounts(liquidity,sqrtPriceX96,tickLow,tickHigh,token0Decimal,token1Decimal){ let sqrtRatioA = Math.sqrt(1.0001**tickLow).toFixed(18); let sqrtRatioB = Math.sqrt(1.0001**tickHigh).toFixed(18); let currentTick = getTickAtSqrtRatio(sqrtPriceX96); let sqrtPrice = sqrtPriceX96 / Q96; let amount0wei = 0; let amount1wei = 0; if(currentTick &lt;= tickLow){ amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtRatioA)/(sqrtRatioA*sqrtRatioB))); } if(currentTick &gt; tickHigh){ amount1wei = Math.floor(liquidity*(sqrtRatioB-sqrtRatioA)); } if(currentTick &gt;= tickLow &amp;&amp; currentTick &lt; tickHigh){ amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtPrice)/(sqrtPrice*sqrtRatioB))); amount1wei = Math.floor(liquidity*(sqrtPrice-sqrtRatioA)); } let amount0Human = (amount0wei/(10**token0Decimal)).toFixed(token0Decimal); let amount1Human = (amount1wei/(10**token1Decimal)).toFixed(token1Decimal); console.log(&quot;Amount Token0 wei: &quot;+amount0wei); console.log(&quot;Amount Token1 wei: &quot;+amount1wei); console.log(&quot;Amount Token0 : &quot;+amount0Human); console.log(&quot;Amount Token1 : &quot;+amount1Human); return [amount0wei, amount1wei] } async function start(positionID){ let data = await getData(positionID); let tokens = await getTokenAmounts(data.liquidity, data.SqrtX96, data.tickLow, data.tickHigh, data.T0d, data.T1d); } start(273381) // Also it can be used without the position data if you pull the data it will work for any range getTokenAmounts(12558033400096537032, 20259533801624375790673555415) </code></pre> <p>Python3 code:</p> <pre><code>import STPyV8 with STPyV8.JSContext() as ctxt: output = ctxt.eval(&quot;&quot;&quot; import { JSBI } from &quot;@uniswap/sdk&quot;; import { ethers } from 'ethers'; import * as fs from 'fs'; // ERC20 json abi file let ERC20Abi = fs.readFileSync('Erc20.json'); const ERC20 = JSON.parse(ERC20Abi); // V3 pool abi json file let pool = fs.readFileSync('V3PairAbi.json'); const IUniswapV3PoolABI = JSON.parse(pool); // V3 factory abi json let facto = fs.readFileSync('V3factory.json'); const IUniswapV3FactoryABI = JSON.parse(facto); let NFT = fs.readFileSync('UniV3NFT.json'); const IUniswapV3NFTmanagerABI = JSON.parse(NFT); const provider = new ethers.providers.JsonRpcProvider(&quot;https://eth-mainnet.g.alchemy.com/v2/fRrLGBzCur7V6wCQjGRPdtmTUQzjCk2F&quot;) // V3 standard addresses (different for celo) const factory = &quot;0x1F98431c8aD98523631AE4a59f267346ea31F984&quot;; const NFTmanager = &quot;0xC36442b4a4522E871399CD717aBDD847Ab11FE88&quot;; async function getData(tokenID){ let FactoryContract = new ethers.Contract(factory, IUniswapV3FactoryABI, provider); let NFTContract = new ethers.Contract(NFTmanager, IUniswapV3NFTmanagerABI, provider); let position = await NFTContract.positions(tokenID); let token0contract = new ethers.Contract(position.token0, ERC20, provider); let token1contract = new ethers.Contract(position.token1, ERC20, provider); let token0Decimal = await token0contract.decimals(); let token1Decimal = await token1contract.decimals(); let token0sym = await token0contract.symbol(); let token1sym = await token1contract.symbol(); let V3pool = await FactoryContract.getPool(position.token0, position.token1, position.fee); let poolContract = new ethers.Contract(V3pool, IUniswapV3PoolABI, provider); let slot0 = await poolContract.slot0(); let pairName = token0sym +&quot;/&quot;+ token1sym; let dict = {&quot;SqrtX96&quot; : slot0.sqrtPriceX96.toString(), &quot;Pair&quot;: pairName, &quot;T0d&quot;: token0Decimal, &quot;T1d&quot;: token1Decimal, &quot;tickLow&quot;: position.tickLower, &quot;tickHigh&quot;: position.tickUpper, &quot;liquidity&quot;: position.liquidity.toString()} return dict } const Q96 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(96)); const MIN_TICK = -887272; const MAX_TICK = 887272; function getTickAtSqrtRatio(sqrtPriceX96){ let tick = Math.floor(Math.log((sqrtPriceX96/Q96)**2)/Math.log(1.0001)); return tick; } async function getTokenAmounts(liquidity,sqrtPriceX96,tickLow,tickHigh,token0Decimal,token1Decimal){ let sqrtRatioA = Math.sqrt(1.0001**tickLow).toFixed(18); let sqrtRatioB = Math.sqrt(1.0001**tickHigh).toFixed(18); let currentTick = getTickAtSqrtRatio(sqrtPriceX96); let sqrtPrice = sqrtPriceX96 / Q96; let amount0wei = 0; let amount1wei = 0; if(currentTick &lt;= tickLow){ amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtRatioA)/(sqrtRatioA*sqrtRatioB))); } if(currentTick &gt; tickHigh){ amount1wei = Math.floor(liquidity*(sqrtRatioB-sqrtRatioA)); } if(currentTick &gt;= tickLow &amp;&amp; currentTick &lt; tickHigh){ amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtPrice)/(sqrtPrice*sqrtRatioB))); amount1wei = Math.floor(liquidity*(sqrtPrice-sqrtRatioA)); } let amount0Human = (amount0wei/(10**token0Decimal)).toFixed(token0Decimal); let amount1Human = (amount1wei/(10**token1Decimal)).toFixed(token1Decimal); console.log(&quot;Amount Token0 wei: &quot;+amount0wei); console.log(&quot;Amount Token1 wei: &quot;+amount1wei); console.log(&quot;Amount Token0 : &quot;+amount0Human); console.log(&quot;Amount Token1 : &quot;+amount1Human); return [amount0wei, amount1wei] } async function start(positionID){ let data = await getData(positionID); let tokens = await getTokenAmounts(data.liquidity, data.SqrtX96, data.tickLow, data.tickHigh, data.T0d, data.T1d); } start(273381) // Also it can be used without the position data if you pull the data it will work for any range getTokenAmounts(12558033400096537032, 20259533801624375790673555415) &quot;&quot;&quot; ) output = ctxt.eval() print(output()) </code></pre> <p>Again going back to my hunch, is it possible that Python isn't able to recognize the <code>package.json</code> in my project folder?</p>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6725147/" ]
74,500,819
<p>I am trying to create a function miles to KM, but the result is float and does not transform it. Distance: is a column in integer format.</p> <p>the function 'miles_a_KM' receives the parameter miles, which is an integer column.</p> <pre><code>def miles_to_KM(miles): MIc = 1.609344 km = miles * MIc return(pd.DataFrame({'km':km}).fillna(0)) </code></pre> <p>the problem.</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [8], in &lt;cell line: 1&gt;() ----&gt; 1 miles_to_KM('Distance') Input In [7], in miles_to_KM(miles) 1 def miles_to_KM(miles): 2 MIc = 1.609344 ----&gt; 3 km = miles * MIc 4 return(pd.DataFrame({'km':km}).fillna(0)) TypeError: can't multiply sequence by non-int of type 'float' </code></pre> <p>try</p> <pre><code>return(pd.DataFrame({'km':km}).astype(float).fillna(0)) </code></pre>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485760/" ]
74,500,881
<p>I have a <strong>button</strong> in my Flutter project that I want the <strong>phone number</strong> to appear when it's pressed by the user, and when the number appears, the user can <strong>copy the number</strong> and use it, or when pressing the button, it goes to a <strong>direct call process</strong> with the phone number</p> <p>Is there a way or a widget by which I can achieve this?</p>
[ { "answer_id": 74500848, "author": "cooogeee", "author_id": 3003395, "author_profile": "https://Stackoverflow.com/users/3003395", "pm_score": 0, "selected": false, "text": "Dim i as Long\nDim j as Long\n V(i, j) = Rnd * 50\n Debug.Print WorksheetFunction.Min(V)\n" }, { "answer_id": 74501763, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 2, "selected": false, "text": "Private Sub Command2_Click()\n \n Const Max As Long = 50\n \n ' Populate the array.\n\n Dim V(1 To 12, 1 To 9) As Long\n \n Dim i As Long\n Dim j As Long\n \n Randomize\n For i = 1 To 12\n For j = 1 To 9\n V(i, j) = Rnd * Max\n Next j\n Next i\n \n Debug.Print GetDataString(V, , , \"Random numbers from 0 to \" & Max)\n \n Debug.Print \"How Min Was Changed in the Loop (It Started at \" & Max & \")\"\n Debug.Print \"The array was looped by rows.\"\n Debug.Print \"Visually find the following values to understand what happened.\"\n Debug.Print \"i\", \"j\", \"Min\"\n\n ' Calculate the minimum.\n \n Dim Min As Long: Min = Max\n \n For i = 1 To 12\n For j = 1 To 9\n If V(i, j) < Min Then\n Min = V(i, j)\n Debug.Print i, j, Min\n End If\n Next j\n Next i\n \n Debug.Print \"The minimum is \" & Min & \".\"\n \n MsgBox GetDataString(V, , , \"Random numbers from 0 to \" & Max) & vbLf _\n & \"The minimum is \" & Min & \".\", vbInformation\n \nEnd Sub\n\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of a 2D array in a string.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetDataString( _\n ByVal Data As Variant, _\n Optional ByVal RowDelimiter As String = vbLf, _\n Optional ByVal ColumnDelimiter As String = \" \", _\n Optional ByVal Title As String = \"PrintData Result\") _\nAs String\n \n ' Store the limits in variables\n Dim rLo As Long: rLo = LBound(Data, 1)\n Dim rHi As Long: rHi = UBound(Data, 1)\n Dim cLo As Long: cLo = LBound(Data, 2)\n Dim cHi As Long: cHi = UBound(Data, 2)\n \n ' Define the arrays.\n Dim cLens() As Long: ReDim cLens(rLo To rHi)\n Dim strData() As String: ReDim strData(rLo To rHi, cLo To cHi)\n \n ' For each column ('c'), store strings of the same length ('cLen')\n ' in the string array ('strData').\n \n Dim r As Long, c As Long\n Dim cLen As Long\n \n For c = cLo To cHi\n ' Calculate the current column's maximum length ('cLen').\n cLen = 0\n For r = rLo To rHi\n strData(r, c) = CStr(Data(r, c))\n cLens(r) = Len(strData(r, c))\n If cLens(r) > cLen Then cLen = cLens(r)\n Next r\n ' Store strings of the same length in the current column\n ' of the string array.\n If c = cHi Then ' last row (no column delimiter ('ColumnDelimiter'))\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c)\n Next r\n Else ' all but the last row\n For r = rLo To rHi\n strData(r, c) = Space(cLen - cLens(r)) & strData(r, c) _\n & ColumnDelimiter\n Next r\n End If\n Next c\n \n ' Write the title to the print string ('PrintString').\n Dim PrintString As String: PrintString = Title\n \n ' Append the data from the string array to the print string.\n For r = rLo To rHi\n PrintString = PrintString & RowDelimiter\n For c = cLo To cHi\n PrintString = PrintString & strData(r, c)\n Next c\n Next r\n \n ' Assign print string as the result.\n GetDataString = PrintString\n\nEnd Function\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20358871/" ]
74,500,889
<p>My use case is to serve response of an HTTP request after receiving another request from separate server.</p> <p><a href="https://i.stack.imgur.com/CHQX1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CHQX1.png" alt="enter image description here" /></a></p> <ol> <li>I want to do this best possible way keeping scaling in mind.</li> <li>We are using Golang 1.19 with Gin Framework.</li> <li>Server will have multiple pods thus channels will not work.</li> <li>There will be timeouts for all request making initial request timed out after 60 seconds.</li> </ol> <p>My current solution is to use a shared cache where each pod will keep checking the cache. I believe, I can optimize this with channels where rather than checking in cache one by one, system periodically checks for any completed response.</p> <p>I would also like to know how it could have been achieved in other programming languages.</p> <p>PS: This is design based query, I have some reputation here to share bounty thus asking here. Please feel free to edit if question is not clear.</p>
[ { "answer_id": 74503580, "author": "AminMal", "author_id": 14672383, "author_profile": "https://Stackoverflow.com/users/14672383", "pm_score": 2, "selected": true, "text": "server_app +---------------------+\n | server_app_service |\n +---------------------+\n | server_app_pod_a |\n | server_app_pod_b |\n | server_app_pod_c |\n +---------------------+\n \"request A\" server_app_pod_a server_app_pod_a request B server_app_pod_a request \"B\" Scala akka akka-cluster-sharding server_app server_app_pod_b serer_app_pod_b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3305978/" ]
74,500,926
<p>I created a .netcore webapi targeting framework 3.1. Added the required classes and code in ApplicationUser and ApplicationDbContext and in startup services.AddDbContext&lt;..........</p> <p>Then I ran command add-migration IniCr which built and ran ok. But when I ran the update-database console window shows the following error:</p> <pre><code>fail: Microsoft.EntityFrameworkCore.Database.Command[20102] Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE [AspNetUsers] ( [Id] nvarchar(450) NOT NULL, [UserName] nvarchar(256) NULL, [NormalizedUserName] nvarchar(256) NULL, [Email] nvarchar(256) NULL, [NormalizedEmail] nvarchar(256) NULL, [EmailConfirmed] bit NOT NULL, [PasswordHash] nvarchar(max) NULL, [SecurityStamp] nvarchar(max) NULL, [ConcurrencyStamp] nvarchar(max) NULL, [PhoneNumber] nvarchar(max) NULL, [PhoneNumberConfirmed] bit NOT NULL, [TwoFactorEnabled] bit NOT NULL, [LockoutEnd] datetimeoffset NULL, [LockoutEnabled] bit NOT NULL, [AccessFailedCount] int NOT NULL, CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id]) ); Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE [AspNetUsers] ( [Id] nvarchar(450) NOT NULL, [UserName] nvarchar(256) NULL, [NormalizedUserName] nvarchar(256) NULL, [Email] nvarchar(256) NULL, [NormalizedEmail] nvarchar(256) NULL, [EmailConfirmed] bit NOT NULL, [PasswordHash] nvarchar(max) NULL, [SecurityStamp] nvarchar(max) NULL, [ConcurrencyStamp] nvarchar(max) NULL, [PhoneNumber] nvarchar(max) NULL, [PhoneNumberConfirmed] bit NOT NULL, [TwoFactorEnabled] bit NOT NULL, [LockoutEnd] datetimeoffset NULL, [LockoutEnabled] bit NOT NULL, [AccessFailedCount] int NOT NULL, CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id]) ); System.AggregateException: An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.) ---&gt; System.InvalidOperationException: Cannot open log for source '.NET Runtime'. You may not have write access. ---&gt; System.ComponentModel.Win32Exception (1722): The RPC server is unavailable. --- End of inner exception stack trace --- at System.Diagnostics.EventLogInternal.OpenForWrite(String currentMachineName) at System.Diagnostics.EventLogInternal.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName) at System.Diagnostics.EventLogInternal.WriteEvent(EventInstance instance, Byte[] data, Object[] values) at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values) at Microsoft.Extensions.Logging.EventLog.WindowsEventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category) at Microsoft.Extensions.Logging.EventLog.EventLogLogger.WriteMessage(String message, EventLogEntryType eventLogEntryType, Int32 eventId) at Microsoft.Extensions.Logging.EventLog.EventLogLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) at Microsoft.Extensions.Logging.Logger.&lt;Log&gt;g__LoggerLog|12_0[TState](LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func`3 formatter, List`1&amp; exceptions, TState&amp; state) --- End of inner exception stack trace --- at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions) at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) at Microsoft.Extensions.Logging.LoggerMessage.&lt;&gt;c__DisplayClass10_0`6.&lt;Define&gt;b__0(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition`6.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, WarningBehavior warningBehavior, TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4, TParam5 arg5, TParam6 arg6) at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.LogCommandError(IDiagnosticsLogger`1 diagnostics, DbCommand command, TimeSpan duration, EventDefinition`6 definition) at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.CommandError(IDiagnosticsLogger`1 diagnostics, IRelationalConnection connection, DbCommand command, DbContext context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, DateTimeOffset startTime, TimeSpan duration) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject) at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.&lt;&gt;c__DisplayClass0_0.&lt;.ctor&gt;b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.) </code></pre> <p>When I check my mssql server I see a new db created as per the name I gave in appsettinngs.json but only with 1 table - efmigrationhistory.</p> <p>Why such? What mistake did I make? What needs to be done to get the migration going and create the full database with aspnet identity? Please suggest the correction; Some help needed.</p>
[ { "answer_id": 74503580, "author": "AminMal", "author_id": 14672383, "author_profile": "https://Stackoverflow.com/users/14672383", "pm_score": 2, "selected": true, "text": "server_app +---------------------+\n | server_app_service |\n +---------------------+\n | server_app_pod_a |\n | server_app_pod_b |\n | server_app_pod_c |\n +---------------------+\n \"request A\" server_app_pod_a server_app_pod_a request B server_app_pod_a request \"B\" Scala akka akka-cluster-sharding server_app server_app_pod_b serer_app_pod_b" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4912001/" ]
74,500,959
<p>I have specific list of names (ABC, BCD, ......., JKL), Then separately I am maintain the another location with those list of name plus another separate words (Like - Off, ON, .... etc)</p> <p>So I need count then no of name mention only in that specific list.</p> <p>You can get my example in below G sheet, also Feel Free to contact me for any clarification.</p> <p><a href="https://docs.google.com/spreadsheets/d/1bKA1KOs36ZDfR6VY18Md260MaFJWvO8uY3zto8jscOE/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1bKA1KOs36ZDfR6VY18Md260MaFJWvO8uY3zto8jscOE/edit?usp=sharing</a></p> <p>Indika<a href="https://i.stack.imgur.com/OwmYS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OwmYS.png" alt="Sample" /></a></p> <p>Best regards</p> <p>Indika</p>
[ { "answer_id": 74501553, "author": "ztiaa", "author_id": 17887301, "author_profile": "https://Stackoverflow.com/users/17887301", "pm_score": 1, "selected": false, "text": "=ArrayFormula(BYROW(D2:O,LAMBDA(r,IF(COUNTBLANK(r)=COLUMNS(r),,\nSUM(--REGEXMATCH(r,\"\\b\"&TEXTJOIN(\"\\b|\\b\",1,A2:A11)&\"\\b\"))))))\n" }, { "answer_id": 74501651, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 1, "selected": false, "text": "=INDEX(BYROW(IF(\"\"=IFNA(VLOOKUP(D2:O11, A2:A, 1, )), 0, 1), \n LAMBDA(x, IFERROR(1/(1/SUM(x))))))\n" }, { "answer_id": 74502001, "author": "P.b", "author_id": 12634230, "author_profile": "https://Stackoverflow.com/users/12634230", "pm_score": 0, "selected": false, "text": " =BYROW(D2:O11,LAMBDA(x,SUM(--(ISNUMBER(MATCH(x,$A$2:$A$11,0)))))) =SUM(--(ISNUMBER(MATCH(D2:O2,$A$2:$A$11,0))))" }, { "answer_id": 74502724, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": true, "text": "=INDEX(BYROW(XLOOKUP(D2:O11, A2:A, IFERROR(A2:A/0, 1),,,1), \n LAMBDA(x, IFERROR(1/(1/SUM(x))))))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18131328/" ]
74,500,964
<p>I try to create a relation between two tables in a Spring Boot Application. I have the following Code:</p> <pre><code> @Entity @Table(name = &quot;account&quot;) @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Builder public class Account { @Id @Column(name=&quot;ID&quot;, nullable = false, updatable = false) @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long id; @Column(name=&quot;NAME&quot;, nullable = false) private String name; @Column(name=&quot;client_id&quot;, nullable = false) private Long clientId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = &quot;client_id&quot;, insertable=false, updatable=false) private Client client; } @Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Builder public class Client { @Id @Column(name=&quot;client_id&quot;, nullable = false, updatable = false) @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long id; @Column(name=&quot;NAME&quot;, nullable = false, unique = true) private String name; @OneToMany(mappedBy = &quot;client&quot;, cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private List&lt;Account&gt; accounts; } </code></pre> <p>I always get the error relation &quot;account&quot; does not exist. What could be wrong?</p> <pre><code> Caused by: org.postgresql.util.PSQLException: ERROR: relation &quot;account&quot; does not exist </code></pre>
[ { "answer_id": 74501798, "author": "Hasni Iheb", "author_id": 11335868, "author_profile": "https://Stackoverflow.com/users/11335868", "pm_score": 0, "selected": false, "text": "account" }, { "answer_id": 74507821, "author": "simplesystems", "author_id": 4853434, "author_profile": "https://Stackoverflow.com/users/4853434", "pm_score": 2, "selected": true, "text": "spring.jpa.hibernate.ddl-auto=create-drop\n spring.jpa.hibernate.ddl-auto=update\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4853434/" ]
74,500,987
<p>I CANNOT USE ANY IMPORTED LIBRARY. I have this task where I have some directories containing some files; every file contains, besides some words, the name of the next file to be opened, in its first line. Once every word of every files contained in a directory is opened, they have to be treated in a way that should return a single string; such string contains in its first position, the most frequent first letter of every word seen before, in its second position the most frequent second letter, and so on. I have managed to do this with a directory containing 3 files, but it's not using any type of chain-like mechanism, rather a passing of local variables. Some of my college colleagues suggested I had to use slicing of lists, but I can't figure out how. I CANNOT USE ANY IMPORTED LIBRARY. This is what I got:</p> <pre><code>''' The objective of the homework assignment is to design and implement a function that reads some strings contained in a series of files and generates a new string from all the strings read. The strings to be read are contained in several files, linked together to form a closed chain. The first string in each file is the name of another file that belongs to the chain: starting from any file and following the chain, you always return to the starting file. Example: the first line of file &quot;A.txt&quot; is &quot;B.txt,&quot; the first line of file &quot;B.txt&quot; is &quot;C.txt,&quot; and the first line of &quot;C.txt&quot; is &quot;A.txt,&quot; forming the chain &quot;A.txt&quot;-&quot;B.txt&quot;-&quot;C.txt&quot;. In addition to the string with the name of the next file, each file also contains other strings separated by spaces, tabs, or carriage return characters. The function must read all the strings in the files in the chain and construct the string obtained by concatenating the characters with the highest frequency in each position. That is, in the string to be constructed, at position p, there will be the character with the highest frequency at position p of each string read from the files. In the case where there are multiple characters with the same frequency, consider the alphabetical order. The generated string has a length equal to the maximum length of the strings read from the files. Therefore, you must write a function that takes as input a string &quot;filename&quot; representing the name of a file and returns a string. The function must construct the string according to the directions outlined above and return the constructed string. Example: if the contents of the three files A.txt, B.txt, and C.txt in the directory test01 are as follows test01/A.txt test01/B.txt test01/C.txt ------------------------------------------------------------------------------- test01/B.txt test01/C.txt test01/A.txt house home kite garden park hello kitchen affair portrait balloon angel surfing the function most_frequent_chars (&quot;test01/A.txt&quot;) will return &quot;hareennt&quot;. ''' def file_names_list(filename): intermezzo = [] lista_file = [] a_file = open(filename) lines = a_file.readlines() for line in lines: intermezzo.extend(line.split()) del intermezzo[1:] lista_file.append(intermezzo[0]) intermezzo.pop(0) return lista_file def words_list(filename): lista_file = [] a_file = open(filename) lines = a_file.readlines()[1:] for line in lines: lista_file.extend(line.split()) return lista_file def stuff_list(filename): file_list = file_names_list(filename) the_rest = words_list(filename) second_file_name = file_names_list(file_list[0]) the_lists = words_list(file_list[0]) and words_list(second_file_name[0]) the_rest += the_lists[0:] return the_rest def most_frequent_chars(filename): huge_words_list = stuff_list(filename) maxOccurs = &quot;&quot; list_of_chars = [] for i in range(len(max(huge_words_list, key=len))): for item in huge_words_list: try: list_of_chars.append(item[i]) except IndexError: pass maxOccurs += max(sorted(set(list_of_chars)), key = list_of_chars.count) list_of_chars.clear() return maxOccurs print(most_frequent_chars(&quot;test01/A.txt&quot;)) </code></pre>
[ { "answer_id": 74501852, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 3, "selected": true, "text": "def read_file(fname):\n with open(fname, 'r') as f:\n return list(filter(None, [y.rstrip(' \\n').lstrip(' ') for x in f for y in x.split()]))\n\ndef read_chain(fname):\n seen = set()\n new = fname\n result = []\n while not new in seen:\n A = read_file(new)\n seen.add(new)\n new, words = A[0], A[1:]\n result.extend(words)\n return result\n\ndef most_frequent_chars (fname):\n all_words = read_chain(fname)\n result = []\n for i in range(max(map(len,all_words))):\n chars = [word[i] for word in all_words if i<len(word)]\n result.append(max(sorted(set(chars)), key = chars.count))\n return ''.join(result)\n\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n read_file x.split() list(filter(None, arr)) read_chain most_frequent_chars maxOccurs += max(sorted(set(list_of_chars)), key = list_of_chars.count) def scan_file(fname, database):\n with open(fname, 'r') as f:\n next_file = None\n for x in f:\n for y in x.split():\n if next_file is None:\n next_file = y\n else:\n for i,c in enumerate(y):\n while len(database) <= i:\n database.append({})\n if c in database[i]:\n database[i][c] += 1\n else:\n database[i][c] = 1\n return next_file\n\ndef most_frequent_chars (fname):\n database = []\n seen = set()\n new = fname\n while not new in seen:\n seen.add(new)\n new = scan_file(new, database)\n return ''.join(max(sorted(d.keys()),key=d.get) for d in database)\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n database" }, { "answer_id": 74501887, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "def parsi_file(filename):\n \n visited_files = set()\n words_list = []\n \n # Getting words from all files\n while filename not in visited_files:\n visited_files.add(filename)\n with open(filename) as f:\n filename = f.readline().strip()\n words_list += [line.strip() for line in f.readlines()] \n \n # Creating dictionaries of letters:count for each index\n letters_dicts = []\n for word in words_list:\n for i in range(len(word)): \n if i > len(letters_dicts)-1:\n letters_dicts.append({})\n letter = word[i]\n if letters_dicts[i].get(letter):\n letters_dicts[i][letter] += 1\n else:\n letters_dicts[i][letter] = 1\n \n # Sorting dicts and getting the \"best\" letter\n code = \"\"\n for dic in letters_dicts:\n sorted_letters = sorted(dic, key = lambda letter: (-dic[letter],letter))\n code += sorted_letters[0]\n \n return code\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20534052/" ]
74,500,998
<p>A problem given by my lab professor, as the title reads: <em>Find the largest combination given a list/array of integers.</em> ie:</p> <pre><code>input: {10, 68, 75, 7, 21, 12} stdout: 77568211210 my output : 75768211210 </code></pre> <p>The current code:</p> <pre><code>import java.util.*; import java.lang.*; public class classwork6 { static Scanner in = new Scanner(System.in); static void sort(String[] arr) { for(int i=0;i&lt;arr.length;i++) { for(int j=i+1;j&lt;arr.length;j++) { if(arr[i].compareTo(arr[j])&lt;0) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } public static void main(String[] args) { int[] list = {10, 68, 75, 7, 21, 12}; String[] arr = new String[list.length]; for(int i=0;i&lt;list.length;i++) { arr[i] = String.valueOf(list[i]); } sort(arr); System.out.print(Arrays.toString(arr).replaceAll(&quot;[\\[\\], ]&quot;,&quot;&quot;)); } } </code></pre> <p>My first attempt was simply sorting the array, after which I quickly found out that 777568211210&gt;75682112107</p> <p>My latest attempt was to lexicographically compare the string values of the integers. Yet the output is still incorrect 777568211210&gt;75768211210</p>
[ { "answer_id": 74501852, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 3, "selected": true, "text": "def read_file(fname):\n with open(fname, 'r') as f:\n return list(filter(None, [y.rstrip(' \\n').lstrip(' ') for x in f for y in x.split()]))\n\ndef read_chain(fname):\n seen = set()\n new = fname\n result = []\n while not new in seen:\n A = read_file(new)\n seen.add(new)\n new, words = A[0], A[1:]\n result.extend(words)\n return result\n\ndef most_frequent_chars (fname):\n all_words = read_chain(fname)\n result = []\n for i in range(max(map(len,all_words))):\n chars = [word[i] for word in all_words if i<len(word)]\n result.append(max(sorted(set(chars)), key = chars.count))\n return ''.join(result)\n\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n read_file x.split() list(filter(None, arr)) read_chain most_frequent_chars maxOccurs += max(sorted(set(list_of_chars)), key = list_of_chars.count) def scan_file(fname, database):\n with open(fname, 'r') as f:\n next_file = None\n for x in f:\n for y in x.split():\n if next_file is None:\n next_file = y\n else:\n for i,c in enumerate(y):\n while len(database) <= i:\n database.append({})\n if c in database[i]:\n database[i][c] += 1\n else:\n database[i][c] = 1\n return next_file\n\ndef most_frequent_chars (fname):\n database = []\n seen = set()\n new = fname\n while not new in seen:\n seen.add(new)\n new = scan_file(new, database)\n return ''.join(max(sorted(d.keys()),key=d.get) for d in database)\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n database" }, { "answer_id": 74501887, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "def parsi_file(filename):\n \n visited_files = set()\n words_list = []\n \n # Getting words from all files\n while filename not in visited_files:\n visited_files.add(filename)\n with open(filename) as f:\n filename = f.readline().strip()\n words_list += [line.strip() for line in f.readlines()] \n \n # Creating dictionaries of letters:count for each index\n letters_dicts = []\n for word in words_list:\n for i in range(len(word)): \n if i > len(letters_dicts)-1:\n letters_dicts.append({})\n letter = word[i]\n if letters_dicts[i].get(letter):\n letters_dicts[i][letter] += 1\n else:\n letters_dicts[i][letter] = 1\n \n # Sorting dicts and getting the \"best\" letter\n code = \"\"\n for dic in letters_dicts:\n sorted_letters = sorted(dic, key = lambda letter: (-dic[letter],letter))\n code += sorted_letters[0]\n \n return code\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74500998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16662311/" ]
74,501,021
<p>i'm pretty new to html and css. Browsed through previously asked similar questions but non of the solutions seems to work for me. Basically I have this situation:</p> <p><a href="https://i.stack.imgur.com/qyKKF.png" rel="nofollow noreferrer">Situation</a>.</p> <p>The desired effect is the content to be visible through the semi-transparent header, but the header shouldn't overlap the scrollbar.</p> <p>HTML is</p> <pre><code>&lt;body&gt; &lt;div class=&quot;flex&quot;&gt; &lt;nav&gt; &lt;/nav&gt; &lt;div class=&quot;container&quot;&gt; &lt;header&gt; &lt;/header&gt; &lt;div class=&quot;content&quot;&gt; some random text &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt; &lt;/footer&gt; &lt;/body&gt; </code></pre> <p>CSS is</p> <pre><code>*{ padding: 0; margin: 0; box-sizing: border-box; } .flex{ display: flex; } nav{ flex: 0 0 20rem; background-color: black; height: 90vh; } .container{ background-color: blue; flex-grow: 1; height: 90vh; overflow-y: auto; padding-top: 100px; } header{ height: 80px; position: fixed; top: 0; left: 20rem; right: 0; z-index: 1; background-color: rgba(0, 0, 0, 0.5); } .content{ height: 2000px; color: white; } footer{ height: 10vh; background-color: gray; } </code></pre> <p>Only solution I've found is to put a value into header {right} equal to the width of the scrollbar, but that's of course not reliable for all browsers, so it's just a trick, not a real solution.</p> <p>Tried using sticky but that way header doesn't overlap content as desired.</p> <p>Tried to put header directly inside content but it doesn't work neither.</p>
[ { "answer_id": 74501852, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 3, "selected": true, "text": "def read_file(fname):\n with open(fname, 'r') as f:\n return list(filter(None, [y.rstrip(' \\n').lstrip(' ') for x in f for y in x.split()]))\n\ndef read_chain(fname):\n seen = set()\n new = fname\n result = []\n while not new in seen:\n A = read_file(new)\n seen.add(new)\n new, words = A[0], A[1:]\n result.extend(words)\n return result\n\ndef most_frequent_chars (fname):\n all_words = read_chain(fname)\n result = []\n for i in range(max(map(len,all_words))):\n chars = [word[i] for word in all_words if i<len(word)]\n result.append(max(sorted(set(chars)), key = chars.count))\n return ''.join(result)\n\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n read_file x.split() list(filter(None, arr)) read_chain most_frequent_chars maxOccurs += max(sorted(set(list_of_chars)), key = list_of_chars.count) def scan_file(fname, database):\n with open(fname, 'r') as f:\n next_file = None\n for x in f:\n for y in x.split():\n if next_file is None:\n next_file = y\n else:\n for i,c in enumerate(y):\n while len(database) <= i:\n database.append({})\n if c in database[i]:\n database[i][c] += 1\n else:\n database[i][c] = 1\n return next_file\n\ndef most_frequent_chars (fname):\n database = []\n seen = set()\n new = fname\n while not new in seen:\n seen.add(new)\n new = scan_file(new, database)\n return ''.join(max(sorted(d.keys()),key=d.get) for d in database)\nprint(most_frequent_chars(\"test01/A.txt\"))\n# output: \"hareennt\"\n database" }, { "answer_id": 74501887, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "def parsi_file(filename):\n \n visited_files = set()\n words_list = []\n \n # Getting words from all files\n while filename not in visited_files:\n visited_files.add(filename)\n with open(filename) as f:\n filename = f.readline().strip()\n words_list += [line.strip() for line in f.readlines()] \n \n # Creating dictionaries of letters:count for each index\n letters_dicts = []\n for word in words_list:\n for i in range(len(word)): \n if i > len(letters_dicts)-1:\n letters_dicts.append({})\n letter = word[i]\n if letters_dicts[i].get(letter):\n letters_dicts[i][letter] += 1\n else:\n letters_dicts[i][letter] = 1\n \n # Sorting dicts and getting the \"best\" letter\n code = \"\"\n for dic in letters_dicts:\n sorted_letters = sorted(dic, key = lambda letter: (-dic[letter],letter))\n code += sorted_letters[0]\n \n return code\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548188/" ]
74,501,029
<p>I'm making a calculator in Python using Tkinter, and I'm getting an error im not sure as to why im running into this error but ive legit tried retyping the whole code and cant find anything about it on yt:</p> <p>`</p> <pre><code>from tkinter import * w = Tk() w.title(&quot;Simple Calculator&quot;) ent = Entry() ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10 ) def button_click(number): current = ent.get() ent.delete(0,END) ent.insert(0,str(current)+str(number)) def button_clear(): ent.delete(0, END) def button_add(first_number): first_number = ent.get() global f_num f_num = int(first_number) ent.delete(END) # Defining Button button_1 = Button(w,text=&quot;1&quot;,padx=40,pady=20,command=lambda:button_click(1)) button_2 = Button(w,text=&quot;2&quot;,padx = 40,pady = 20,command=lambda:button_click(2)) button_3 = Button(w,text=&quot;3&quot;,padx = 40,pady = 20,command=lambda:button_click(3)) button_4 = Button(w,text=&quot;4&quot;,padx = 40,pady = 20,command=lambda:button_click(4)) button_5 = Button(w,text=&quot;5&quot;,padx = 40,pady = 20,command=lambda:button_click(5)) button_6 = Button(w,text=&quot;6&quot;,padx = 40,pady = 20,command=lambda:button_click(6)) button_7 = Button(w,text=&quot;7&quot;,padx = 40,pady = 20,command=lambda:button_click(7)) button_8 = Button(w,text=&quot;8&quot;,padx = 40,pady = 20,command=lambda:button_click(8)) button_9 = Button(w,text=&quot;9&quot;,padx = 40,pady = 20,command=lambda:button_click(9)) button_0 = Button(w,text=&quot;0&quot;,padx = 40,pady = 20,command=lambda:button_click(0)) button_add = Button(w,text=&quot;+&quot;,padx=39,pady=20,command=button_add) button_equal = Button(w,text=&quot;=&quot;,padx = 91,pady = 20,command=button_click) button_clear = Button(w,text=&quot;CLEAR&quot;,padx = 79,pady = 20,command=button_clear) # Putting button on screen button_1.grid(row=3,column=0 ) button_2.grid(row=3,column= 1) button_3.grid(row=3,column= 2) button_4.grid(row=2,column= 0) button_5.grid(row=2,column= 1) button_6.grid(row=2,column= 2) button_7.grid(row=1,column= 0) button_8.grid(row=1,column= 1) button_9.grid(row=1,column= 2) button_0.grid(row=4,column= 0) button_clear.grid(row=4,column=1,columnspan=2) button_add.grid(row=5,column=0) button_equal.grid(row=5,column=1,columnspan=2) w.mainloop() </code></pre> <p>`</p> <p>i tried everything to fix this error P.S. I don't actually know which line the error is on, because it's saying that the error is on line 1705, even though the code is only 101 lines</p>
[ { "answer_id": 74501196, "author": "Seyi Daniel", "author_id": 13505098, "author_profile": "https://Stackoverflow.com/users/13505098", "pm_score": -1, "selected": true, "text": "def button_add():\nfirst_number = ent.get()\nglobal f_num\nf_num = int(first_number)\nent.delete(END)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16127284/" ]
74,501,053
<p>So I am trying to select all the rows that contains string equal to values from another table.</p> <pre><code>SELECT q.QUERY, f.ANONID FROM FACTS f INNER JOIN QUERYDIM q ON f.QUERYID = q.ID WHERE q.QUERY IN (SELECT city FROM zipcodes); </code></pre> <p>q.QUERY is a string with different lengths I want to select all the q.QUERY that contains value that is equal to any value in city</p> <p>example</p> <pre><code>one row: q.QUERY = &quot;this is a city called berlin&quot; </code></pre> <p>another row:</p> <pre><code>q.QUERY = &quot;in cairo it is nice&quot; SELECT city FROM zipcodes = (&quot;berlin&quot;,&quot;Birmingham&quot;,&quot;Huntsville&quot;,etc..) </code></pre> <p>so each q.QUERY loops through all the cities in the table every time</p> <p>I am trying to find all the rows that has values of city</p>
[ { "answer_id": 74501222, "author": "ScaisEdge", "author_id": 3522312, "author_profile": "https://Stackoverflow.com/users/3522312", "pm_score": 0, "selected": false, "text": "SELECT q.QUERY, f.ANONID \nFROM FACTS f\nINNER JOIN QUERYDIM q ON f.QUERYID = q.ID \nINNER JOIN ( SELECT city FROM zipcodes ) t on q.query like concat('%',t.city, '%');\n" }, { "answer_id": 74501257, "author": "Per Huss", "author_id": 6315242, "author_profile": "https://Stackoverflow.com/users/6315242", "pm_score": 2, "selected": true, "text": "select q.query, f.anonid \nfrom facts f\ninner join querydim q on f.queryid = q.id \nwhere exists (select 1 from zipcodes where locate(city, q.query));\n locate" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17473034/" ]
74,501,058
<p>I have an array with values</p> <pre><code>const range = [1,10,100,500,1000,2000,4000,8000] let input = 1580 </code></pre> <p>The expected output is 1000 because 1580 is between 1000 and 2000</p> <p>But my code is giving wrong results and also giving incorrect for large values.</p> <pre><code>for(i=0;i&lt;range.length;i++) { if(input &gt; range[i]) break; } console.log(range[i]) </code></pre>
[ { "answer_id": 74501088, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": false, "text": "input < range input const range = [1, 10, 100, 500, 1000, 2000, 4000, 8000]\nconst input = 1580\nlet i;\nfor (i = 0; i < range.length; i++) {\n if (input < range[i])\n break;\n}\nconsole.log(i);\nconsole.log(range[i - 1]) .reduce const range = [1,1560,10,100,500,1000,1500,2000,4000,8000,1550];\nconst input = 1580;\nconst output = range.reduce(\n (bestSoFar, num) => num > input ? bestSoFar : Math.max(bestSoFar, num),\n 0\n);\nconsole.log(output);" }, { "answer_id": 74501329, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const range = [1,10,100,500,1000,2000,4000,8000]\n\nlet input = 1580\n\nconsole.log(range.reduce((a,c)=>c<=input?c:a))" }, { "answer_id": 74501442, "author": "adarsh", "author_id": 13961769, "author_profile": "https://Stackoverflow.com/users/13961769", "pm_score": -1, "selected": false, "text": "for(i=0;i<range.length;i++)\n{\n if(input > range[i]) \n break;\n}\nconsole.log(range[i]);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549354/" ]
74,501,064
<p>How to remove duplicate by ID. For each ID, the column Drug must have unique values. Any help is appreciated.</p> <pre><code> dat &lt;- read.table(text=&quot;Id Drug A Meropenem A Ampicillin A Augmentin A Meropenem A Ampicillin A Augmentin B Meropenem B Ampicillin B Augmentin&quot;, header=TRUE) This is the desired output: dat.desired &lt;- read.table(text=&quot;Id Drug A Meropenem A Ampicillin A Augmentin B Meropenem B Ampicillin B Augmentin&quot;, header=TRUE) </code></pre>
[ { "answer_id": 74501088, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 2, "selected": false, "text": "input < range input const range = [1, 10, 100, 500, 1000, 2000, 4000, 8000]\nconst input = 1580\nlet i;\nfor (i = 0; i < range.length; i++) {\n if (input < range[i])\n break;\n}\nconsole.log(i);\nconsole.log(range[i - 1]) .reduce const range = [1,1560,10,100,500,1000,1500,2000,4000,8000,1550];\nconst input = 1580;\nconst output = range.reduce(\n (bestSoFar, num) => num > input ? bestSoFar : Math.max(bestSoFar, num),\n 0\n);\nconsole.log(output);" }, { "answer_id": 74501329, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const range = [1,10,100,500,1000,2000,4000,8000]\n\nlet input = 1580\n\nconsole.log(range.reduce((a,c)=>c<=input?c:a))" }, { "answer_id": 74501442, "author": "adarsh", "author_id": 13961769, "author_profile": "https://Stackoverflow.com/users/13961769", "pm_score": -1, "selected": false, "text": "for(i=0;i<range.length;i++)\n{\n if(input > range[i]) \n break;\n}\nconsole.log(range[i]);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19965337/" ]
74,501,067
<p>I am writing shiny apps that take an object (a photograph or a matrix of numbers mostly) and making a set of plots to explore the object. I want to setup the shiny app as a function so I can call it from a command line and pass the object of interest directly to it. I would like to be able to return the name of the object in titles of the graphs and so forth. I can do this with substitute() outside of the shiny app, but when I put it in the shiny app it returns the name of object &quot;inside the scope&quot; of the shiny function, not the name of the objet that was passed to the shiny function.</p> <p>Per suggestion, I used styler to improve the style of the code:</p> <pre><code> #this puts Children in the title of the graph which is what I want but I want a shiny app: myPlot &lt;- function(x) { plot(1:10, main = substitute(x)) } children &lt;- &quot;10&quot; myPlot(children) #when I do it inside the shiny App #this puts x in the title of the plot which is not what I want: require(shiny) app1 &lt;- function(x) { shinyApp( ui = mainPanel(plotOutput(&quot;plot1&quot;)), server = function(input, output) { output$plot1 &lt;- renderPlot(myPlot(x)) } ) } app1(children) </code></pre> <p>before the styler package:</p> <pre><code>#this puts Children in the title of the graph which is what I want but I want a shiny app: myPlot = function(x){ plot(1:10,main=substitute(x)) } children = &quot;10&quot; myPlot(children) #when I do it inside the shiny App #this puts x in the title of the plot which is not what I want: app1 = function(x) {shinyApp( ui = mainPanel(plotOutput(&quot;plot1&quot;)) , server = function(input,output){output$plot1 &lt;- renderPlot( plot(1:10,main=substitute(x)) )} )} app1(children) </code></pre>
[ { "answer_id": 74501487, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 1, "selected": false, "text": "app1 = function(x) {\n title <- substitute(x)\n shinyApp(\n ui = mainPanel(plotOutput(\"plot1\")),\n server = function(input, output){\n output$plot1 <- renderPlot( plot(1:10, main = title) )\n }\n )\n}\n" }, { "answer_id": 74508194, "author": "polkas", "author_id": 5442527, "author_profile": "https://Stackoverflow.com/users/5442527", "pm_score": 0, "selected": false, "text": "substitute substitute env fun <- function(x) substitute(expr = x, env = environment()) # current env is environment()\n# you can control the scope of the substitute\n# the parent.frame give us access to the nth previous env\nfun_deep2 <- function(x) {\n fun_temp <- function(x) {\n substitute(expr = x, env = parent.frame(n = 1))\n }\n fun_temp(x)\n}\n\nfun(hey)\nfun_deep2(hey)\n styler substitute x = 1:10; y = 1:10; do.call(t.test, list(x = x, y = y)) do.call(t.test, list(x = 1:10, y = 1:10)) do.call" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548300/" ]
74,501,093
<p>Hey this is my function</p> <pre><code>function open() { document.getElementById(&quot;main&quot;).style.marginLeft = &quot;20%&quot;; document.getElementById(&quot;mySidebar&quot;).style.width = &quot;20%&quot;; document.getElementById(&quot;mySidebar&quot;).style.display = &quot;block&quot;; document.getElementById(&quot;openNav&quot;).style.display = 'inline-block'; } function close() { document.getElementById(&quot;main&quot;).style.marginLeft = &quot;0%&quot;; document.getElementById(&quot;mySidebar&quot;).style.display = &quot;none&quot;; document.getElementById(&quot;openNav&quot;).style.display = &quot;inline-block&quot;; } function Test() { var item = document.getElementById(&quot;main&quot;).style.marginLeft =&quot;&quot;; if (item = &quot;0%&quot;) { w3_open() item = document.getElementById(&quot;main&quot;).style.marginLeft = &quot;20%&quot;; } else if (item = &quot;20%&quot;) { w3_close() } </code></pre> <p>}</p> <p>First part works perfectly, but after second click none happens..</p> <p>Idk whats wrong, can someone some suggestions?</p> <p>///UPDATE</p> <p>After clicking this:</p> <pre><code>&lt;button id=&quot;openNav&quot; class=&quot;w3-button w3-teal w3-xlarge&quot; onclick=&quot;Test()&quot;&gt;&amp;#9776;&lt;/button&gt; </code></pre> <p>I can open sidebar, but after clicking again i cannot close it. :/</p>
[ { "answer_id": 74501195, "author": "reza hrkeng", "author_id": 20517507, "author_profile": "https://Stackoverflow.com/users/20517507", "pm_score": -1, "selected": false, "text": "Id(\"openNav\").style.display='inline-block';\n function close() and open()\n function open() { \n\ndocument.getElementById(\"main\").style.marginLeft = \"20%\"; \n\n document.getElementById(\"mySidebar\").style.width = \"20%\"; \n \ndocument.getElementById(\"mySidebar\").style.display = \"block\"; \n\n document.getElementById(\"openNav\").style.display = 'inline-block'; } \n function close() { \n\n document.getElementById(\"main\").style.marginLeft = \"0\"; \n\n document.getElementById(\"mySidebar\").style.width = \"0 !important\"; \n\n document.getElementById(\"openNav\").style.display = \"inline-block\"; } \nfunction Test() { \nvar item=document.getElementById(\"main\").style.marginLeft ;\n if (item == \"0\") { \n w3_open() item = document.getElementById(\"main\").style.marginLeft ;\n} else if (item == \"20%\") { w3_close() }\n" }, { "answer_id": 74501253, "author": "pzutils", "author_id": 13812770, "author_profile": "https://Stackoverflow.com/users/13812770", "pm_score": 1, "selected": false, "text": "item \"0%\" \"\" var item = document.getElementById(\"main\").style.marginLeft =\"\";\n var item = document.getElementById(\"main\").style.marginLeft == = item = \"0%\" item == \"0%\" w3_open() w3_close() open() close()" }, { "answer_id": 74501254, "author": "anurag-dhamala", "author_id": 14917277, "author_profile": "https://Stackoverflow.com/users/14917277", "pm_score": 1, "selected": false, "text": "function open() {\n \n document.getElementById(\"main\").style.marginLeft = \"20%\";\n document.getElementById(\"mySidebar\").style.width = \"20%\";\n document.getElementById(\"mySidebar\").style.display = \"block\";\n }\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\";\n document.getElementById(\"mySidebar\").style.display = \"none\";\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft;\n if (item == \"0%\"){\n open()\n } else if (item == \"20%\"){ \n close()\n }\n}\n" }, { "answer_id": 74501691, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 3, "selected": true, "text": "marginLeft open() close() Test() function open() {\n document.getElementById(\"main\").style.marginLeft = \"20%\"\n document.getElementById(\"mySidebar\").style.width = \"20%\"\n document.getElementById(\"mySidebar\").style.display = \"block\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\"\n document.getElementById(\"mySidebar\").style.display = \"none\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft\n\n // simplified condition\n if (item == \"20%\") close()\n else open()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15868779/" ]
74,501,121
<p>I get two types of errors when I try to start or initiate the member function <code>temp_controll</code> from the subclass <code>Temperature_Controll</code>. The issue is that the while loops are started in a new thread.</p> <p>I am having trouble passing the modbus client connection to the member function.</p> <pre><code> AttributeError: 'ModbusTcpClient' object has no attribute 'modbus' </code></pre> <p>I don't understand the problem in its entirety, because I assumed I would inherit modbus.client from the main class?</p> <p>The second problem was, when I comment out rp and want to access a member function from the main class &quot;database_reading&quot;, I get the following error:</p> <pre><code> AttributeError: 'str' object has no attribute 'database_reading' </code></pre> <p>How can I execute the subclass method via a second thread?</p> <pre><code>class Echo(WebSocket): def __init__(self, client, server, sock, address): super().__init__(server, sock, address) self.modbus = client def database_reading(self) do_something() return data class Temperature_Controll2(Echo): def __init__(self, client): super(Temperature_Controll, self).__init__(client) self.modbus = client def temp_controll(self, value): #super().temp_controll(client) while True: print(&quot;temp_controll&quot;) rp = self.modbus.read_coils(524, 0x1) print(rp.bits[0]) self.database_reading() def main(): logging.basicConfig() with ModbusClient(host=HOST, port=PORT) as client: client.connect() time.sleep(0.01) print(&quot;Websocket server on port %s&quot; % PORTNUM) server = SimpleWebSocketServer('', PORTNUM, partial(Echo, client)) control = Temperature_Controll2.temp_controll t2 = threading.Thread(target=control, args=(client, 'get')) t2.start() try: t1 = threading.Thread(target=server.serveforever()) t1.start() finally: server.close() if __name__ == &quot;__main__&quot;: main() </code></pre> <p>This is a minimal example of my code, the thread t1 is executed without any problems. I have little experience with OOP programming, maybe someone here can help, thanks!</p>
[ { "answer_id": 74501195, "author": "reza hrkeng", "author_id": 20517507, "author_profile": "https://Stackoverflow.com/users/20517507", "pm_score": -1, "selected": false, "text": "Id(\"openNav\").style.display='inline-block';\n function close() and open()\n function open() { \n\ndocument.getElementById(\"main\").style.marginLeft = \"20%\"; \n\n document.getElementById(\"mySidebar\").style.width = \"20%\"; \n \ndocument.getElementById(\"mySidebar\").style.display = \"block\"; \n\n document.getElementById(\"openNav\").style.display = 'inline-block'; } \n function close() { \n\n document.getElementById(\"main\").style.marginLeft = \"0\"; \n\n document.getElementById(\"mySidebar\").style.width = \"0 !important\"; \n\n document.getElementById(\"openNav\").style.display = \"inline-block\"; } \nfunction Test() { \nvar item=document.getElementById(\"main\").style.marginLeft ;\n if (item == \"0\") { \n w3_open() item = document.getElementById(\"main\").style.marginLeft ;\n} else if (item == \"20%\") { w3_close() }\n" }, { "answer_id": 74501253, "author": "pzutils", "author_id": 13812770, "author_profile": "https://Stackoverflow.com/users/13812770", "pm_score": 1, "selected": false, "text": "item \"0%\" \"\" var item = document.getElementById(\"main\").style.marginLeft =\"\";\n var item = document.getElementById(\"main\").style.marginLeft == = item = \"0%\" item == \"0%\" w3_open() w3_close() open() close()" }, { "answer_id": 74501254, "author": "anurag-dhamala", "author_id": 14917277, "author_profile": "https://Stackoverflow.com/users/14917277", "pm_score": 1, "selected": false, "text": "function open() {\n \n document.getElementById(\"main\").style.marginLeft = \"20%\";\n document.getElementById(\"mySidebar\").style.width = \"20%\";\n document.getElementById(\"mySidebar\").style.display = \"block\";\n }\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\";\n document.getElementById(\"mySidebar\").style.display = \"none\";\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft;\n if (item == \"0%\"){\n open()\n } else if (item == \"20%\"){ \n close()\n }\n}\n" }, { "answer_id": 74501691, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 3, "selected": true, "text": "marginLeft open() close() Test() function open() {\n document.getElementById(\"main\").style.marginLeft = \"20%\"\n document.getElementById(\"mySidebar\").style.width = \"20%\"\n document.getElementById(\"mySidebar\").style.display = \"block\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\"\n document.getElementById(\"mySidebar\").style.display = \"none\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft\n\n // simplified condition\n if (item == \"20%\") close()\n else open()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20125632/" ]
74,501,151
<p>I am really struggling with a problem: I have to find all the leaves in a binary tree and sum them to their father using recursion and only basic controls(no specialised functions).</p> <p>I tried checking all the nodes' children to see if those were leaves and then add them to their fathers but it seems I can't get the recursion done correctly</p> <pre><code>t = { val: 1, sx: { val: 8, sx: { val: 7, sx: {}, dx: {} }, dx: { val: 1, sx: {}, dx: {} } }, dx: { val: 3, sx: { val: 5, sx: {}, dx: {} }, dx: {} } }; function pota3(t) { if (t == null) { return } if (t.dx != null) { if (t.dx.sx == null &amp;&amp; t.dx.dx == null) { t.val += t.dx.val delete t.dx } } if (t.sx != null) { if (t.sx.sx == null &amp;&amp; t.sx.dx == null) { t.val += t.sx.val delete t.sx } } pota3(t.dx) pota3(t.sx) } pota3(t) </code></pre> <p>wanted result:</p> <pre><code> t = { val: 1, sx: { val: 16,sx: {}, dx: {}}, dx: { val: 8, sx: {}, dx:{} } } </code></pre>
[ { "answer_id": 74501195, "author": "reza hrkeng", "author_id": 20517507, "author_profile": "https://Stackoverflow.com/users/20517507", "pm_score": -1, "selected": false, "text": "Id(\"openNav\").style.display='inline-block';\n function close() and open()\n function open() { \n\ndocument.getElementById(\"main\").style.marginLeft = \"20%\"; \n\n document.getElementById(\"mySidebar\").style.width = \"20%\"; \n \ndocument.getElementById(\"mySidebar\").style.display = \"block\"; \n\n document.getElementById(\"openNav\").style.display = 'inline-block'; } \n function close() { \n\n document.getElementById(\"main\").style.marginLeft = \"0\"; \n\n document.getElementById(\"mySidebar\").style.width = \"0 !important\"; \n\n document.getElementById(\"openNav\").style.display = \"inline-block\"; } \nfunction Test() { \nvar item=document.getElementById(\"main\").style.marginLeft ;\n if (item == \"0\") { \n w3_open() item = document.getElementById(\"main\").style.marginLeft ;\n} else if (item == \"20%\") { w3_close() }\n" }, { "answer_id": 74501253, "author": "pzutils", "author_id": 13812770, "author_profile": "https://Stackoverflow.com/users/13812770", "pm_score": 1, "selected": false, "text": "item \"0%\" \"\" var item = document.getElementById(\"main\").style.marginLeft =\"\";\n var item = document.getElementById(\"main\").style.marginLeft == = item = \"0%\" item == \"0%\" w3_open() w3_close() open() close()" }, { "answer_id": 74501254, "author": "anurag-dhamala", "author_id": 14917277, "author_profile": "https://Stackoverflow.com/users/14917277", "pm_score": 1, "selected": false, "text": "function open() {\n \n document.getElementById(\"main\").style.marginLeft = \"20%\";\n document.getElementById(\"mySidebar\").style.width = \"20%\";\n document.getElementById(\"mySidebar\").style.display = \"block\";\n }\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\";\n document.getElementById(\"mySidebar\").style.display = \"none\";\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft;\n if (item == \"0%\"){\n open()\n } else if (item == \"20%\"){ \n close()\n }\n}\n" }, { "answer_id": 74501691, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 3, "selected": true, "text": "marginLeft open() close() Test() function open() {\n document.getElementById(\"main\").style.marginLeft = \"20%\"\n document.getElementById(\"mySidebar\").style.width = \"20%\"\n document.getElementById(\"mySidebar\").style.display = \"block\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\"\n document.getElementById(\"mySidebar\").style.display = \"none\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft\n\n // simplified condition\n if (item == \"20%\") close()\n else open()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20471458/" ]
74,501,170
<p>In the code below, how can I change Jack's drink from &quot;Lemonade&quot; to &quot;Soda&quot; inside the <code>groupingDict</code>.</p> <pre><code>struct User { var name: String? var drink: String? } let u1 = User(name: &quot;Jack&quot;, drink: &quot;Lemonade&quot;) let u2 = User(name: &quot;Jill&quot;, drink: &quot;Iced Tea&quot;) let list = [u1, u2] var groupingDict = Dictionary(grouping: list, by: { $0.name }) print(&quot;groupingDict-original: &quot;, groupingDict) for (index, dict) in groupingDict.enumerated() { if dict.key == &quot;Jack&quot; { } } print(&quot;groupingDict-changed: &quot;, groupingDict) </code></pre>
[ { "answer_id": 74501195, "author": "reza hrkeng", "author_id": 20517507, "author_profile": "https://Stackoverflow.com/users/20517507", "pm_score": -1, "selected": false, "text": "Id(\"openNav\").style.display='inline-block';\n function close() and open()\n function open() { \n\ndocument.getElementById(\"main\").style.marginLeft = \"20%\"; \n\n document.getElementById(\"mySidebar\").style.width = \"20%\"; \n \ndocument.getElementById(\"mySidebar\").style.display = \"block\"; \n\n document.getElementById(\"openNav\").style.display = 'inline-block'; } \n function close() { \n\n document.getElementById(\"main\").style.marginLeft = \"0\"; \n\n document.getElementById(\"mySidebar\").style.width = \"0 !important\"; \n\n document.getElementById(\"openNav\").style.display = \"inline-block\"; } \nfunction Test() { \nvar item=document.getElementById(\"main\").style.marginLeft ;\n if (item == \"0\") { \n w3_open() item = document.getElementById(\"main\").style.marginLeft ;\n} else if (item == \"20%\") { w3_close() }\n" }, { "answer_id": 74501253, "author": "pzutils", "author_id": 13812770, "author_profile": "https://Stackoverflow.com/users/13812770", "pm_score": 1, "selected": false, "text": "item \"0%\" \"\" var item = document.getElementById(\"main\").style.marginLeft =\"\";\n var item = document.getElementById(\"main\").style.marginLeft == = item = \"0%\" item == \"0%\" w3_open() w3_close() open() close()" }, { "answer_id": 74501254, "author": "anurag-dhamala", "author_id": 14917277, "author_profile": "https://Stackoverflow.com/users/14917277", "pm_score": 1, "selected": false, "text": "function open() {\n \n document.getElementById(\"main\").style.marginLeft = \"20%\";\n document.getElementById(\"mySidebar\").style.width = \"20%\";\n document.getElementById(\"mySidebar\").style.display = \"block\";\n }\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\";\n document.getElementById(\"mySidebar\").style.display = \"none\";\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft;\n if (item == \"0%\"){\n open()\n } else if (item == \"20%\"){ \n close()\n }\n}\n" }, { "answer_id": 74501691, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 3, "selected": true, "text": "marginLeft open() close() Test() function open() {\n document.getElementById(\"main\").style.marginLeft = \"20%\"\n document.getElementById(\"mySidebar\").style.width = \"20%\"\n document.getElementById(\"mySidebar\").style.display = \"block\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction close() {\n document.getElementById(\"main\").style.marginLeft = \"0%\"\n document.getElementById(\"mySidebar\").style.display = \"none\"\n document.getElementById(\"openNav\").style.display = \"inline-block\"\n}\n\nfunction Test() {\n var item = document.getElementById(\"main\").style.marginLeft\n\n // simplified condition\n if (item == \"20%\") close()\n else open()\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4833705/" ]
74,501,204
<p>I have used the below logic, but getting an exception &quot;java.lang.StringIndexOutOfBoundsException&quot;. Help will be appreciated. Thank you!!</p> <pre><code>import java.util.Scanner; public class Demo{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(&quot;Enter a number:- &quot;); String number = sc.next(); for (int i = number.length(); i &gt;= 0; i--) { System.out.println(number.charAt(i)); } } } </code></pre>
[ { "answer_id": 74501336, "author": "Mitesh Bhimjiyaani", "author_id": 20548630, "author_profile": "https://Stackoverflow.com/users/20548630", "pm_score": 0, "selected": false, "text": "import java.util.Scanner;\npublic class Demo{\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.print(\"Enter a number:- \");\n String number = sc.next(); \n\n for (int i = number.length() -1 ; i >= 0; i--) { // correct answer: number.lenght() -1 as array start with 0.\n System.out.print(number.charAt(i)); //using print instead of println so that it display in same line\n }\n\n }\n\n}\n" }, { "answer_id": 74501870, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 1, "selected": false, "text": "Scanner sc = new Scanner(System.in);\nSystem.out.print(\"Enter a number:- \");\nchar[] chars = sc.next().toCharArray();\nint len = chars.length;\nfor (int i = 0; i < len/2; i++) {\n char c1 = chars[i];\n char c2 = chars[len-i-1];\n chars[i] = c2;\n chars[len-i-1] = c1;\n}\nString s = new String(chars);\nSystem.out.println(s);\n reverse()" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15314104/" ]
74,501,221
<p>My question is : How do I find all the running processes that end with &quot;sh&quot;. I know that &quot;ps aux&quot; lists all the processes that are running and also &quot;grep&quot; prints a specific named process which is written inside &quot; &quot;. I know I have to combine the command &quot;ps aux&quot; and also &quot;grep&quot; with a wildcard.</p> <p>My solution is ps aux | grep &quot;*sh&quot; but it does not run properly. How could it be solved?</p>
[ { "answer_id": 74501336, "author": "Mitesh Bhimjiyaani", "author_id": 20548630, "author_profile": "https://Stackoverflow.com/users/20548630", "pm_score": 0, "selected": false, "text": "import java.util.Scanner;\npublic class Demo{\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.print(\"Enter a number:- \");\n String number = sc.next(); \n\n for (int i = number.length() -1 ; i >= 0; i--) { // correct answer: number.lenght() -1 as array start with 0.\n System.out.print(number.charAt(i)); //using print instead of println so that it display in same line\n }\n\n }\n\n}\n" }, { "answer_id": 74501870, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 1, "selected": false, "text": "Scanner sc = new Scanner(System.in);\nSystem.out.print(\"Enter a number:- \");\nchar[] chars = sc.next().toCharArray();\nint len = chars.length;\nfor (int i = 0; i < len/2; i++) {\n char c1 = chars[i];\n char c2 = chars[len-i-1];\n chars[i] = c2;\n chars[len-i-1] = c1;\n}\nString s = new String(chars);\nSystem.out.println(s);\n reverse()" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19086573/" ]
74,501,242
<p>I’m completly beginer in a web development. Currently, I’m learning a basic stuff but I have a huge issue with a procces of adding pictures in code.</p> <p>I watched many tutorials on youtube and I try basicaly everything (img src=NAME OF THE PICTURE + jpg/png) (img src=URL LING FROM THE GOOGLE) and many other things but unfortuntely I didn’t found proper solution. I will be realy greatfull if there’s someone who can give me a good advice so I can solve my issue</p> <p>P.S sorry if I made some gramar mistakes, I’m not native English speaker</p> <p>Thanks</p> <pre><code>type here </code></pre>
[ { "answer_id": 74501260, "author": "Liam-Nothing", "author_id": 17254553, "author_profile": "https://Stackoverflow.com/users/17254553", "pm_score": 1, "selected": false, "text": "<img src=\"https://nothingelse.fr/img/new_logo_ne.png\" />\n" }, { "answer_id": 74501353, "author": "CerenG", "author_id": 8943514, "author_profile": "https://Stackoverflow.com/users/8943514", "pm_score": 0, "selected": false, "text": " <img src=\"https://cdn.vox-cdn.com/thumbor/tZLxhLAWoEFRpf0pe-CirjvF0XY=/1400x788/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/15788040/20150428-cloud-computing.0.1489222360.jpg\" /> \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548559/" ]
74,501,243
<p>I'm using a REST API from RapidApi, and I succeded in printing the whole response, but I need only some specific parameters. Like, to print only the Deprature and Arrival times. When using params:{} it doesn't help, because that prints every parameter with the specified argument. I need the inverse, to print a specific parameter with more arguments.</p> <pre><code>import requests url = &quot;https://timetable-lookup.p.rapidapi.com/TimeTable/LHR/BCN/20221119/&quot; headers = { &quot;X-RapidAPI-Key&quot;: &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;, &quot;X-RapidAPI-Host&quot;: &quot;timetable-lookup.p.rapidapi.com&quot; } response = requests.request(&quot;GET&quot;,url,headers=headers, params=querystring) print(response.text) </code></pre> <p>The API response is the following:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;OTA_AirDetailsRS PrimaryLangID=&quot;eng&quot; Version=&quot;1.0&quot; TransactionIdentifier=&quot;&quot; FLSNote=&quot;This XML adds attributes not in the OTA XML spec. All such attributes start with FLS&quot; FLSDevice=&quot;ota-xml-expanded&quot; xmlns=&quot;http://www.opentravel.org/OTA/2003/05&quot;&gt; &lt;Success/&gt; &lt;FLSResponseFields FLSOriginCode=&quot;LHR&quot; FLSOriginName=&quot;Heathrow Airport&quot; FLSDestinationCode=&quot;BCN&quot; FLSDestinationName=&quot;Barcelona Airport&quot; FLSStartDate=&quot;2022-11-19&quot; FLSEndDate=&quot;2022-11-19&quot; FLSResultCount=&quot;5&quot; FLSRoutesFound=&quot;124&quot; FLSBranchCount=&quot;1457&quot; FLSTargetCount=&quot;1112&quot; FLSRecordCount=&quot;785252&quot;/&gt; &lt;FlightDetails TotalFlightTime=&quot;PT2H05M&quot; TotalMiles=&quot;714&quot; TotalTripTime=&quot;PT2H05M&quot; FLSDepartureDateTime=&quot;2022-11-19T06:05:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; FLSDepartureCode=&quot;LHR&quot; FLSDepartureName=&quot;Heathrow Airport&quot; FLSArrivalDateTime=&quot;2022-11-19T09:10:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FLSArrivalCode=&quot;BCN&quot; FLSArrivalName=&quot;Barcelona Airport&quot; FLSFlightType=&quot;NonStop&quot; FLSFlightLegs=&quot;1&quot; FLSFlightDays=&quot;.....6.&quot; FLSDayIndicator=&quot;&quot;&gt; &lt;FlightLegDetails DepartureDateTime=&quot;2022-11-19T06:05:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; ArrivalDateTime=&quot;2022-11-19T09:10:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FlightNumber=&quot;472&quot; JourneyDuration=&quot;PT2H05M&quot; SequenceNumber=&quot;1&quot; LegDistance=&quot;714&quot; FLSMeals=&quot;G&quot; FLSInflightServices=&quot; &quot; FLSUUID=&quot;LHRBCN20221119BA472&quot;&gt; &lt;DepartureAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;LHR&quot; FLSLocationName=&quot;Heathrow Airport&quot; Terminal=&quot;5&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;ArrivalAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;BCN&quot; FLSLocationName=&quot;Barcelona Airport&quot; Terminal=&quot;1&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;MarketingAirline Code=&quot;BA&quot; CodeContext=&quot;IATA&quot; CompanyShortName=&quot;British Airways&quot;/&gt; &lt;Equipment AirEquipType=&quot;32N&quot;/&gt; &lt;/FlightLegDetails&gt; &lt;/FlightDetails&gt; &lt;FlightDetails TotalFlightTime=&quot;PT2H05M&quot; TotalMiles=&quot;714&quot; TotalTripTime=&quot;PT2H05M&quot; FLSDepartureDateTime=&quot;2022-11-19T07:25:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; FLSDepartureCode=&quot;LHR&quot; FLSDepartureName=&quot;Heathrow Airport&quot; FLSArrivalDateTime=&quot;2022-11-19T10:30:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FLSArrivalCode=&quot;BCN&quot; FLSArrivalName=&quot;Barcelona Airport&quot; FLSFlightType=&quot;NonStop&quot; FLSFlightLegs=&quot;1&quot; FLSFlightDays=&quot;.....6.&quot; FLSDayIndicator=&quot;&quot;&gt; &lt;FlightLegDetails DepartureDateTime=&quot;2022-11-19T07:25:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; ArrivalDateTime=&quot;2022-11-19T10:30:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FlightNumber=&quot;478&quot; JourneyDuration=&quot;PT2H05M&quot; SequenceNumber=&quot;1&quot; LegDistance=&quot;714&quot; FLSMeals=&quot;G&quot; FLSInflightServices=&quot; &quot; FLSUUID=&quot;LHRBCN20221119BA478&quot;&gt; &lt;DepartureAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;LHR&quot; FLSLocationName=&quot;Heathrow Airport&quot; Terminal=&quot;5&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;ArrivalAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;BCN&quot; FLSLocationName=&quot;Barcelona Airport&quot; Terminal=&quot;1&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;MarketingAirline Code=&quot;BA&quot; CodeContext=&quot;IATA&quot; CompanyShortName=&quot;British Airways&quot;/&gt; &lt;Equipment AirEquipType=&quot;320&quot;/&gt; &lt;/FlightLegDetails&gt; &lt;/FlightDetails&gt; &lt;FlightDetails TotalFlightTime=&quot;PT2H05M&quot; TotalMiles=&quot;714&quot; TotalTripTime=&quot;PT2H05M&quot; FLSDepartureDateTime=&quot;2022-11-19T10:25:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; FLSDepartureCode=&quot;LHR&quot; FLSDepartureName=&quot;Heathrow Airport&quot; FLSArrivalDateTime=&quot;2022-11-19T13:30:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FLSArrivalCode=&quot;BCN&quot; FLSArrivalName=&quot;Barcelona Airport&quot; FLSFlightType=&quot;NonStop&quot; FLSFlightLegs=&quot;1&quot; FLSFlightDays=&quot;.....6.&quot; FLSDayIndicator=&quot;&quot;&gt; &lt;FlightLegDetails DepartureDateTime=&quot;2022-11-19T10:25:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; ArrivalDateTime=&quot;2022-11-19T13:30:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FlightNumber=&quot;474&quot; JourneyDuration=&quot;PT2H05M&quot; SequenceNumber=&quot;1&quot; LegDistance=&quot;714&quot; FLSMeals=&quot;G&quot; FLSInflightServices=&quot; &quot; FLSUUID=&quot;LHRBCN20221119BA474&quot;&gt; &lt;DepartureAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;LHR&quot; FLSLocationName=&quot;Heathrow Airport&quot; Terminal=&quot;5&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;ArrivalAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;BCN&quot; FLSLocationName=&quot;Barcelona Airport&quot; Terminal=&quot;1&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;MarketingAirline Code=&quot;BA&quot; CodeContext=&quot;IATA&quot; CompanyShortName=&quot;British Airways&quot;/&gt; &lt;Equipment AirEquipType=&quot;32N&quot;/&gt; &lt;/FlightLegDetails&gt; &lt;/FlightDetails&gt; &lt;FlightDetails TotalFlightTime=&quot;PT2H05M&quot; TotalMiles=&quot;714&quot; TotalTripTime=&quot;PT2H05M&quot; FLSDepartureDateTime=&quot;2022-11-19T13:15:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; FLSDepartureCode=&quot;LHR&quot; FLSDepartureName=&quot;Heathrow Airport&quot; FLSArrivalDateTime=&quot;2022-11-19T16:20:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FLSArrivalCode=&quot;BCN&quot; FLSArrivalName=&quot;Barcelona Airport&quot; FLSFlightType=&quot;NonStop&quot; FLSFlightLegs=&quot;1&quot; FLSFlightDays=&quot;.....6.&quot; FLSDayIndicator=&quot;&quot;&gt; &lt;FlightLegDetails DepartureDateTime=&quot;2022-11-19T13:15:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; ArrivalDateTime=&quot;2022-11-19T16:20:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FlightNumber=&quot;480&quot; JourneyDuration=&quot;PT2H05M&quot; SequenceNumber=&quot;1&quot; LegDistance=&quot;714&quot; FLSMeals=&quot;G&quot; FLSInflightServices=&quot; &quot; FLSUUID=&quot;LHRBCN20221119BA480&quot;&gt; &lt;DepartureAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;LHR&quot; FLSLocationName=&quot;Heathrow Airport&quot; Terminal=&quot;5&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;ArrivalAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;BCN&quot; FLSLocationName=&quot;Barcelona Airport&quot; Terminal=&quot;1&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;MarketingAirline Code=&quot;BA&quot; CodeContext=&quot;IATA&quot; CompanyShortName=&quot;British Airways&quot;/&gt; &lt;Equipment AirEquipType=&quot;320&quot;/&gt; &lt;/FlightLegDetails&gt; &lt;/FlightDetails&gt; &lt;FlightDetails TotalFlightTime=&quot;PT2H05M&quot; TotalMiles=&quot;714&quot; TotalTripTime=&quot;PT2H05M&quot; FLSDepartureDateTime=&quot;2022-11-19T19:20:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; FLSDepartureCode=&quot;LHR&quot; FLSDepartureName=&quot;Heathrow Airport&quot; FLSArrivalDateTime=&quot;2022-11-19T22:25:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FLSArrivalCode=&quot;BCN&quot; FLSArrivalName=&quot;Barcelona Airport&quot; FLSFlightType=&quot;NonStop&quot; FLSFlightLegs=&quot;1&quot; FLSFlightDays=&quot;.....6.&quot; FLSDayIndicator=&quot;&quot;&gt; &lt;FlightLegDetails DepartureDateTime=&quot;2022-11-19T19:20:00&quot; FLSDepartureTimeOffset=&quot;+0000&quot; ArrivalDateTime=&quot;2022-11-19T22:25:00&quot; FLSArrivalTimeOffset=&quot;+0100&quot; FlightNumber=&quot;482&quot; JourneyDuration=&quot;PT2H05M&quot; SequenceNumber=&quot;1&quot; LegDistance=&quot;714&quot; FLSMeals=&quot;G&quot; FLSInflightServices=&quot; &quot; FLSUUID=&quot;LHRBCN20221119BA482&quot;&gt; &lt;DepartureAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;LHR&quot; FLSLocationName=&quot;Heathrow Airport&quot; Terminal=&quot;5&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;ArrivalAirport CodeContext=&quot;IATA&quot; LocationCode=&quot;BCN&quot; FLSLocationName=&quot;Barcelona Airport&quot; Terminal=&quot;1&quot; FLSDayIndicator=&quot;&quot;/&gt; &lt;MarketingAirline Code=&quot;BA&quot; CodeContext=&quot;IATA&quot; CompanyShortName=&quot;British Airways&quot;/&gt; &lt;Equipment AirEquipType=&quot;32N&quot;/&gt; &lt;/FlightLegDetails&gt; &lt;/FlightDetails&gt; &lt;/OTA_AirDetailsRS&gt; </code></pre> <p>How can I write the code to display only the <em>DepartureDateTime</em> , <em>ArrivalDateTime</em>, and <em>LocationCode</em> for the arrival and destination country?</p> <p>Thank you!</p>
[ { "answer_id": 74501331, "author": "Kieran", "author_id": 20534032, "author_profile": "https://Stackoverflow.com/users/20534032", "pm_score": 1, "selected": false, "text": "xml.etree.ElementTree # create element tree object\ntree = ET.parse(xmlfile)\n \n# get root element\nroot = tree.getroot()\n" }, { "answer_id": 74524275, "author": "vivi25-5", "author_id": 13540021, "author_profile": "https://Stackoverflow.com/users/13540021", "pm_score": 1, "selected": true, "text": "soup = BeautifulSoup(response.content, 'html.parser')\nfor i in range(5):\n print (\"Arrivals: \",soup.findAll(\"flightlegdetails\")[i][\"arrivaldatetime\"])\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13540021/" ]
74,501,298
<p>I use a coroutine to add another coroutine to the event loop multiple times but partway through I cancel the first coroutine. I thought this would mean that any coroutines already added to the event loop would complete successfully and no more would be added, however I find that coroutines that have already been added to the event loop also seem to be cancelled.</p> <p>I'm running this script in Spyder so I don't need to call run_until_complete, etc. because the event loop is already running in the background on my environment.</p> <p>I'm sure I'm missing something and the code is behaving exactly as it should - but I can't figure out why. I would also like to know how I might allow cancellation of runTimes but still let slowPrinter complete.</p> <p>Thank you!</p> <p>Code below</p> <pre><code>import asyncio loop = asyncio.get_event_loop() async def runTimes(async_func, times): for i in range(0, times): task = loop.create_task(async_func()) await task async def slowPrinter(): await asyncio.sleep(2) print(&quot;slowPrinter done&quot;) async def doStuff(): for i in range(0, 10): await(asyncio.sleep(1)) print(&quot;doStuff done&quot;) async def doLater(delay_ms, method, *args, **kwargs): try: print(&quot;doLater &quot; + str(delay_ms) + &quot; &quot; + str(method.__name__)) except AttributeError: print(&quot;doLater &quot; + str(delay_ms)) await asyncio.sleep(delay_ms/1000) method(*args, **kwargs) print(&quot;doLater complete&quot;) task = loop.create_task(runTimes(slowPrinter, 3)) loop.create_task(doLater(3000, task.cancel)) loop.create_task(doStuff()) </code></pre> <p>Output</p> <pre><code>doLater 3000 cancel slowPrinter done doLater complete doStuff done </code></pre> <p>Expected Output</p> <pre><code>doLater 3000 cancel slowPrinter done doLater complete **slowPrinter done** doStuff done </code></pre> <p>Edit: Part of the reason I have built the code without using things like run_later is because I need to port the code to micropython later so I am sticking to functions I can use on micropython.</p> <p>Edit2: Interestingly, task cancellation seems to propagate to tasks created from within the coroutine as well!</p> <pre><code>async def runTimes(async_func, times): for i in range(0, times): task = loop.create_task(async_func()) try: await task except asyncio.CancelledError: print(&quot;cancelled as well&quot;) </code></pre> <p>Output</p> <pre><code>doLater 3000 cancel slowPrinter done doLater complete cancelled as well slowPrinter done doStuff done </code></pre>
[ { "answer_id": 74501331, "author": "Kieran", "author_id": 20534032, "author_profile": "https://Stackoverflow.com/users/20534032", "pm_score": 1, "selected": false, "text": "xml.etree.ElementTree # create element tree object\ntree = ET.parse(xmlfile)\n \n# get root element\nroot = tree.getroot()\n" }, { "answer_id": 74524275, "author": "vivi25-5", "author_id": 13540021, "author_profile": "https://Stackoverflow.com/users/13540021", "pm_score": 1, "selected": true, "text": "soup = BeautifulSoup(response.content, 'html.parser')\nfor i in range(5):\n print (\"Arrivals: \",soup.findAll(\"flightlegdetails\")[i][\"arrivaldatetime\"])\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4384768/" ]
74,501,300
<p>I am facing one problem when I want to filter an array inside an array by an array. Please see the example-</p> <pre><code>const array1 = [ { name: &quot;this is name1&quot;, products: [ { id: &quot;4&quot; }, { id: &quot;2&quot; }, ] }, { name: &quot;this is name2&quot;, products: [ { id: &quot;2&quot; }, { id: &quot;1&quot; } ] } ] const array2 = [ { id: &quot;1&quot;, refund: true }, { id: &quot;2&quot;, refund: false }, { id: &quot;3&quot;, refund: true }, { id: &quot;4&quot;, refund: false} ] </code></pre> <p>Here I have to filter <code>array1</code> products field. Here in <code>array1</code> products filed an array with of id. I have to filter this products field by searching same object from array2 by id and then filter when refund is true.</p> <p>From the example I need result by this-</p> <pre><code>const array1 = [ { name: &quot;this is name2&quot;, products: [ { id: &quot;1&quot; } ] } ] </code></pre> <p>Here in result we can see only one object in this array. Because from <code>array1</code>, in the object's product filed have two id <code>4</code> and <code>2</code>. From <code>array2</code> we can see refund <code>false</code> for both id <code>4</code> and <code>2</code>. That's why <code>array1</code> remove first object.</p> <p>In the second object we can see products field contain two id <code>2</code> and <code>1</code>. From <code>array2</code> we can see refund is <code>false</code> for id <code>2</code> but refund is <code>true</code> for id <code>1</code>. Hence for id <code>1</code> refund is <code>true</code> that's why it stay in products array.</p> <p>Please help me. I hope I can clear my questions.</p>
[ { "answer_id": 74501371, "author": "vighnesh153", "author_id": 8822610, "author_profile": "https://Stackoverflow.com/users/8822610", "pm_score": 2, "selected": false, "text": "filter map reduce const array1 = [\n {\n name: 'this is name1',\n products: [{ id: '4' }, { id: '2' }],\n },\n {\n name: 'this is name2',\n products: [{ id: '2' }, { id: '1' }],\n },\n];\n\nconst array2 = [\n { id: '1', refund: true },\n { id: '2', refund: false },\n { id: '3', refund: true },\n { id: '4', refund: false },\n];\n\n// Transforms array2 to { 1: { id: 1, refund: true }, 2: ...} \nconst array2ToMap = array2.reduce((map, item) => {\n map[item.id] = item\n return map\n}, new Map());\n\nconst result = array1\n .map(item => {\n // Filters only the products that have refund as `true`\n const filteredProducts = item.products.filter(\n product => array2ToMap[product.id]?.refund\n );\n return { ...item, products: filteredProducts };\n })\n // Only select items which have at least 1 filtered products\n .filter(item => item.products.length > 0);\n\nconsole.log(result);" }, { "answer_id": 74501539, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const array1 = [{\"name\":\"this is name1\",\"products\":[{\"id\":\"4\"},{\"id\":\"2\"}]},{\"name\":\"this is name2\",\"products\":[{\"id\":\"2\"},{\"id\":\"1\"}]}];\nconst array2 = [{\"id\":\"1\",\"refund\":true},{\"id\":\"2\",\"refund\":false},{\"id\":\"3\",\"refund\":true},{\"id\":\"4\",\"refund\":false}];\n\nconst refundIds = array2.filter(i=>i.refund).map(i=>i.id);\nconst intersect = (a,b) => a.some(i=>b.includes(i));\n\nconsole.log(array1.filter(e=>\n intersect(refundIds, e.products.map(i=>i.id)))\n .map(({products, ...a})=>({...a,\n products: products.filter(i=>refundIds.includes(i.id))\n }))\n);" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19698958/" ]
74,501,391
<p>I wrote simple server running script on node.js</p> <pre><code>const http = require('http') let requestsCount = 0 const server = http.createServer((request, response) =&gt; { requestsCount++ response.write(`Leo Garsia ${requestsCount}`) }) server.listen(3005, () =&gt; { console.info('Server is Running on port 3005') }) </code></pre> <p>When in the browser I typed 'localhost:3005', it works a long time, before display first result. (about 10 minutes) Why does it huppens?</p> <p>And then when I refresh browser it requestsCount increments twice. And displays the result like 2,4,6, and so on. Very interesting why?</p>
[ { "answer_id": 74501623, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 2, "selected": true, "text": "response.end() response.write" }, { "answer_id": 74501826, "author": "Leo Garsia", "author_id": 14569267, "author_profile": "https://Stackoverflow.com/users/14569267", "pm_score": 0, "selected": false, "text": "const express = require('express')\n\nconst app=express();\nlet requestsCount = 0\napp.listen(3005, () =>{\n console.log('Server is running on port 3005...')\n})\n\napp.get('/leo', (request, response)=>{\n requestsCount++\n response.write(`Request URL is, ${request.url} count is, ${requestsCount}`)\n response.end()\n console.info(`Request URL is, ${request.url} count is, ${requestsCount}`)\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569267/" ]
74,501,396
<p>When testing my react native app (with expo) through the expo go IOS app the icons are not vertically centered, however when testing on web they are vertically centered. I have tried giving each icon a parent div and centering it vertically, giving it a TabBarIconStyle of textAlignVertical: center, and textAlign: center, everything I can think of to vertically align these icons.</p> <p>My Navigator:</p> <pre class="lang-js prettyprint-override"><code>&lt;TabNav.Navigator screenOptions={TabNavOptions}&gt; &lt;TabNav.Screen name=&quot;Home&quot; component={HomeScreen} options={{ tabBarIconStyle: { textAlignVertical: &quot;center&quot;, textAlign: &quot;center&quot; }, tabBarIcon: ({ color, size }) =&gt; ( &lt;View style={{}}&gt; &lt;Ionicons name=&quot;home&quot; color={color} size={size} style={{ textAlignVertical: &quot;center&quot; }} /&gt; &lt;/View&gt; ), }} /&gt; &lt;TabNav.Screen name=&quot;Workouts&quot; component={HomeScreen} options={{ tabBarIcon: ({ color, size }) =&gt; &lt;Ionicons name=&quot;barbell&quot; color={color} size={size} /&gt; }} /&gt; &lt;TabNav.Screen name=&quot;Exercises&quot; component={HomeScreen} options={{ tabBarIcon: ({ color, size }) =&gt; &lt;Ionicons name=&quot;bicycle&quot; color={color} size={size} /&gt; }} /&gt; &lt;/TabNav.Navigator&gt; </code></pre> <p>My screen options for the Navigator:</p> <pre class="lang-js prettyprint-override"><code>const TabNavOptions: BottomTabNavigationOptions = { tabBarShowLabel: false, tabBarActiveTintColor: &quot;#4B7079&quot;, tabBarInactiveTintColor: &quot;#FFFFFF&quot;, tabBarStyle: { width: &quot;90%&quot;, height: 60, position: &quot;absolute&quot;, left: &quot;5%&quot;, bottom: 30, borderRadius: 100, borderTopWidth: 0, backgroundColor: &quot;#75B1BC&quot; }, }; </code></pre> <p>This is what it looks like on web (and what it should look like)</p> <p><a href="https://i.stack.imgur.com/UDFW4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UDFW4.png" alt="enter image description here" /></a></p> <p>This is what it looks like on expo go</p> <p><a href="https://i.stack.imgur.com/Mq1WK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mq1WK.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74501623, "author": "Heiko Theißen", "author_id": 16462950, "author_profile": "https://Stackoverflow.com/users/16462950", "pm_score": 2, "selected": true, "text": "response.end() response.write" }, { "answer_id": 74501826, "author": "Leo Garsia", "author_id": 14569267, "author_profile": "https://Stackoverflow.com/users/14569267", "pm_score": 0, "selected": false, "text": "const express = require('express')\n\nconst app=express();\nlet requestsCount = 0\napp.listen(3005, () =>{\n console.log('Server is running on port 3005...')\n})\n\napp.get('/leo', (request, response)=>{\n requestsCount++\n response.write(`Request URL is, ${request.url} count is, ${requestsCount}`)\n response.end()\n console.info(`Request URL is, ${request.url} count is, ${requestsCount}`)\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8388264/" ]
74,501,437
<p>The definition of hasNext() is &quot;Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.&quot;</p> <p>When I put <strong>standardInput.hasNext()</strong> in for-loop, the program runs toward infinity. But if i Put it in while-loop it does not run to infinity. Where is the differenc between these two programs and why one of them work and another not?</p> <p>for-loop:</p> <pre><code> import java.util.Scanner; public class Vocabulary { public static void main(String[] args) { Scanner standardInput = new Scanner(System.in); for(int i = 0; standardInput.hasNext(); i++){ System.out.print(i); } } } </code></pre> <p>while-loop:</p> <pre><code> import java.util.Scanner; public class Sum { public static void main(String[] args) { Scanner standardInput = new Scanner(System.in); double sum = 0; while(standardInput.hasNext()) { double nextNumber = standardInput.nextDouble(); sum += nextNumber; } System.out.println(&quot;The Sum is &quot; + sum + &quot;.&quot;); } } </code></pre> <p>I read the definition, but still cannot understand why one program works but another not</p>
[ { "answer_id": 74501477, "author": "Code-Apprentice", "author_id": 1440565, "author_profile": "https://Stackoverflow.com/users/1440565", "pm_score": 2, "selected": false, "text": "standardInput.nextDouble() standardInput.hasNext() hasNext()" }, { "answer_id": 74501482, "author": "oleg.cherednik", "author_id": 3461397, "author_profile": "https://Stackoverflow.com/users/3461397", "pm_score": 2, "selected": false, "text": "for...loop standardInput while...loop for(int i = 0; standardInput.hasNext(); i++){\n String str = standardInput.next(); // add reading\n System.out.print(i);\n}\n" }, { "answer_id": 74501499, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "for(int i = 0; standardInput.hasNext(); i++){\n System.out.print(i);\n\n}\n while(standardInput.hasNext()) {\n double nextNumber = standardInput.nextDouble();\n sum += nextNumber;\n }\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472612/" ]
74,501,531
<p>I have a GlideImage that is inside a Box. Inside that Box, there is also a button with an icon. I want that, when I click on the button, the image is maximized and occupies the whole screen with a button in the lower right corner where it is possible to minimize it. I would also like to zoom in on it. Does anyone know how I can do this and if it's possible in the current state of Jetpack Compose?</p> <p>I leave you the code I have to generate the Box, with the image and the icon.</p> <p>Thanks in advance for any help.</p> <pre><code>@ExperimentalGlideComposeApi @Composable fun BuildImage(imageUrl: String) { Box( modifier = Modifier .padding(vertical = 25.dp, horizontal = 25.dp) .background( brush = Brush.linearGradient( listOf( Color.Gray, Color.White ) ), shape = RoundedCornerShape(14.dp) ) .clip(RoundedCornerShape(14.dp)) ) { GlideImage( model = imageUrl, contentDescription = null, contentScale = ContentScale.FillBounds ) Box(modifier = Modifier.matchParentSize(), contentAlignment = Alignment.BottomEnd) { IconButton( onClick = { /* TO IMPLEMENT */ }, modifier = Modifier .padding(11.dp) .background(Color.Blue, RoundedCornerShape(3.dp)) .clip(RoundedCornerShape(3.dp)) .size(52.dp) ) { Icon( painter = painterResource(id = R.drawable.maximize), contentDescription = null, tint = Color.Unspecified ) } } } } </code></pre>
[ { "answer_id": 74502590, "author": "Sky", "author_id": 9846834, "author_profile": "https://Stackoverflow.com/users/9846834", "pm_score": 1, "selected": false, "text": "@OptIn(ExperimentalGlideComposeApi::class)\n@Composable\nfun Q74501531() {\n val configuration = LocalConfiguration.current\n val screenWidth = configuration.screenWidthDp.dp // Get screen width as dp from local configuration\n val screenHeight = configuration.screenHeight.dp // You can also get screen height but for demo it's unused\n\n Column(\n modifier = Modifier.fillMaxSize()\n ) {\n var isExpanded by remember { mutableStateOf(false) } // Trigger state for change width and height\n val width by animateDpAsState(if (isExpanded) screenWidth else screenWidth / 3)\n val height by animateDpAsState(if (isExpanded) screenWidth / 2 else screenWidth / 5)\n\n GlideImage(\n modifier = Modifier.size(width, height),\n model = \"https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg\",\n contentDescription = null,\n contentScale = ContentScale.Crop\n )\n\n Spacer(Modifier.weight(1f))\n\n TextButton(\n modifier = Modifier\n .fillMaxWidth()\n .padding(horizontal = 8.dp),\n onClick = { isExpanded = !isExpanded }\n ) {\n Text(\"Toggle\")\n }\n }\n}\n" }, { "answer_id": 74521191, "author": "R0ck", "author_id": 18215416, "author_profile": "https://Stackoverflow.com/users/18215416", "pm_score": 3, "selected": true, "text": "Dialog(\n properties = DialogProperties(usePlatformDefaultWidth = false),\n onDismissRequest = { /* implement */ }\n) {\n Box(modifier = Modifier.fillMaxSize()) {\n ZoomableImage(imageUrl)\n }\n}\n\n@ExperimentalGlideComposeApi\n@Composable\nfun ZoomableImage(model: Any, contentDescription: String? = null) {\n val angle by remember { mutableStateOf(0f) }\n var zoom by remember { mutableStateOf(1f) }\n var offsetX by remember { mutableStateOf(0f) }\n var offsetY by remember { mutableStateOf(0f) }\n\n val configuration = LocalConfiguration.current\n val screenWidth = configuration.screenWidthDp.dp.value\n val screenHeight = configuration.screenHeightDp.dp.value\n\n GlideImage(\n model,\n contentDescription = contentDescription,\n contentScale = ContentScale.Fit,\n modifier = Modifier\n .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }\n .graphicsLayer(\n scaleX = zoom,\n scaleY = zoom,\n rotationZ = angle\n )\n .pointerInput(Unit) {\n detectTransformGestures(\n onGesture = { _, pan, gestureZoom, _ ->\n zoom = (zoom * gestureZoom).coerceIn(1F..4F)\n if (zoom > 1) {\n val x = (pan.x * zoom)\n val y = (pan.y * zoom)\n val angleRad = angle * PI / 180.0\n\n offsetX =\n (offsetX + (x * cos(angleRad) - y * sin(angleRad)).toFloat()).coerceIn(\n -(screenWidth * zoom)..(screenWidth * zoom)\n )\n offsetY =\n (offsetY + (x * sin(angleRad) + y * cos(angleRad)).toFloat()).coerceIn(\n -(screenHeight * zoom)..(screenHeight * zoom)\n )\n } else {\n offsetX = 0F\n offsetY = 0F\n }\n }\n )\n }\n .fillMaxSize()\n )\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18215416/" ]
74,501,545
<p>I want to know why am i getting an error when i delete temp in this function.</p> <p>`</p> <pre><code>#include&lt;iostream&gt; using namespace std; //NODE FOR LINKED LIST class node { public: int data; node* next; node(int val) { data = val; next = NULL; } ~node() { delete next; } }; //Linked List class LinkedList { node* head; public: LinkedList() { head = NULL; } //checking if head is Null or not void insertAtEnd(int val) { if (head == NULL) { head = new node(val); return; } node* temp = head; while (temp-&gt;next != NULL) temp = temp-&gt;next; temp-&gt;next = new node(val); //delete temp; //Now if i use this delete temp my loop in display function breaks and runs indefinitely } void display() { cout &lt;&lt; &quot;Your List : &quot;; node* temp = head; while (temp != NULL) { cout &lt;&lt; temp-&gt;data &lt;&lt; &quot;&gt;&quot;; temp = temp-&gt;next; } cout &lt;&lt; endl; delete temp; } }; int main() { LinkedList obj; //sample tests obj.insertAtEnd(10); obj.insertAtEnd(20); obj.insertAtEnd(30); obj.insertAtEnd(40); obj.display(); system(&quot;pause&quot;); return 0; } </code></pre> <p>`</p> <p>I tried commenting this delete out and it worked but its been leaking memory a simple solution i thought was to make a *temp in constructor then deleteing it in destruction assigning NULL in every function that needs it.</p>
[ { "answer_id": 74501646, "author": "Doc Brown", "author_id": 220984, "author_profile": "https://Stackoverflow.com/users/220984", "pm_score": 2, "selected": false, "text": "LinkedList temp insertAtEnd display temp temp next LinkedList head node delete s destructor and let " }, { "answer_id": 74501674, "author": "Gianni Crivello", "author_id": 14161394, "author_profile": "https://Stackoverflow.com/users/14161394", "pm_score": 1, "selected": false, "text": "LinkedList nodes LinkedList node node LinkedList ~LinkedList() {\n node* deleter_node = nullptr; //pointer to current node (node we want to delete)\n deleter_node = head; //deleter points to the head of your list\n\n while (deleter_node != nullptr) { //traverse list and delete nodes\n node* temp = nullptr;\n temp = deleter_node -> next; //temp ensures we \n //don't loose the pointer to the next node\n\n delete deleter_node; //delete current node\n deleter_node = temp; \n }\n}\n\n LinkedList node class LinkedList {\n Node* head;\npublic:\n struct Node { //node is now a public member struct\n int data = 0;\n Node* next = nullptr;\n };\n\n LinkedList() { //default constructor\n head = nullptr;\n }\n ~LinkedList() { //destructor handles memory management\n Node* deleter_node = nullptr;\n deleter_node = head;\n while (deleter_node != nullptr) {\n Node* temp = nullptr;\n temp = deleter_node -> next;\n delete deleter_node;\n deleter_node = temp;\n }\n };\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15266522/" ]
74,501,622
<p>I am trying to apply the function on multiple data frames. I created a list for the data frames. If the ranking is less than 100, high performance column would be assigned values copied over from the ranking column and if the ranking is between 100 and 200, the average column would be assigned the values copied over from the ranking column. If the ranking is between 200 and 300, the lower performance column gets assigned values copied from the ranking column. I do not get any error messages when I run the script but the function does not get applied to the data frames. Any suggestions would be helpful.</p> <pre><code> for file in tests: #tests would be a list of data frame def func (file): if (file['ranking']) &lt; 100: (file['ranking']) == (file['High Performance']) elif (file['ranking']) &gt; 100 &amp; (file['ranking'] &lt; 200): (file['ranking'])== (file['Average']) elif (file ['ranking']) &gt; 200&amp; (file['ranking'] &lt; 300): (file['ranking']) == (file ['Low Performance']) else: return '' file['High Performance'] = file.apply(func, axis=1) file['Average'] = file.apply(func, axis=1) file['Low Performance'] = file.apply(func, axis=1) </code></pre>
[ { "answer_id": 74501690, "author": "Harishma Ashok", "author_id": 20403698, "author_profile": "https://Stackoverflow.com/users/20403698", "pm_score": 2, "selected": true, "text": "def func (file):\n if (file['ranking']) < 100:\n (file['ranking']) == (file['High Performance'])\n elif (file['ranking']) > 100 & (file['ranking'] < 200):\n (file['ranking'])== (file['Average'])\n elif (file ['ranking']) > 200& (file['ranking'] < 300):\n (file['ranking']) == (file ['Low Performance'])\n else: \n return ''\n \nfor file in tests: #tests would be a list of data frame\n file['High Performance'] = file.apply(func, axis=1)\n file['Average'] = file.apply(functionss, axis=1)\n file['Low Performance'] = file.apply(functionss, axis=1)\n" }, { "answer_id": 74502225, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "apply import numpy as np\nimport pandas as pd\n\ndef func(file):\n result = file['ranking'].copy()\n result[:] = ''\n result.loc[mask] = file.loc[(mask := file['ranking'].lt(100)), 'High Performance']\n result.loc[mask] = file.loc[(mask := file['ranking'].between(100, 200, inclusive='left')), 'Average']\n result.loc[mask] = file.loc[(mask := file['ranking'].between(200, 300, inclusive='both')), 'Low Performance']\n return result\n\n\nprint('\\nOriginal frames:\\n')\nlst = [] # Data preparation\nfor _ in range(2): # adjust\n df = pd.DataFrame(\n {'ranking': np.random.randint(0, 400, 100), 'High Performance': np.random.randint(1000, 10000, 100),\n 'Average': np.random.randint(10000, 100000, 100), 'Low Performance': np.random.randint(100000, 1000000, 100)})\n lst.append(df)\n print(df.head(5))\n\nprint('\\nProcessed frames:\\n')\nfor i, file in enumerate(lst):\n lst[i]['ranking'] = func(file)\n print(lst[i].head(5))\n Original frames:\n\n ranking High Performance Average Low Performance\n0 340 7674 53049 893702\n1 58 6838 38181 653512\n2 313 2383 66811 794135\n3 260 3930 24911 968317\n4 377 6543 80905 599571\n ranking High Performance Average Low Performance\n0 223 6044 77461 237517\n1 250 6128 24633 112060\n2 396 3701 26695 767052\n3 261 9031 64877 415611\n4 313 1298 52726 782069\n\nProcessed frames:\n\n ranking High Performance Average Low Performance\n0 7674 53049 893702\n1 6838 6838 38181 653512\n2 2383 66811 794135\n3 968317 3930 24911 968317\n4 6543 80905 599571\n ranking High Performance Average Low Performance\n0 237517 6044 77461 237517\n1 112060 6128 24633 112060\n2 3701 26695 767052\n3 415611 9031 64877 415611\n4 1298 52726 782069\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18708380/" ]
74,501,637
<p>The data needs to be stored in this format</p> <pre><code>data = {'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'No'}], 'new user': [{'title': 'Take out trash', 'description': 'Take the trash can down the street', 'due date': '10 oct 2022', 'date assigned': '20 Oct 2022', 'status': 'No'}]} </code></pre> <p>I need to display this data like this:</p> <pre><code>user: admin title: Register Users with taskManager.py description: Use taskManager.py to add the usernames and passwords for all team members that will be using this program date assigned: 10 Oct 2019 due date: 20 Oct 2022 status: No title: Assign initial tasks description: Use taskManager.py to assign each team member with appropriate tasks date assigned: 10 Oct 2019 due date: 25 Oct 2019 status: No user: new user title: Take out trash description: Take the trash can down the street date assigned: 10 Oct 2022 due date: 20 Oct 202 status: No </code></pre> <p>How do I do this?</p>
[ { "answer_id": 74501690, "author": "Harishma Ashok", "author_id": 20403698, "author_profile": "https://Stackoverflow.com/users/20403698", "pm_score": 2, "selected": true, "text": "def func (file):\n if (file['ranking']) < 100:\n (file['ranking']) == (file['High Performance'])\n elif (file['ranking']) > 100 & (file['ranking'] < 200):\n (file['ranking'])== (file['Average'])\n elif (file ['ranking']) > 200& (file['ranking'] < 300):\n (file['ranking']) == (file ['Low Performance'])\n else: \n return ''\n \nfor file in tests: #tests would be a list of data frame\n file['High Performance'] = file.apply(func, axis=1)\n file['Average'] = file.apply(functionss, axis=1)\n file['Low Performance'] = file.apply(functionss, axis=1)\n" }, { "answer_id": 74502225, "author": "Алексей Р", "author_id": 15035314, "author_profile": "https://Stackoverflow.com/users/15035314", "pm_score": 0, "selected": false, "text": "apply import numpy as np\nimport pandas as pd\n\ndef func(file):\n result = file['ranking'].copy()\n result[:] = ''\n result.loc[mask] = file.loc[(mask := file['ranking'].lt(100)), 'High Performance']\n result.loc[mask] = file.loc[(mask := file['ranking'].between(100, 200, inclusive='left')), 'Average']\n result.loc[mask] = file.loc[(mask := file['ranking'].between(200, 300, inclusive='both')), 'Low Performance']\n return result\n\n\nprint('\\nOriginal frames:\\n')\nlst = [] # Data preparation\nfor _ in range(2): # adjust\n df = pd.DataFrame(\n {'ranking': np.random.randint(0, 400, 100), 'High Performance': np.random.randint(1000, 10000, 100),\n 'Average': np.random.randint(10000, 100000, 100), 'Low Performance': np.random.randint(100000, 1000000, 100)})\n lst.append(df)\n print(df.head(5))\n\nprint('\\nProcessed frames:\\n')\nfor i, file in enumerate(lst):\n lst[i]['ranking'] = func(file)\n print(lst[i].head(5))\n Original frames:\n\n ranking High Performance Average Low Performance\n0 340 7674 53049 893702\n1 58 6838 38181 653512\n2 313 2383 66811 794135\n3 260 3930 24911 968317\n4 377 6543 80905 599571\n ranking High Performance Average Low Performance\n0 223 6044 77461 237517\n1 250 6128 24633 112060\n2 396 3701 26695 767052\n3 261 9031 64877 415611\n4 313 1298 52726 782069\n\nProcessed frames:\n\n ranking High Performance Average Low Performance\n0 7674 53049 893702\n1 6838 6838 38181 653512\n2 2383 66811 794135\n3 968317 3930 24911 968317\n4 6543 80905 599571\n ranking High Performance Average Low Performance\n0 237517 6044 77461 237517\n1 112060 6128 24633 112060\n2 3701 26695 767052\n3 415611 9031 64877 415611\n4 1298 52726 782069\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19698970/" ]
74,501,688
<p>I'm not asking for an answer to the question, but rather how I, on my own, could have gotten the answer.</p> <h3><strong>Original Question:</strong></h3> <p><strong>Does the following code cause Python to make a new list of size (len(nums) - 1) in memory that then gets iterated over?</strong></p> <pre><code>for item in nums[1:]: # do stuff with item </code></pre> <h3>Original Answer</h3> <p>A similarish question is asked <a href="https://stackoverflow.com/questions/10079216/skip-first-entry-in-for-loop-in-python">here</a> and there is a subcomment by Srinivas Reddy Thatiparthy saying that a new sublist is created. <strong>But, there is <em>no</em> detail given about how he arrived at this answer, which I think makes it very different from what I'm looking for.</strong></p> <h3><strong>Question:</strong></h3> <p><strong>How could I have figured out on my own what the answer to my question is?</strong></p> <p><em>I've had similar questions before. For instance, I learned that if I do <code>my_function(nums[1:])</code>, I don't pass in a &quot;slice&quot; but rather a completely new, different sublist! I found this out by just testing whether the original list passed into <code>my_function</code> was modified post-function (it wasn't).</em> <strong>But I don't see an immediate way to figure out if Python is making a new sublist for the <code>for</code> loop example.</strong> Please help me to know how to do this.</p> <h4>side note</h4> <p>By the way, this is the current solution I'm using from the original stackoverflow post solutions:</p> <pre><code>for indx, item in enumerate(nums): if indx == 0: continue # do stuff w items </code></pre>
[ { "answer_id": 74501767, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "function areSameRef(thing1, thing2){\n thing1.modify()\n return thing1.equals(thing2) //make sure this is not just a referential equality check\n}\n function foo(list1, list2){\n list1.append(someElement)\n return list1.length == list2.length\n}\n function bar(list1, list2){\n list1.set(someIndex, someElement)\n return list1.get(someIndex)==list2.get(someIndex)\n}\n for i in [nums 1:] foo(5) 6 7 def foo(x : int):\n l = range(9999)\n return 5\n\ndef bar(x:int):\n l = range(9999)\n if (x + 1 != (x*2+2)/2):\n return l[x]\n else:\n return 5\n foo bar foo l bar l range list for i in nums[1:]" }, { "answer_id": 74502437, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "nums[1:] nums.__getitem__(slice(1, None)) list_subscript nums[1:] nums = [1 ,2, 3]\ntmp = nums[1:]\nfor item in tmp:\n pass\n\ntmp[0] = \"new stuff\"\n\nassert id(nums) != id(tmp), \"List slice creates a new object\"\nassert type(tmp) == type(nums), \"List slice creates a new list\"\nassert 999 not in nums, \"List slice doesn't affect original\"\n import numpy as np\n\nnums = np.array([1,2,3])\ntmp = nums[1:]\nfor item in tmp:\n pass\n\ntmp[0] = 999\n\nassert id(nums) != id(tmp), \"array slice creates a new object\"\nassert type(tmp) == type(nums), \"array slice creates a new list\"\nassert 999 not in nums, \"array slice doesn't affect original\"\n" }, { "answer_id": 74502479, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": ":= import sys\nprint(sys.version)\n\na = list(range(1000))\nfor i in (b := a[1:]):\n b[0] = 906\nprint(b is a)\nprint(a[:10])\nprint(b[:10])\nprint(sys.getsizeof(a))\nprint(sys.getsizeof(b))\n 3.11.0 (main, Nov 4 2022, 00:14:47) [GCC 7.5.0]\nFalse\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[906, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n8056\n8048\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9277931/" ]
74,501,725
<p><a href="https://i.stack.imgur.com/kqmkp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kqmkp.png" alt="enter image description here" /></a></p> <p>I want to align the switch button to Top right side (marked in the picture)</p> <p>What i did,</p> <p>I tried FlutterSwitch wrap with container and set aligment. It didn't work. then i tried Positioned, It also didn't work</p> <pre><code>Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Container( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: Column( children: [ Align( alignment: Alignment.topRight, child: FlutterSwitch( value: isSwitchOn, onToggle: (value) { setState(() { isSwitchOn = value; }); }, width: 60.0, height: 40.0, toggleSize: 28.0, activeToggleColor: const Color.fromARGB(255, 113, 82, 173), inactiveToggleColor: const Color(0xFF2F363D), activeColor: const Color.fromARGB(255, 49, 32, 82), inactiveColor: Colors.grey, activeIcon: const Icon( Icons.nightlight_round, color: Color(0xFFF8E3A1), ), inactiveIcon: const Icon( Icons.wb_sunny, color: Color(0xFFF8E3A1), ), ), ), ], ), ), ), ); </code></pre>
[ { "answer_id": 74501767, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "function areSameRef(thing1, thing2){\n thing1.modify()\n return thing1.equals(thing2) //make sure this is not just a referential equality check\n}\n function foo(list1, list2){\n list1.append(someElement)\n return list1.length == list2.length\n}\n function bar(list1, list2){\n list1.set(someIndex, someElement)\n return list1.get(someIndex)==list2.get(someIndex)\n}\n for i in [nums 1:] foo(5) 6 7 def foo(x : int):\n l = range(9999)\n return 5\n\ndef bar(x:int):\n l = range(9999)\n if (x + 1 != (x*2+2)/2):\n return l[x]\n else:\n return 5\n foo bar foo l bar l range list for i in nums[1:]" }, { "answer_id": 74502437, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "nums[1:] nums.__getitem__(slice(1, None)) list_subscript nums[1:] nums = [1 ,2, 3]\ntmp = nums[1:]\nfor item in tmp:\n pass\n\ntmp[0] = \"new stuff\"\n\nassert id(nums) != id(tmp), \"List slice creates a new object\"\nassert type(tmp) == type(nums), \"List slice creates a new list\"\nassert 999 not in nums, \"List slice doesn't affect original\"\n import numpy as np\n\nnums = np.array([1,2,3])\ntmp = nums[1:]\nfor item in tmp:\n pass\n\ntmp[0] = 999\n\nassert id(nums) != id(tmp), \"array slice creates a new object\"\nassert type(tmp) == type(nums), \"array slice creates a new list\"\nassert 999 not in nums, \"array slice doesn't affect original\"\n" }, { "answer_id": 74502479, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": ":= import sys\nprint(sys.version)\n\na = list(range(1000))\nfor i in (b := a[1:]):\n b[0] = 906\nprint(b is a)\nprint(a[:10])\nprint(b[:10])\nprint(sys.getsizeof(a))\nprint(sys.getsizeof(b))\n 3.11.0 (main, Nov 4 2022, 00:14:47) [GCC 7.5.0]\nFalse\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[906, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n8056\n8048\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10725992/" ]
74,501,726
<p>Here is my dataframe:</p> <pre><code>col1 &lt;- c(&quot;hello my name is&quot;, &quot;Nice to meet you&quot;, &quot;how are you&quot;) col2 &lt;- c(&quot;dog&quot;, &quot;Cats&quot;, &quot;Frogs are cool&quot;) col3 &lt;- c(&quot;Pause&quot;, &quot;breathe in and out&quot;, &quot;what are you talking about&quot;) df &lt;- data.frame(col1, col2, col3) </code></pre> <p>I want to apply <code>gsub</code> on the following variables in my df:</p> <pre><code>vars &lt;- c(&quot;col1&quot;, &quot;col2&quot;) </code></pre> <p>I want to use <code>gsub</code> to capitalize the first letter of every cell:</p> <pre><code>df &lt;- df %&gt;% as_tibble() %&gt;% mutate(across(vars), gsub, pattern = &quot;^(\\w)(\\w+)&quot;, replacement = &quot;\\U\\1\\L\\2&quot;, perl = TRUE) </code></pre> <p>But I'm getting the following error:</p> <pre><code>Error in `mutate_cols()`: ! Problem with `mutate()` input `..2`. ℹ `..2 = gsub`. x `..2` must be a vector, not a function. Run `rlang::last_error()` to see where the error occurred. </code></pre> <p>Any guidance would be appreciated!</p>
[ { "answer_id": 74501755, "author": "deschen", "author_id": 2725773, "author_profile": "https://Stackoverflow.com/users/2725773", "pm_score": 3, "selected": true, "text": "df %>%\n as_tibble() %>%\n mutate(across(any_of(vars), gsub, pattern = \"^(\\\\w)(\\\\w+)\", replacement = \"\\\\U\\\\1\\\\L\\\\2\"))\n # A tibble: 3 x 3\n col1 col2 col3 \n <chr> <chr> <chr> \n1 UhLello my name is UdLog Pause \n2 UNLice to meet you UCLats breathe in and out \n3 UhLow are you UFLrogs are cool what are you talking about\n" }, { "answer_id": 74503389, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf |>\n as_tibble() |>\n mutate(across(all_of(vars), str_to_sentence))\n#> # A tibble: 3 x 3\n#> col1 col2 col3 \n#> <chr> <chr> <chr> \n#> 1 Hello my name is Dog Pause \n#> 2 Nice to meet you Cats breathe in and out \n#> 3 How are you Frogs are cool what are you talking about\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4937644/" ]
74,501,735
<p>I need to copy the contents of a file to the end of the same file.</p> <p>I wrote the following code.</p> <pre><code>#!/bin/bash cat file.txt &gt;&gt; file1.txt cat file1.txt &gt;&gt; file.txt rm file1.txt </code></pre> <p>But it creates an additional file. How can this be done without creating an additional file?</p>
[ { "answer_id": 74501755, "author": "deschen", "author_id": 2725773, "author_profile": "https://Stackoverflow.com/users/2725773", "pm_score": 3, "selected": true, "text": "df %>%\n as_tibble() %>%\n mutate(across(any_of(vars), gsub, pattern = \"^(\\\\w)(\\\\w+)\", replacement = \"\\\\U\\\\1\\\\L\\\\2\"))\n # A tibble: 3 x 3\n col1 col2 col3 \n <chr> <chr> <chr> \n1 UhLello my name is UdLog Pause \n2 UNLice to meet you UCLats breathe in and out \n3 UhLow are you UFLrogs are cool what are you talking about\n" }, { "answer_id": 74503389, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf |>\n as_tibble() |>\n mutate(across(all_of(vars), str_to_sentence))\n#> # A tibble: 3 x 3\n#> col1 col2 col3 \n#> <chr> <chr> <chr> \n#> 1 Hello my name is Dog Pause \n#> 2 Nice to meet you Cats breathe in and out \n#> 3 How are you Frogs are cool what are you talking about\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133865/" ]
74,501,737
<p>I have an edgelist in a pandas dataframe that looks like this:</p> <pre><code> topic neighbor 0 K Kl 1 K Pr 2 Kl TS 3 Pr Kl 4 Pr Pr </code></pre> <p>When I turn this into a Graph (using networkx as nx) with <code>G = nx.from_pandas_edgelist(df)</code> it gives me KeyError: 'source'.</p> <p>It works when I specify a source and target <code>G = nx.from_pandas_edgelist(df, &quot;topic&quot;, &quot;neighbor&quot;)</code> but this is an undirected Graph so I do not really want a source and target.</p> <p>Is this the way it has to be done? Will specifying a source and target have implications for later calculations of degree_centrality?</p>
[ { "answer_id": 74501809, "author": "SultanOrazbayev", "author_id": 10693596, "author_profile": "https://Stackoverflow.com/users/10693596", "pm_score": 2, "selected": true, "text": "create_using from networkx import Graph, from_pandas_edgelist\n\ndf = ...\n\n# note that Graph is the default setting, so specifying\n# create_using=Graph is optional\nG = from_pandas_edgelist(df, \"topic\", \"neighbor\", create_using=Graph)\n\n\nprint(G.is_directed())\n# False\n" }, { "answer_id": 74501821, "author": "Scott Boston", "author_id": 6361531, "author_profile": "https://Stackoverflow.com/users/6361531", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport networkx as nx\n\ndf = pd.read_clipboard()\nprint(df)\n topic neighbor\n0 K Kl\n1 K Pr\n2 Kl TS\n3 Pr Kl\n4 Pr Pr\n source target G = nx.from_pandas_edgelist(df, source='topic', target='neighbor')\nnx.draw_networkx(G)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17280156/" ]
74,501,744
<p>normally we would use it like that:</p> <pre><code>class TestClass { public $t; public function set(\stdClass &amp;$t) { $this-&gt;t = &amp;$t; } } $obj = new \stdClass(); $obj-&gt;fromOUTSIDE = 1; $test = new TestClass(); $test-&gt;set($obj); var_dump($test); </code></pre> <p><a href="https://onlinephp.io/c/cf4e3" rel="nofollow noreferrer">https://onlinephp.io/c/cf4e3</a></p> <p>this results in the desired result:</p> <pre><code>object(TestClass)#2 (1) { [&quot;t&quot;]=&gt; &amp;object(stdClass)#1 (1) { [&quot;fromOUTSIDE&quot;]=&gt; int(1) } } </code></pre> <p>notice the &amp; character, as its a reference. So far so good!</p> <p>But what if the <code>__get</code> magic method creates this?</p> <pre><code>class TestClass { public function __get(string $propertyName) { $xx = new \stdClass(); $xx-&gt;fromGET = 1; $this-&gt;t = &amp;$xx; return $this-&gt;t; } } $test = new TestClass(); $test-&gt;t; var_dump($test); </code></pre> <p><a href="https://onlinephp.io/c/21f4f" rel="nofollow noreferrer">https://onlinephp.io/c/21f4f</a></p> <p>the reference character disappeared!</p> <pre><code>object(TestClass)#1 (1) { [&quot;t&quot;]=&gt; object(stdClass)#2 (1) { [&quot;fromGET&quot;]=&gt; int(1) } } </code></pre> <p>how to make it referenced? Even using the public function &amp;__get form still no work!</p> <p>EDIT:</p> <p>So a basic code:</p> <pre><code>class X { public \stdClass $t; public function __construct(\stdClass &amp;$t) { $this-&gt;t = &amp;$t; } } $t = new \stdClass(); $t-&gt;TTTT = 1; $X = new X($t); var_dump($t);echo &quot;\r\n&quot;; var_dump($X-&gt;t);echo &quot;\r\n&quot;; $t = new \stdClass(); $t-&gt;TTTT = 2; var_dump($t);echo &quot;\r\n&quot;; var_dump($X-&gt;t);echo &quot;\r\n&quot;; </code></pre> <p><a href="https://onlinephp.io/c/9cd7a" rel="nofollow noreferrer">https://onlinephp.io/c/9cd7a</a></p> <p>see, it results #1, #1, #3, #1 because renewing the old object wont be affected the object inside the <code>X</code>. If I do:</p> <pre><code>&lt;?php class X { public \stdClass $t; public function __construct(\stdClass &amp;$t) { $this-&gt;t = &amp;$t; } } $t = new \stdClass(); $t-&gt;TTTT = 1; $X = new X($t); var_dump($t);echo &quot;\r\n&quot;; var_dump($X-&gt;t);echo &quot;\r\n&quot;; $t = new \stdClass(); $t-&gt;TTTT = 2; var_dump($t);echo &quot;\r\n&quot;; var_dump($X-&gt;t);echo &quot;\r\n&quot;; </code></pre> <p><a href="https://onlinephp.io/c/8efd4" rel="nofollow noreferrer">https://onlinephp.io/c/8efd4</a></p> <p>gives the desired result, #1, #1, #3, #3. But what if <code>$t</code> property doesn't exist? Maybe <code>__get</code> has to create it or obtain from an object-container. And this is where I can't solve it.</p>
[ { "answer_id": 74533165, "author": "SvenTUM", "author_id": 11370312, "author_profile": "https://Stackoverflow.com/users/11370312", "pm_score": 2, "selected": false, "text": "stdClass <?php\nclass TestClass\n{\n public function __get(string $propertyName)\n {\n $xx = new StdClass();\n $xx->fromGET = 1;\n $this->t = $xx; // no reference needed here\n return $this->t;\n }\n}\n\n$test = new TestClass();\n$test->t;\n\n// another Reference to the object is created\n$t =& $test->t;\nvar_dump($test);\n" }, { "answer_id": 74534792, "author": "Lenny4", "author_id": 6824121, "author_profile": "https://Stackoverflow.com/users/6824121", "pm_score": 3, "selected": true, "text": "t stdClass __get $xx __get global <?php\n\nclass TestClass\n{\n public function __get(string $propertyName)\n {\n global $xx;\n $xx = new \\stdClass();\n $xx->fromGET = 1;\n $this->t = &$xx;\n return $this->t;\n }\n}\n\n$test = new TestClass();\n$test->t;\nvar_dump($test);\n object(TestClass)#1 (1) {\n [\"t\"]=>\n &object(stdClass)#2 (1) {\n [\"fromGET\"]=>\n int(1)\n }\n}\n $xx __get <?php\n\nclass TestClass\n{\n public function __construct(\\stdClass $xx)\n {\n $this->xx = $xx;\n }\n\n public function __get(string $propertyName)\n {\n $this->xx->fromGET = 1;\n $this->t = &$this->xx;\n return $this->t;\n }\n}\n\n$test = new TestClass(new \\stdClass());\n$test->t;\nvar_dump($test);\n object(TestClass)#1 (2) {\n [\"xx\"]=>\n &object(stdClass)#2 (1) {\n [\"fromGET\"]=>\n int(1)\n }\n [\"t\"]=>\n &object(stdClass)#2 (1) {\n [\"fromGET\"]=>\n int(1)\n }\n}\n unset($test->xx) <?php\n\nclass TestClass\n{\n public function __construct(\\stdClass $xx)\n {\n $this->xx = $xx;\n }\n\n public function __get(string $propertyName)\n {\n $this->xx->fromGET = 1;\n $this->t = &$this->xx;\n return $this->t;\n }\n}\n\n$test = new TestClass(new \\stdClass());\n$test->t;\nunset($test->xx);\nvar_dump($test);\n object(TestClass)#1 (1) {\n [\"t\"]=>\n object(stdClass)#2 (1) {\n [\"fromGET\"]=>\n int(1)\n }\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043342/" ]
74,501,748
<p>I have a bottom sheet dialog with 2 <code>nestedscrollview</code>, the outer one wrap the entire view, the inner one wrap a single <code>textview</code>, I have 2 problems:</p> <p><em><strong>1.</strong></em> the the inner one can scroll only down, as you can see in the gif:</p> <p><a href="https://i.stack.imgur.com/KZCQ7.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KZCQ7.gif" alt="enter image description here" /></a></p> <p>I need to make the inner <code>nestedscrollview</code> scrollable in both direction and the outer <code>nestedscrollview</code> scrollable when I drag outside the inner one, how can I do it?</p> <p><em><strong>2.</strong></em> I need to make the inner <code>nestedscrollview</code> to wrap text, tried with constraints but not working, wrap_content make the entire <code>textview</code> to be shown, making the <code>scrollview</code> a simple <code>textview</code>.</p> <p>How can I do it?</p> <p>This is my XML code:</p> <pre><code>&lt;androidx.core.widget.NestedScrollView android:id=&quot;@+id/outer_scrollview&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;ViewSwitcher android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt; &lt;androidx.core.widget.NestedScrollView android:id=&quot;@+id/inner_scrollview&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;match_parent&quot; android:background=&quot;200dp&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt; &lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&quot; android:textColor=&quot;@color/white&quot; android:textSize=&quot;25dp&quot; &lt;/androidx.core.widget.NestedScrollView&gt; &lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;&gt;&lt;/TextView&gt; &lt;/ViewSwitcher&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; &lt;/androidx.core.widget.NestedScrollView&gt; </code></pre>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12615735/" ]
74,501,791
<p>I am struggling in writing a code that would produce a plot of any function with rectangle overlay of the area under the function for a specific interval. I see many examples of density functions with histograms but I want my rectangle to be bound by the function curve. We can take a function like x^2 as an example. Can someone help? something like this:</p> <p>Image reference: <a href="https://www.whitman.edu/mathematics/calculus_online/section08.06.html" rel="nofollow noreferrer">https://www.whitman.edu/mathematics/calculus_online/section08.06.html</a></p> <p>I tried different codes but I am new to R.</p>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549084/" ]
74,501,803
<p>I have below code :</p> <pre><code>public async Task StartAsync(CancellationToken cancellationToken) { var cronExpressionVal = new Timer(async e =&gt; await GetCronExpression(cancellationToken), null, TimeSpan.Zero, new TimeSpan(0, 5, 0)); } </code></pre> <p>What I am trying to achieve is, <code>GetCronExpression</code> method should run at every 5 minutes.</p> <p>But my problem is, when we first time run programme so it is coming in <code>StartAsync</code> method.</p> <p>And it execute successfully.</p> <p>Now it is not coming again in this method so my <code>GetCronExpression</code> method is not calling at every 5 minutes.</p> <p>So my question is where should I put this <code>GetCronExpression</code> method call so it execute at every 5 minutes.</p>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17029269/" ]
74,501,844
<p>So I’m trying to create a buy and sell program and in there, I also coded the range where a random price out of a certain range will pop out. Now the problem is I can’t figure out a way on how to display a “not available today” on a 15% chance. so basically the price list will only show the price of the item OR a “not available today” note.</p> <pre><code>this is how the code looks like now. i only inserted the price range and an srand function. srand(time(NULL)); item1 = rand() % (1000 - 500 + 1) + 500; item2 = rand() % (5000 - 1500 + 1) + 1500; item3 = rand() % ( 8000 - 5000 + 1 ) + 5000; printf(&quot;The Price of Item1 is %dG\n&quot;, item1); printf(&quot;The Price of Item2 is %dG\n&quot;, item2); printf(&quot;The Price of Item3 is %dG\n&quot;, item3); </code></pre>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20117789/" ]
74,501,859
<p>Making a registration form for a website using Vue 3. I have a method, that gets values of password and password confirmation fields and compares it. If they're true - nothing happens, else - a red label appears and submit button gets disabled. I have implemented this in vue 3. but when passwords are equal, it dont works, but sometimes when they are not, it displays that they are.</p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;label for=&quot;password&quot;&gt;Пароль&lt;/label&gt; &lt;input type=&quot;text&quot; v-model=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; placeholder=&quot;••••••••&quot; required=&quot;&quot;&gt; &lt;/div&gt; &lt;div&gt; &lt;label for=&quot;confirm-password&quot;&gt;Подтвердите Пароль&lt;/label&gt; &lt;input @keydown=&quot;confirmPassword&quot; type=&quot;confirm-password&quot; v-model=&quot;confirm&quot; name=&quot;confirm-password&quot; id=&quot;confirm-password&quot; placeholder=&quot;••••••••&quot; required=&quot;&quot;&gt; &lt;label for=&quot;confirm-password&quot; v-if=&quot;invalidPasswords&quot;&gt;Пароли не совпадают&lt;/label&gt; &lt;/div&gt; &lt;button :disabled=&quot;submitDisabled&quot; type=&quot;submit&quot;&gt;Создать аккаунт&lt;/button&gt; &lt;/template&gt; &lt;script&gt; export default { name: &quot;RegistrationView&quot;, data () { return { ... password: '', confirm: '', invalidPasswords: false, submitDisabled: false, } }, methods: { confirmPassword() { if (this.password !== this.confirm){ this.invalidPasswords = true this.submitDisabled = true } else { this.invalidPasswords = false this.submitDisabled = false } }, }, } &lt;/script&gt; </code></pre> <p>Screenshots: <a href="https://i.stack.imgur.com/3eOB1.png" rel="nofollow noreferrer">https://i.stack.imgur.com/3eOB1.png</a> <a href="https://i.stack.imgur.com/ein5h.png" rel="nofollow noreferrer">https://i.stack.imgur.com/ein5h.png</a> <a href="https://i.stack.imgur.com/ein5h.png" rel="nofollow noreferrer">https://i.stack.imgur.com/ein5h.png</a></p>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13767821/" ]
74,501,871
<p>I am trying to parse through a data structure and I have used a for loop initializing a variable i and using the range() function. I originally set my range to be the size of the records: 25,173 but then I kept receiving an</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In [63], line 41 37 input_list.append(HOME_AVG_PTS) 39 return input_list ---&gt; 41 Data[&quot;AVG_PTS_HOME&quot;]= extract_wl(AVG_PTS_HOME) Cell In [63], line 28, in extract_wl(input_list) 26 if i==25172: 27 HOME_AVG_PTS[0]= HOME_AVG_PTS[0]/count ---&gt; 28 elif int(Data([&quot;TEAM_ID_AWAY&quot;][i])) == const_home_team_id: 29 if type(PTS_AWAY[i]) is int: 30 count+= 1 IndexError: list index out of range </code></pre> <p>So I tried changing my for loop to be in the range of the function with the issue i.e.</p> <pre><code>for i in range(len(Data[&quot;TEAM_ID_AWAY&quot;])): </code></pre> <p>But I keep receiving the same error still</p> <p>The Data variable holds the contents of a csv file which I have used the panda module to read and put into Data. You can assume all the column headers I have used are valid and furthermore that they all have range 25173. [Here is an image showing the range and values for the Data<a href="https://i.stack.imgur.com/ZWkHQ.png" rel="nofollow noreferrer">&quot;TEAM_ID_HOME&quot;</a></p> <pre><code>AVG_PTS_HOME = [] def extract_wl(input_list): for j in range(25173): const_season_id = Data[&quot;SEASON_ID&quot;][j] #print(const_season_id) const_game_id = int(Data[&quot;GAME_ID&quot;][j]) #print(const_game_id) const_home_team_id = Data[&quot;TEAM_ID_HOME&quot;][j] #print(const_home_team_id) #if j==10: #break print(&quot;Iteration #&quot;, j) print(len(Data[&quot;TEAM_ID_AWAY&quot;])) count = 0 HOME_AVG_PTS=[0.0] for i in range(len(Data[&quot;TEAM_ID_AWAY&quot;])): if (int(Data[&quot;GAME_ID&quot;][i]) &lt; const_game_id and int(Data[&quot;SEASON_ID&quot;][i]) == const_season_id): if int(Data[&quot;TEAM_ID_HOME&quot;][i]) == const_home_team_id: if type(PTS_HOME[i]) is int: count+= 1 HOME_AVG_PTS[0]+= PTS_HOME[i] if i==25172: HOME_AVG_PTS[0]= HOME_AVG_PTS[0]/count elif int(Data([&quot;TEAM_ID_AWAY&quot;][i])) == const_home_team_id: if type(PTS_AWAY[i]) is int: count+= 1 HOME_AVG_PTS[0]+= PTS_AWAY[i] if i==25172: HOME_AVG_PTS[0]= float(HOME_AVG_PTS[0]/count) print(HOME_AVG_PTS) input_list.append(HOME_AVG_PTS) return input_list Data[&quot;AVG_PTS_HOME&quot;]= extract_wl(AVG_PTS_HOME) </code></pre> <p>Can anyone point out why I am having this error or help me resolve it? In the meantime I think I am going to just create a separate function which takes a list of all the AWAY_IDs and then parse through that instead.</p>
[ { "answer_id": 74531377, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "android:editable=\"false\" Edittext.setEnabled(false); " }, { "answer_id": 74545847, "author": "Saiful Sazib", "author_id": 4047442, "author_profile": "https://Stackoverflow.com/users/4047442", "pm_score": 0, "selected": false, "text": " ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);\n" }, { "answer_id": 74612052, "author": "Aniruddh Parihar", "author_id": 8031784, "author_profile": "https://Stackoverflow.com/users/8031784", "pm_score": 2, "selected": true, "text": "<androidx.core.widget.NestedScrollView\n android:id=\"@+id/outer_scrollview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:fillViewport=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.constraintlayout.widget.ConstraintLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n\n <ViewSwitcher\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n\n <androidx.core.widget.NestedScrollView\n android:id=\"@+id/inner_scrollview\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:background=\"200dp\"\n android:nestedScrollingEnabled=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\">\n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\">\n\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n android:textColor=\"@color/white\"\n android:textSize=\"25dp\"></TextView>\n \n </LinearLayout> \n \n </androidx.core.widget.NestedScrollView>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"></TextView>\n\n </ViewSwitcher>\n\n </androidx.constraintlayout.widget.ConstraintLayout>\n\n</androidx.core.widget.NestedScrollView>\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20351405/" ]
74,501,874
<p>I want to read a image from api, but I am getting a error TypeError: 'module' object is not callable. I am trying to make a random meme generator</p> <pre><code>import PySimpleGUI as sg from PIL import Image import requests, json cutURL = 'https://meme-api-python.herokuapp.com/gimme' imageURL = json.loads(requests.get(cutURL).content)[&quot;url&quot;] img = Image(requests.get(imageURL).content) img_box = sg.Image(img) window = sg.Window('', [[img_box]]) while True: event, values = window.read() if event is None: break window.close() </code></pre> <pre><code>Here is the response of the api postLink &quot;https://redd.it/yyjl2e&quot; subreddit &quot;dankmemes&quot; title &quot;Everything's fixed&quot; url &quot;https://i.redd.it/put9bi0vjp0a1.jpg&quot; </code></pre> <p>I tried using python simple gui module, IS there alternative way to make a random meme generator.</p>
[ { "answer_id": 74502147, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 1, "selected": false, "text": "Image.open(...) Image BytesIO Image.open BytesIO Image.open BytesIO StringIO from io import BytesIO\n\ndef get_image(url):\n data = BytesIO(requests.get(url).content)\n return Image.open(data)\n" }, { "answer_id": 74502191, "author": "finix", "author_id": 17105703, "author_profile": "https://Stackoverflow.com/users/17105703", "pm_score": 1, "selected": false, "text": "def window():\n root = tk.Tk()\n panel = Label(root)\n panel.pack()\n img = None\n\n def updata():\n\n response = requests.get(https://meme-api-python.herokuapp.com/gimme)\n img = Image.open(BytesIO(response.content))\n img = img.resize((640, 480), Image.ANTIALIAS) #custom resolution\n img = ImageTk.PhotoImage(img)\n panel.config(image=img)\n panel.image = img\n \n root.update_idletasks()\n root.after(30, updata)\n\n updata()\n root.mainloop()\n" }, { "answer_id": 74502239, "author": "Jason Yang", "author_id": 11936135, "author_profile": "https://Stackoverflow.com/users/11936135", "pm_score": 3, "selected": true, "text": "PIL.Image from io import BytesIO\nimport PySimpleGUI as sg\nfrom PIL import Image\nimport requests, json\n\ndef image_to_data(im):\n \"\"\"\n Image object to bytes object.\n : Parameters\n im - Image object\n : Return\n bytes object.\n \"\"\"\n with BytesIO() as output:\n im.save(output, format=\"PNG\")\n data = output.getvalue()\n return data\n\ncutURL = 'https://meme-api-python.herokuapp.com/gimme'\n\nimageURL = json.loads(requests.get(cutURL).content)[\"url\"]\ndata = requests.get(imageURL).content\nstream = BytesIO(data)\nimg = Image.open(stream)\n\nimg_box = sg.Image(image_to_data(img))\n\nwindow = sg.Window('', [[img_box]], finalize=True)\n\n# Check if the size of the window is greater than the screen\nw1, h1 = window.size\nw2, h2 = sg.Window.get_screen_size()\nif w1>w2 or h1>h2:\n window.move(0, 0)\n\nwhile True:\n event, values = window.read()\n if event is None:\n break\nwindow.close()\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20166957/" ]
74,501,885
<p>I'm working on a canvas that allows dragging shapes like Figma. I want to draw a guideline (x, y) when shapes intersect each other, just like below.</p> <p>I already handled when shapes are snapped, so we don't need to calculate when they snap each other, basically, we know when should draw the lines. Just couldn't figure out the calculation of lines. Also, we already know the rect values when the shapes are snapped.</p> <p><strong>Edit:</strong></p> <p>Here is the codepen link that you can play with it. You'll see the shapes are not always drawing correctly.</p> <p><a href="https://codepen.io/lakers19/pen/ZEoPpKL" rel="nofollow noreferrer">https://codepen.io/lakers19/pen/ZEoPpKL</a></p> <pre class="lang-js prettyprint-override"><code>&quot;firstRect&quot;:{ &quot;x&quot;: 827, &quot;y&quot;: 282, &quot;width&quot;: 95, &quot;height&quot;: 43, &quot;right&quot;: 923, &quot;bottom&quot;: 325, &quot;top&quot;: 282, &quot;left&quot;: 827, } &quot;secondRect&quot;: { &quot;x&quot;: 745, &quot;y&quot;: 365, &quot;width&quot;: 82, &quot;height&quot;: 42, &quot;right&quot;: 827, &quot;bottom&quot;: 407, &quot;top&quot;: 365, &quot;left&quot;: 745, } { &quot;currentRect&quot;: { &quot;x&quot;: 938, &quot;y&quot;: 369, &quot;width&quot;: 134, &quot;height&quot;: 80, &quot;top&quot;: 369, &quot;right&quot;: 1073, &quot;bottom&quot;: 449, &quot;left&quot;: 938 } } </code></pre> <p>According to these values, I want to apply styles something like this:</p> <pre class="lang-js prettyprint-override"><code> guideLineX.style.left = `.. px` guideLineX.style.top = `..px` guideLineX.style.width = '1px' guideLineX.style.height = `..px` guideLineY.style.left = `..px` guideLineY.style.top = `..px` guideLineY.style.width = `...px` guideLineY.style.height = '1px' </code></pre> <p><a href="https://i.stack.imgur.com/eJQ53.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJQ53.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74554071, "author": "Attic V", "author_id": 20558601, "author_profile": "https://Stackoverflow.com/users/20558601", "pm_score": -1, "selected": false, "text": "if (tops of rectangles line up):\n draw a line on the top that connects the corners\n\nif (left of rectangles line up):\n draw a line on the left that connects the corners\n\nif (right of rectangles line up):\n draw a line on the right that connects the corners\n\nif (bottom of rectangles line up):\n draw a line on the bottom that connects the corners\n" }, { "answer_id": 74606981, "author": "Sascha Doerdelmann", "author_id": 11934850, "author_profile": "https://Stackoverflow.com/users/11934850", "pm_score": 0, "selected": false, "text": "const inRange = true var actualY;\n var distance = 1000000;\n const edges = [rect.top, rect.bottom ];\n for(e = 0; e < 2; e++){\n const edge = edges[e];\n candidates = [firstRect.top, firstRect.bottom, secondRect.top, secondRect.bottom ];\n for(c = 0; c < 4; c++){\n const candidate = candidates[c];\n const candidateDistance = Math.max(candidate,edge) - Math.min(candidate, edge);\n if(candidateDistance < distance){\n actualY = candidate;\n distance = candidateDistance;\n }\n }\n }\n Math.min(rect.right, horizontalRect.right);\n Math.max(rect.left, horizontalRect.left);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10330468/" ]
74,501,916
<p>Reading a book about bash and it was introducing regular expressions(I'm pretty new to them) with an example:</p> <pre><code>rename -n 's/(.*)(.*)/new$1$2/' * 'file1' would be renamed to 'newfile1' 'file2' would be renamed to 'newfile2' 'file3' would be renamed to 'newfile3' </code></pre> <p>There wasn't really a breakdown provided with this example, unfortunately. I kind of get what capture groups are and that .* is greedy and will match all characters but I'm uncertain as to why two capture groups are needed. Also, I get that $ represents the end of the line but am unsure of what $1$2 is actually doing here. Appreciate any insight provided.</p> <p>Attempted to research capture groups and the $ for some similar examples with explanations but came up short.</p>
[ { "answer_id": 74502347, "author": "Robert", "author_id": 1431720, "author_profile": "https://Stackoverflow.com/users/1431720", "pm_score": 1, "selected": false, "text": "rename sed s (.*)(.*) new$1$2 $ $ $1 $2 $0 .* \\. basename rename -n 's/(.*)/new$1/' *" }, { "answer_id": 74502571, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 3, "selected": true, "text": "(.*)(.*) .* file .* file .* rename -n 's/(.*)/new$1/' *\n rename -n 's/.*/new$&/' *\n rename -n 's/^/new/' *\n rename -n '$_ = \"new$_\"' *\n rename -n '$_ = \"new\" . $_' *\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397334/" ]
74,501,917
<p>I'm having some trouble returning the properties of my object. I keep getting an undefined error when I run the following code. I'm trying to reference what the rank is for each individual card. I thought the best way would be for them to each have their own object. However, when I console log I cant seem to get the properties out. Any advice?</p> <ul> <li>The first console.log I need to return the rank #.</li> </ul> <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> //Deck with ranks var arrClubs = [ {"img": '2_of_clubs.png',"rank": 1},{"img": '3_of_clubs.png',"rank": 2},{"img": '4_of_clubs.png',"rank": 3},{"img": '5_of_clubs.png',"rank": 4},{"img": '6_of_clubs.png',"rank": 5},{"img": '7_of_clubs.png',"rank": 6},{"img": '8_of_clubs.png',"rank": 7},{"img": '9_of_clubs.png',"rank": 8},{"img": '10_of_clubs.png',"rank": 9},{"img": 'jack_of_clubs.png',"rank": 10},{"img": 'queen_of_clubs.png',"rank": 11},{"img": 'king_of_clubs.png',"rank": 12},{"img": 'ace_of_clubs.png',"rank": 13}, ] var suitType = Math.ceil(Math.random() * 1) var card = Math.floor(Math.random() * 12) var selectedCard //storing selected card if (suitType == "1"){ //Clubs console.log(JSON.stringify([arrClubs[rank]])) //selectedCard = arrClubs[card] }else if(suitType == "2"){ //Diamonds // console.log(arrDiamonds[card]) //selectedCard = arrDiamonds[card] } else if (suitType == "3"){ //Hearts // console.log(arrHearts[card]) //selectedCard = arrHearts[card] } else { //Spades // console.log(arrSpades[card]) // selectedCard = arrSpades[card] } document.getElementById('p1Card').src = "./images/cards/" + selectedCard</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;img src="./images/cards/black_joker.png" height="300px" id="p1Card"&gt; &lt;img src="./images/cards/red_joker.png" height="300px" id="p2Card"&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74501940, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 1, "selected": false, "text": "var arrClubs = [\n {\"img\": '2_of_clubs.png',\"rank\": 1},{\"img\": '3_of_clubs.png',\"rank\": 2},{\"img\": '4_of_clubs.png',\"rank\": 3},{\"img\": '5_of_clubs.png',\"rank\": 4},{\"img\": '6_of_clubs.png',\"rank\": 5},{\"img\": '7_of_clubs.png',\"rank\": 6},{\"img\": '8_of_clubs.png',\"rank\": 7},{\"img\": '9_of_clubs.png',\"rank\": 8},{\"img\": '10_of_clubs.png',\"rank\": 9},{\"img\": 'jack_of_clubs.png',\"rank\": 10},{\"img\": 'queen_of_clubs.png',\"rank\": 11},{\"img\": 'king_of_clubs.png',\"rank\": 12},{\"img\": 'ace_of_clubs.png',\"rank\": 13}\n]\n\nconsole.log(arrClubs)\n console.table(arrClubs)\n" }, { "answer_id": 74501953, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 2, "selected": true, "text": "var arrClubs = [\n {\"img\": '2_of_clubs.png',\"rank\": 1},{\"img\": '3_of_clubs.png',\"rank\": 2},\n ];\n \n console.log(arrClubs[0].rank)" }, { "answer_id": 74501965, "author": "tstrmn", "author_id": 15605135, "author_profile": "https://Stackoverflow.com/users/15605135", "pm_score": 0, "selected": false, "text": "JSON.stringify console.log(arrClubs) console.log(arrClubs[0].rank) const ranks = arrClubs.map(item => item.rank);\nconsole.log(ranks);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11996252/" ]
74,501,930
<p>I am currently struggling with moving data from a function calculation in R. I have 8 columns that have calculated a certain y value at the same point under different conditions (type), and my output looks like this:</p> <pre><code>ydata &lt;- output %&gt;% select(x, type, y_a,y_b,y_c,y_d,y_e,y_f,y_g,y_h) ydata #&gt; x type y_a y_b y_c ... #&gt; 1 1 1.3 &lt;NA&gt; &lt;NA&gt; #&gt; 2 1 2.7 &lt;NA&gt; &lt;NA&gt; #&gt; 3 1 4.4 &lt;NA&gt; &lt;NA&gt; #&gt; 1 2 &lt;NA&gt; 2.2 &lt;NA&gt; #&gt; 2 2 &lt;NA&gt; 3.3 &lt;NA&gt; #&gt; 3 2 &lt;NA&gt; 4.4 &lt;NA&gt; #&gt; 1 3 &lt;NA&gt; &lt;NA&gt; 3.3 #&gt; 2 3 &lt;NA&gt; &lt;NA&gt; 7.6 #&gt; 3 3 &lt;NA&gt; &lt;NA&gt; 11.3 ... </code></pre> <p>However, my desired output would look like this, which I am unsure how to produce:</p> <pre><code>#&gt; x y_a y_b y_c ... #&gt; 1 1.3 2.2 3.3 #&gt; 2 2.7 3.3 7.6 #&gt; 3 4.4 4.4 11.3 ... </code></pre> <p>I've tried using summarize() to group the variables together by x, but doing so would not shift the column's data in the desired way so that the &lt;NA&gt; values would not appear in the data frame.</p>
[ { "answer_id": 74502140, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": true, "text": "library(dplyr)\n\ndf %>% \n group_by(x) %>% \n summarize(across(contains(\"_\"), ~ .x[.x != \"<NA>\"]))\n# A tibble: 3 × 4\n x y_a y_b y_c\n <int> <chr> <chr> <chr>\n1 1 1.3 2.2 3.3\n2 2 2.7 3.3 7.6\n3 3 4.4 4.4 11.3\n df <- structure(list(x = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), type = c(1L,\n1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), y_a = c(\"1.3\", \"2.7\", \"4.4\",\n\"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\"), y_b = c(\"<NA>\",\n\"<NA>\", \"<NA>\", \"2.2\", \"3.3\", \"4.4\", \"<NA>\", \"<NA>\", \"<NA>\"),\n y_c = c(\"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"3.3\",\n \"7.6\", \"11.3\")), class = \"data.frame\", row.names = c(NA,\n-9L))\n" }, { "answer_id": 74502200, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 0, "selected": false, "text": "y_a y_b pivot_longer(df,cols = -(x:type)) %>% \n filter(value!=\"<NA>\") %>% \n pivot_wider(x)\n x y_a y_b y_c \n <int> <chr> <chr> <chr>\n1 1 1.3 2.2 3.3 \n2 2 2.7 3.3 7.6 \n3 3 4.4 4.4 11.3 \n pivot_wider(filter(pivot_longer(df,cols = -(x:type)), value!=\"<NA>\"),x)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17346985/" ]
74,501,949
<p>I am having trouble finding a way that takes the average from a list box and then displaying that average on the user form. I know you are supposed to use an array, but I am very confused at the moment how to array a second column on a list box. Below is an example the numbers in the text box need to be averaged up and then displayed in the circle I have</p>
[ { "answer_id": 74502140, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": true, "text": "library(dplyr)\n\ndf %>% \n group_by(x) %>% \n summarize(across(contains(\"_\"), ~ .x[.x != \"<NA>\"]))\n# A tibble: 3 × 4\n x y_a y_b y_c\n <int> <chr> <chr> <chr>\n1 1 1.3 2.2 3.3\n2 2 2.7 3.3 7.6\n3 3 4.4 4.4 11.3\n df <- structure(list(x = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), type = c(1L,\n1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), y_a = c(\"1.3\", \"2.7\", \"4.4\",\n\"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\"), y_b = c(\"<NA>\",\n\"<NA>\", \"<NA>\", \"2.2\", \"3.3\", \"4.4\", \"<NA>\", \"<NA>\", \"<NA>\"),\n y_c = c(\"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"<NA>\", \"3.3\",\n \"7.6\", \"11.3\")), class = \"data.frame\", row.names = c(NA,\n-9L))\n" }, { "answer_id": 74502200, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 0, "selected": false, "text": "y_a y_b pivot_longer(df,cols = -(x:type)) %>% \n filter(value!=\"<NA>\") %>% \n pivot_wider(x)\n x y_a y_b y_c \n <int> <chr> <chr> <chr>\n1 1 1.3 2.2 3.3 \n2 2 2.7 3.3 7.6 \n3 3 4.4 4.4 11.3 \n pivot_wider(filter(pivot_longer(df,cols = -(x:type)), value!=\"<NA>\"),x)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74501949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20454809/" ]
74,502,077
<p>I want to be able to access and modify attributes of HTML elements of a page in my server side code (I am using ASP.NET Core Razor Pages 6.0).</p> <p>For example: a <code>.cshtml</code> file, I have a simple element like this:</p> <pre><code>&lt;div class=&quot;mb-3 mt-3&quot;&gt; &lt;label asp-for=&quot;User.firstname&quot; class=&quot;form-label&quot;&gt;First Name:&lt;/label&gt; &lt;input asp-for=&quot;User.firstname&quot; class=&quot;form-control&quot; placeholder=&quot;First Name&quot;&gt; &lt;/div&gt; </code></pre> <p>How do I access &amp; change attributes of the above <code>&lt;input&gt;</code> element inside the <code>OnGet</code> or <code>OnPost</code> server-side methods?</p> <p>I need to do so as I want to add a class to that <code>&lt;input&gt;</code> element, or make it read-only (depending on certain conditions in my server code).</p> <p>In older versions of .NET, I believe this was possible by giving an HTML element an ID, and writing runat=&quot;server&quot;. Then, one could access the element in the code-behind via its ID and change its attributes. How is this done now in Razor Pages? Should I not be able to do the same because of the asp-for tag helper which I used inn my code above? But how?</p> <p>Thank you for your help!</p>
[ { "answer_id": 74511958, "author": "Software Architect", "author_id": 15868779, "author_profile": "https://Stackoverflow.com/users/15868779", "pm_score": 1, "selected": false, "text": " <form method=\"post\">\n <div class=\"form-group\">\n <input name=\"title\" class=\"form-control\" placeholder=\"Type title here..\" />\n <button type=\"submit\" class=\"btn btn-primary\">Post</button>\n </form>\n public async Task<IActionResult> OnPostAsync(string title)\n {\n //do your stuff \n }\n" }, { "answer_id": 74513610, "author": "Rena", "author_id": 11398810, "author_profile": "https://Stackoverflow.com/users/11398810", "pm_score": -1, "selected": false, "text": "public class User\n{\n public string firstname { get; set; }\n}\n @page\n@model IndexModel\n<form method=\"post\">\n\n <div class=\"mb-3 mt-3\">\n <label asp-for=\"User.firstname\" class=\"form-label\">First Name:</label>\n <input asp-for=\"User.firstname\" class=\"form-control\" placeholder=\"First Name\">\n </div>\n <input type=\"submit\" value=\"Post\"/>\n\n</form>\n [BindProperty] public class IndexModel : PageModel\n{\n [BindProperty]\n public User User { get; set; }\n public void OnGet()\n {\n \n }\n public void OnPost()\n {\n //do your stuff.....\n }\n}\n public class IndexModel : PageModel\n{\n\n public User User { get; set; }\n public void OnGet()\n {\n \n }\n public void OnPost(User User)\n {\n\n }\n \n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15599708/" ]
74,502,083
<p>I am trying to create a login functionality for my Reactjs Webiste using Nodejs express backend.</p> <p>I want to set a JWT token when the user tries to log in and update that token in my mongoDB database and then verify the token on the frontend and save it to localStorage.</p> <p>However, when the user tries to log in after registration, it returns back the result without the token, and thus not allowing the user to log in, unless he clicks the login button again, then my code would generate and update the user with the JWT token.</p> <p>Why is this behavior happening? Why is the first response only returning the found user from the <code>findOne()</code> operation when i am resolving the result from the <code>findOneAndUpdate</code> operation?</p> <p>Here is my code:</p> <p>Auth Controller:</p> <pre><code>login(params) { params.email = params.email.toLowerCase(); return new Promise((resolve, reject) =&gt; { db.collection(&quot;Users&quot;).findOne({ email: params.email }).then((response) =&gt; { console.log(response) if(response) { bcrypt.compare(params.password, response.password, (err, success) =&gt; { if(success) { let token = jwt.sign({ name: response.name, id: response._id }, proccess.env.JWT_SECRET); db.collection(&quot;Users&quot;).findOneAndUpdate({ email: params.email }, { $set: { token: token, lastLogin: new Date() }, }, function (e, s) { if(e) { console.log(e) reject(e) } else { console.log(&quot;updated&quot;) resolve(s) } }) } else { reject({msg: 'Incorrect email or password.'}) } }) } else { reject({msg: 'cannot log in user'}); } }) }) } </code></pre> <p>Auth Router:</p> <pre><code>router.post('/login', (req, res) =&gt; { let User = new models.User() let processes = []; processes.push(function (callback) { User.login(req.body).then(function (response) { callback(null, response); }, function (error) { console.log(error) callback(error); }); }); async.waterfall(processes, function (error, data) { if (!error) { return res.json({ statusCode: 200, msg: 'User logged in successfully.', result: data }); } else { return res.json({ statusCode: 401, msg: 'Cannot login user.', error: error }); } }); }) </code></pre> <p>React Login.js:</p> <pre><code>const login = () =&gt; { axios.post('/login', data).then(async (response) =&gt; { console.log(response) if(response &amp;&amp; response.data.result.value.token ) { localStorage.setItem(&quot;authUser&quot;, JSON.stringify(response.data.result.value.token)) history.push(&quot;/&quot;) console.log(response.data.result) } else { console.log(&quot;ERROR&quot;) } }) } </code></pre>
[ { "answer_id": 74577527, "author": "WolverinDEV", "author_id": 7588455, "author_profile": "https://Stackoverflow.com/users/7588455", "pm_score": 1, "selected": false, "text": "findOneAndUpdate returnNewDocument: true db.collection(\"Users\").findOneAndUpdate({\n email: params.email\n }, {\n $set: { token: token, lastLogin: new Date() },\n }, {\n returnNewDocument: true\n }, function (e, s) {\n if(e) {\n console.log(e)\n reject(e)\n } else {\n console.log(\"updated\")\n resolve(s)\n }\n })\n async await" }, { "answer_id": 74628285, "author": "Nicholi Jin", "author_id": 14979586, "author_profile": "https://Stackoverflow.com/users/14979586", "pm_score": 0, "selected": false, "text": "async login(params) {\n params.email = params.email.toLowerCase();\n\n try {\n const user = await db.collection(\"Users\").findOne({ email: params.email });\n\n if(!user) {\n throw {message: \"Incorrect email\"}\n }\n\n const vaild = await bcrypt.compare(params.password, user.password);\n \n if(!valid) {\n throw {msg: 'Incorrect email or password.'}\n }\n\n let token = jwt.sign({\n name: user.name,\n id: user._id\n }, proccess.env.JWT_SECRET);\n\n return db.collection(\"Users\").findOneAndUpdate({\n email: params.email\n }, {\n $set: { token: token, lastLogin: new Date() },\n }, {new: true}); //FOR THE RETRIEVE NEW UPDATEs FROM MONGODB\n \n } catch(e) {\n throw e\n }\n}\n" }, { "answer_id": 74638500, "author": "Jeevan thomas koshy", "author_id": 5245533, "author_profile": "https://Stackoverflow.com/users/5245533", "pm_score": 0, "selected": false, "text": "login(params) {\n params.email = params.email.toLowerCase();\n\n return new Promise((resolve, reject) => {\n // Find the user with the specified email\n db.collection(\"Users\").findOne({ email: params.email }).then((response) => {\n\n console.log(response);\n\n // If the user exists, update their token and last login time\n if (response) {\n bcrypt.compare(params.password, response.password, (err, success) => {\n if (success) {\n let token = jwt.sign({\n name: response.name,\n id: response._id,\n }, process.env.JWT_SECRET);\n\n // Update the user's token and last login time in the database\n db.collection(\"Users\").findOneAndUpdate(\n { email: params.email },\n { $set: { token: token, lastLogin: new Date() } },\n function (e, s) {\n if (e) {\n console.log(e);\n reject(e);\n } else {\n console.log(\"updated\");\n // Return the updated user with the new token\n resolve(s);\n }\n }\n );\n } else {\n reject({ msg: \"Incorrect email or password.\" });\n }\n });\n } else {\n reject({ msg: \"cannot log in user\" });\n }\n });\n });\n}\n" }, { "answer_id": 74645379, "author": "Meichan", "author_id": 20658432, "author_profile": "https://Stackoverflow.com/users/20658432", "pm_score": 0, "selected": false, "text": "findOne() findOneAndUpdate() findOneAndUpdate() findOneAndUpdate() findOne() findOne() findOneAndUpdate() // Auth Controller:\n\nlogin(params) {\n params.email = params.email.toLowerCase();\n\n return new Promise((resolve, reject) => {\n bcrypt.compare(params.password, response.password, (err, success) => {\n if (success) {\n let token = jwt.sign({\n name: response.name,\n id: response._id\n }, proccess.env.JWT_SECRET);\n\n db.collection(\"Users\").findOneAndUpdate({\n email: params.email\n }, {\n $set: { token: token, lastLogin: new Date() },\n }, function (e, s) {\n if (e) {\n console.log(e)\n reject(e)\n } else {\n console.log(\"updated\")\n resolve(s.value)\n }\n })\n } else {\n reject({ msg: 'Incorrect email or password.' })\n }\n })\n })\n}\n // React Login.js:\n\nconst login = () => {\n axios.post('/login', data).then(async (response) => {\n if (response && response.data.result.token) {\n localStorage.setItem(\"authUser\", JSON.stringify(response.data.result.token))\n history.push(\"/\")\n } else {\n console.log(\"ERROR\")\n }\n })\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15197645/" ]
74,502,129
<p>I am trying print 3 things in straight line like name, age and wages.</p> <p>like this</p> <pre><code>Graham 47 500 Jess 47 250 Dave 23 100 </code></pre> <p>type here</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace General_Employee_Data { class Program { static void Main(string[] args) { var Namelist = new string[2, 2, 3] { { &quot;Graham&quot;, &quot;47&quot;, &quot;500&quot; }, { &quot;Jess&quot; , &quot;47&quot;, &quot;250&quot; }, { &quot;David&quot;, &quot;23&quot;, &quot;100&quot; }, }; for (int i = 0; i &lt; 3; i++) { Console.WriteLine(Namelist[i, i, i]); } } } </code></pre> <p>This isn't homework as I doing it to practise my C#, I seem made it more complex than simple.</p> <p>I trying get arrays names, age , wages on the screen.</p>
[ { "answer_id": 74502159, "author": "finix", "author_id": 17105703, "author_profile": "https://Stackoverflow.com/users/17105703", "pm_score": 0, "selected": false, "text": "Console.WriteLine(Namelist[i].ToString());\n" }, { "answer_id": 74502273, "author": "Prasad Telkikar", "author_id": 6299857, "author_profile": "https://Stackoverflow.com/users/6299857", "pm_score": 2, "selected": false, "text": "Console.WriteLine(Namelist[i][0] + \"\\t\" + Namelist[i][1] + \"\\t\" + Namelist[i][2]);\n string.Join() Console.WriteLine(string.Join(@\"\\t\", Namelist[i]));\n public class Employee\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public int Wages { get; set; }\n\n\n public Employee(string name, int age, int wages)\n {\n this.Name = name;\n this.Age = age;\n this.Wages = wages;\n }\n\n //This will help you to convert, Employee object to expected string\n public override string ToString()\n {\n return $\"{this.Name} \\t {this.Age} \\t {this.Wages}\";\n }\n}\n List<Employee> List<Employee> employees = new List<Employee>()\n{\n new Employee(\"Graham\", 47, 500),\n new Employee(\"Jess\", 47, 250),\n new Employee(\"Dave\", 23, 100)\n}\n foreach(var employee in employees)\n Console.WriteLine(employee);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10054332/" ]
74,502,143
<p>The context here is that I'm comparing the values of two columns—the key and the date. If the criterion is met, we will now create a new column with the flag = Y else &quot;&quot;</p> <p>Condition: if key are matching and date in df1 &gt; date in df2 then &quot;Y&quot; else &quot;&quot;</p> <p>We will therefore iterate through all of the rows in df1 and see if the key matches in df2, at which point we will check dateF and date for that row to see if it is greater, and if it is, we will save &quot;Y&quot; in a new column flag.</p> <p>Update 1: There can be multiple rows in df1 with same key and different dates</p> <p>Df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Key</th> <th>Date</th> <th>Another</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>2022-03-04</td> <td>Apple</td> <td></td> </tr> <tr> <td>321</td> <td>2022-05-01</td> <td>Red</td> <td></td> </tr> <tr> <td>234</td> <td>2022-07-08</td> <td>Green</td> <td></td> </tr> </tbody> </table> </div> <p>Df2:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Key</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>2022-03-01</td> </tr> <tr> <td>321</td> <td>2022-05-01</td> </tr> <tr> <td>234</td> <td>2022-07-01</td> </tr> </tbody> </table> </div> <p>Expected O/P: Explanation: as we can see first row and 3rd row key are matching and the DateF in df1 &gt; Date in df2 so Y</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Key</th> <th>Date</th> <th>Another</th> <th>Flag</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>2022-03-04</td> <td>Apple</td> <td>Y</td> </tr> <tr> <td>321</td> <td>2022-05-01</td> <td>Red</td> <td></td> </tr> <tr> <td>234</td> <td>2022-07-08</td> <td>Green</td> <td>Y</td> </tr> </tbody> </table> </div> <p>Code to create all dfs:</p> <pre><code>import pandas as pd data = [[123, pd.to_datetime('2022-03-04 '),'Apple'], [321, pd.to_datetime('2022-05-01 '),'Red'], [234, pd.to_datetime('2022-07-08 '),'Green']] df1 = pd.DataFrame(data, columns=['Key', 'DateF', 'Another']) #df2 data1 = [[123, pd.to_datetime('2022-03-01 ')], [321, pd.to_datetime('2022-05-01 ')], [234, pd.to_datetime('2022-07-01 ')]] df2 = pd.DataFrame(data1, columns=['Key', 'Date']) </code></pre> <p>Have tried this but i think i am going wrong.</p> <pre><code>for i in df1.Key.unique(): df1.loc[(df1[i] == df2[i]) &amp; (r['DateF'] &gt; df2['Date]), &quot;Flag&quot;] = &quot;Y&quot; </code></pre> <p>Thank You!</p>
[ { "answer_id": 74502244, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "pandas.Series.gt pandas.DataFrame.loc df1.loc[df1['Date'].gt(df2['Date']), \"Flag\"]= \"Y\"\n print(df1)\n\n Key Date Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red NaN\n2 234 2022-07-08 Green Y\n" }, { "answer_id": 74502292, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "final=df1.merge(df2,left_on='Key',right_on='Key',how='left')\nfinal.loc[final['DateF'] > final['Date'], \"Flag\"]=\"Y\"\nfinal=final.drop(['Date'],axis=1)\n\n Key DateF Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red \n2 234 2022-07-08 Green Y\n\n" }, { "answer_id": 74502329, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "ref_dates = dict(zip(df2.Key,df2.Date))\ndf1['Flag'] = ['Y' if date>ref_dates.get(key,'0000-00-00') else '' for key,date in zip(df1.Key,df1.DateF)]\n ref_dates df2 df1 DateF" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16187262/" ]
74,502,145
<p>I'm solving some exercises from a book and now I'm having some difficulties: In this exercise I shall implement Card as an instance of the class Ord. But I don't know how exactly I could implement it, so I would appreciate any help.</p> <p>My code so far looks like this:</p> <pre><code>data Suit = Diamond | Club | Spade | Heart data Rank = Seven | Eight | Nine | Ten | Jack | Queen | King | Ace data Card = Card Suit Rank instance Ord Card where .... </code></pre> <p>Now I don't know how exactly to implement this and I would very much like to understand it. Thanks in advance for the explanations.</p>
[ { "answer_id": 74502244, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "pandas.Series.gt pandas.DataFrame.loc df1.loc[df1['Date'].gt(df2['Date']), \"Flag\"]= \"Y\"\n print(df1)\n\n Key Date Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red NaN\n2 234 2022-07-08 Green Y\n" }, { "answer_id": 74502292, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "final=df1.merge(df2,left_on='Key',right_on='Key',how='left')\nfinal.loc[final['DateF'] > final['Date'], \"Flag\"]=\"Y\"\nfinal=final.drop(['Date'],axis=1)\n\n Key DateF Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red \n2 234 2022-07-08 Green Y\n\n" }, { "answer_id": 74502329, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "ref_dates = dict(zip(df2.Key,df2.Date))\ndf1['Flag'] = ['Y' if date>ref_dates.get(key,'0000-00-00') else '' for key,date in zip(df1.Key,df1.DateF)]\n ref_dates df2 df1 DateF" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,502,158
<p>I have a web story that has cencored word in it with asterix</p> <p>right now i'm doing it with a simple and dumb str.replace</p> <p>but as you can imagine this is a pain and I need to search in the text to find all instance of the censoring</p> <p>here is bastard instance that are capitalized, plurial and with asterix in different places</p> <pre><code>toReplace = toReplace.replace(&quot;b*stard&quot;, &quot;bastard&quot;) toReplace = toReplace.replace(&quot;b*stards&quot;, &quot;bastards&quot;) toReplace = toReplace.replace(&quot;B*stard&quot;, &quot;Bastard&quot;) toReplace = toReplace.replace(&quot;B*stards&quot;, &quot;Bastards&quot;) toReplace = toReplace.replace(&quot;b*st*rd&quot;, &quot;bastard&quot;) toReplace = toReplace.replace(&quot;b*st*rds&quot;, &quot;bastards&quot;) toReplace = toReplace.replace(&quot;B*st*rd&quot;, &quot;Bastard&quot;) toReplace = toReplace.replace(&quot;B*st*rds&quot;, &quot;Bastards&quot;) </code></pre> <p>is there a way to compare all word with &quot;*&quot; (or any other replacement character) to an already compiled dict and replace them with the uncensored version of the word ? maybe regex but I don't think so</p>
[ { "answer_id": 74502244, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "pandas.Series.gt pandas.DataFrame.loc df1.loc[df1['Date'].gt(df2['Date']), \"Flag\"]= \"Y\"\n print(df1)\n\n Key Date Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red NaN\n2 234 2022-07-08 Green Y\n" }, { "answer_id": 74502292, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "final=df1.merge(df2,left_on='Key',right_on='Key',how='left')\nfinal.loc[final['DateF'] > final['Date'], \"Flag\"]=\"Y\"\nfinal=final.drop(['Date'],axis=1)\n\n Key DateF Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-05-01 Red \n2 234 2022-07-08 Green Y\n\n" }, { "answer_id": 74502329, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "ref_dates = dict(zip(df2.Key,df2.Date))\ndf1['Flag'] = ['Y' if date>ref_dates.get(key,'0000-00-00') else '' for key,date in zip(df1.Key,df1.DateF)]\n ref_dates df2 df1 DateF" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16652379/" ]
74,502,237
<p>I have this code here which supposedly builds a list from a document in firebase, which ultimately fails as it always goes to <code>return loading</code>. From what I know, it has something to do with it being a future and I think I am accessing it wrongly. I have tried getting the output as Text and it works, but as a a listview, it does not.</p> <p>I also tried making a function with async on it but the app still outputs loading. Any help would be appreciated.</p> <pre><code>Widget showFriend() { CollectionReference users = FirebaseFirestore.instance.collection('todos'); return FutureBuilder&lt;DocumentSnapshot&gt;( future: users.doc(documentId).get(), builder: (BuildContext context, AsyncSnapshot&lt;DocumentSnapshot&gt; snapshot) { if (snapshot.hasError) { return Text(&quot;Something went wrong&quot;); } if (snapshot.hasData &amp;&amp; !snapshot.data!.exists) { return Text(&quot;Document does not exist&quot;); } if (snapshot.connectionState == ConnectionState.done) { Map&lt;String, dynamic&gt; data = snapshot.data!.data() as Map&lt;String, dynamic&gt;; List&lt;dynamic&gt; fren = []; void waitList() async { List&lt;dynamic&gt; temp; temp = await (data['friends']); fren = temp; } waitList(); fren = List.from(data['friends']); print(fren); if (fren.length &gt; 0) { ListView.builder( itemCount: fren.length, itemBuilder: (context, index) { return ListTile(title: Text('${fren[index]}')); }); } } return Text(&quot;loading&quot;); }); } </code></pre>
[ { "answer_id": 74502308, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " Widget showFriend() {\n CollectionReference users =\n FirebaseFirestore.instance.collection('todos');\n // ignore: newline-before-return\n return FutureBuilder<DocumentSnapshot>(\n // future: users.doc(documentId).get(),\n // ignore: prefer-trailing-comma\n builder:\n (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {\n if (snapshot.hasError) {\n return Text(\"Something went wrong\");\n }\n\n if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasData) {\n if (!snapshot.data!.exists) {\n return Text(\"Document does not exist\");\n } else {\n Map<String, dynamic> data =\n snapshot.data!.data() as Map<String, dynamic>;\n List<dynamic> fren = [];\n\n List<dynamic> temp;\n temp = data['friends'];\n fren = temp;\n\n fren = List.from(data['friends']);\n print(fren);\n if (fren.length > 0) {\n ListView.builder(\n itemCount: fren.length,\n itemBuilder: (context, index) {\n return ListTile(title: Text('${fren[index]}'));\n });\n }\n }\n }\n }\n return Text(\"loading\");\n },\n );\n}\n" }, { "answer_id": 74502358, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": true, "text": "return ListView if (fren.length > 0) {\n return ListView.builder( //here\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15929283/" ]
74,502,335
<p>I am trying to run a Gstreamer plugin written to run <a href="https://github.com/voidmainvoid95/gst-nvmaxine" rel="nofollow noreferrer">NVIDIA Maxine filters</a> through the pipeline.</p> <p>I keep getting <code>no element &quot;nvmaxinevideofx&quot;</code>, and I'm wondering if there is anything fundamentally wrong with my approach or if I'm just making a mistake somewhere.</p> <p>I am super new to Gstreamer and any help would be much appreciated.</p> <p>I am running on Ubuntu 20.04 through WSL.</p> <p>I managed to build the plugin files successfully, but no matter how I add the plugin path to the build directory containing the <code>.so</code> files, it's not getting picked up by either <code>gst-launch</code> or <code>gst-inspect</code>.</p> <p>I tried both adding to the <code>GST_PLUGIN_PATH</code> variable and as an argument to <code>gst-launch</code> with <code>--gst-plugin-path</code>.</p> <p>I have also managed to get Maxine installed at <code>/usr/local/VideoFX</code>.</p> <p>I have also managed to build the <code>gst-template</code> plugin from the official tutorials and run it successfully with:</p> <pre><code>gst-launch-1.0 -v -m --gst-plugin-path=/mnt/d/projects/stream/gst-template/build/gst-plugin/ fakesrc ! my_filter ! fakesink silent=TRUE </code></pre> <p>But when I try to run the same thing with the appropriate parameters for this plugin it returns <code>no element &quot;nvmaxinevideofx&quot;</code>:</p> <pre><code>gst-launch-1.0 -v -m --gst-plugin-path=/mnt/d/projects/stream/gst-nvmaxine/build/ fakesrc ! nvmaxinevideofx ! fakesink silent=TRUE </code></pre>
[ { "answer_id": 74502308, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " Widget showFriend() {\n CollectionReference users =\n FirebaseFirestore.instance.collection('todos');\n // ignore: newline-before-return\n return FutureBuilder<DocumentSnapshot>(\n // future: users.doc(documentId).get(),\n // ignore: prefer-trailing-comma\n builder:\n (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {\n if (snapshot.hasError) {\n return Text(\"Something went wrong\");\n }\n\n if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasData) {\n if (!snapshot.data!.exists) {\n return Text(\"Document does not exist\");\n } else {\n Map<String, dynamic> data =\n snapshot.data!.data() as Map<String, dynamic>;\n List<dynamic> fren = [];\n\n List<dynamic> temp;\n temp = data['friends'];\n fren = temp;\n\n fren = List.from(data['friends']);\n print(fren);\n if (fren.length > 0) {\n ListView.builder(\n itemCount: fren.length,\n itemBuilder: (context, index) {\n return ListTile(title: Text('${fren[index]}'));\n });\n }\n }\n }\n }\n return Text(\"loading\");\n },\n );\n}\n" }, { "answer_id": 74502358, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": true, "text": "return ListView if (fren.length > 0) {\n return ListView.builder( //here\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436740/" ]
74,502,349
<p>I am new to AWS dynamodb, lambda. i have pretty good knowledge in RDB(MySQL).</p> <p>here is my sample table</p> <pre><code>partitian key sort key attribute Device TimeStamp REMARKS D1 2022-12-12 12:13:14 hello D1 2022-12-12 12:14:14 testing D2 2022-12-12 12:18:14 hello D2 2022-12-12 12:19:14 testing D3 2022-11-12 12:13:14 hello D3 2022-12-12 12:14:14 testing </code></pre> <p>i want to extract following output using python boto3 in lambda function using query statement.</p> <p>Latest timestamp value of each'partitian key' Output</p> <pre><code>D1 2022-12-12 12:14:14 testing D2 2022-12-12 12:19:14 testing D3 2022-12-12 12:14:14 testing </code></pre> <p>i tried using aws lambda tutorial but i could get all the data using scan method</p>
[ { "answer_id": 74502308, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": " Widget showFriend() {\n CollectionReference users =\n FirebaseFirestore.instance.collection('todos');\n // ignore: newline-before-return\n return FutureBuilder<DocumentSnapshot>(\n // future: users.doc(documentId).get(),\n // ignore: prefer-trailing-comma\n builder:\n (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {\n if (snapshot.hasError) {\n return Text(\"Something went wrong\");\n }\n\n if (snapshot.connectionState == ConnectionState.done) {\n if (snapshot.hasData) {\n if (!snapshot.data!.exists) {\n return Text(\"Document does not exist\");\n } else {\n Map<String, dynamic> data =\n snapshot.data!.data() as Map<String, dynamic>;\n List<dynamic> fren = [];\n\n List<dynamic> temp;\n temp = data['friends'];\n fren = temp;\n\n fren = List.from(data['friends']);\n print(fren);\n if (fren.length > 0) {\n ListView.builder(\n itemCount: fren.length,\n itemBuilder: (context, index) {\n return ListTile(title: Text('${fren[index]}'));\n });\n }\n }\n }\n }\n return Text(\"loading\");\n },\n );\n}\n" }, { "answer_id": 74502358, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": true, "text": "return ListView if (fren.length > 0) {\n return ListView.builder( //here\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549507/" ]
74,502,366
<p><strong>JSON file data fraction:</strong></p> <pre><code>{ &quot;categories&quot;: [ { &quot;id&quot;: 1, &quot;category_slug&quot;: &quot;food_supplements&quot;, &quot;title&quot;: &quot;Food Supplements&quot;, &quot;image&quot;: &quot;/../../public/images/foodSupplements.png&quot;, } ] } </code></pre> <p><strong>Component data fraction that renders the image:</strong></p> <pre><code>{ Data.categories.map((category, idx) =&gt; { return ( &lt;div key={idx} className=&quot;header-categories-container&quot;&gt; &lt;Image className=&quot;header-btn-image&quot; src={category.image} alt=&quot;btn-img&quot; width=&quot;64&quot; height=&quot;64&quot;&gt;&lt;/Image&gt; &lt;Link href={`/${category.route}`}&gt; &lt;button className=&quot;header-category-button&quot;&gt;{category.title}&lt;/button&gt; &lt;/Link&gt; &lt;/div&gt; ) }) } </code></pre> <p>The error that occurs in the console is the following: The requested resource isn't a valid image for <code>/../../public/images/foodSupplements.png received text/html; charset=utf-8</code></p> <p>Tried putting images into different sources, still didn't work. Tried to import with src=require(...), still the same error.</p>
[ { "answer_id": 74502386, "author": "codinn.dev", "author_id": 15755662, "author_profile": "https://Stackoverflow.com/users/15755662", "pm_score": 2, "selected": true, "text": "{\n \"categories\": [\n {\n \"id\": 1,\n \"category_slug\": \"food_supplements\",\n \"title\": \"Food Supplements\",\n \"image\": \"/images/foodSupplements.png\",\n }\n ]\n}\n images public /images/foodSupplements.png public/images/foodSupplements.png" }, { "answer_id": 74502388, "author": "Mohammed Shahed", "author_id": 19067773, "author_profile": "https://Stackoverflow.com/users/19067773", "pm_score": 0, "selected": false, "text": "public \"image\": \"/foodSupplements.png\"" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19274770/" ]
74,502,375
<p>Let's say I have this dataframe</p> <pre><code>df &lt;- structure(list(A = c(25, 25, 25, 50, 50, 50, 100, 100, 100, 250, 250, 250), R = c(&quot;R1&quot;, &quot;R2&quot;, &quot;R3&quot;, &quot;R1&quot;, &quot;R2&quot;, &quot;R3&quot;, &quot;R1&quot;, &quot;R2&quot;, &quot;R3&quot;, &quot;R1&quot;, &quot;R2&quot;, &quot;R3&quot;), ACI = c(2.75769, 3.59868, 3.00425, 1.90415, 2.19912, 2.01439, 1.34013, 1.45594, 1.3738, 0.84241, 0.87391, 0.85184 ), PB = c(3.06259, 4.10288, 3.40414, 2.00337, 2.32796, 2.13138, 1.37404, 1.49467, 1.40867, 0.84817, 0.88002, 0.85838 ), NB = c(3.13425, 4.22754, 3.49041, 2.03281, 2.36812, 2.16289, 1.3858, 1.5086, 1.42187, 0.85346, 0.88572, 0.86346 ), Bca = c(2.65087, 3.3918, 2.86767, 1.89719, 2.20208, 2.00181, 1.35534, 1.49656, 1.38895, 0.85497, 0.9015, 0.86487 ), SB = c(3.33211, 4.42798, 3.73011, 2.12197, 2.48144, 2.266, 1.41635, 1.54522, 1.45326, 0.85775, 0.89055, 0.86863 ), `round(2)` = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)), class = &quot;data.frame&quot;, row.names = c(NA, -12L)) </code></pre> <p>I would like to draw a line graph with multiple X-axis values, something like a dodged bar graph, but with a line graph. The graph should look something like this: <a href="https://i.stack.imgur.com/KJFpy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KJFpy.png" alt="Graph Image" /></a></p> <p>My attempt until now is this:</p> <pre><code> df %&gt;% pivot_longer(ACI:SB) %&gt;% mutate(across(where(is.character), as.factor)) %&gt;% ggplot(aes(x = R, y = value, group=name)) + geom_line()+ facet_wrap(~A, nrow=1, strip.position=&quot;bottom&quot;) </code></pre> <p>This code is currently outputting this: <a href="https://i.stack.imgur.com/fTJMN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fTJMN.png" alt="Wrong Output" /></a></p> <p>I'd greatly appreciate any help, thanks</p>
[ { "answer_id": 74502529, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ndf %>% \n pivot_longer(ACI:SB) %>% \n mutate(across(where(is.character), as.factor)) %>% \n ggplot(aes(x = A, y = value, group = name, color = name)) +\n geom_point()+\n geom_line()+\n facet_wrap(.~R, nrow = 1, strip.position = \"bottom\")+\n theme_classic()\n labs(x=\"Test/Train\", y=\"Score\", fill=\"Segment Length\") +\n theme(panel.spacing = unit(0, \"lines\"), strip.placement = \"outside\")\n" }, { "answer_id": 74502653, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 2, "selected": false, "text": "interaction annotate library(dplyr)\nlibrary(ggplot2)\nlibrary(ggthemes)\nlibrary(tidyr)\n\ndf %>% \n pivot_longer(ACI:SB) %>% \n mutate(across(where(is.character), as.factor)) %>% \n ggplot(aes(x = interaction(A, R), y = value, group=name)) +\n geom_line(aes(color = name)) +\n geom_point(aes(color = name)) +\n coord_cartesian(ylim = c(0, 5), expand = FALSE, clip = \"off\") +\n annotate(geom = \"text\", x = seq_len(nrow(df)), y = -0.1, label = df$R, size = 3) +\n annotate(geom = \"text\", x = 2 + 3 * (0:3), y = -0.3, label = unique(df$A), size = 3) +\n theme_excel_new() +\n theme(plot.margin = unit(c(1, 1, 4, 1), \"lines\"),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n panel.grid.major.x = element_blank(),\n panel.grid.minor.x = element_blank(),\n legend.position = c(0.5, -0.15), legend.direction = 'horizontal')\n" }, { "answer_id": 74502730, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "df %>% \n pivot_longer(ACI:SB) %>% \n ggplot(aes(rep(1:nrow(df), each = length(value)/nrow(df)), \n value, col = name)) + \n geom_line() + \n geom_point() + \n xlab(\"\") + \n scale_x_continuous(breaks = c(1:nrow(df)), labels = paste(df$R, df$A))\n" }, { "answer_id": 74502764, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "minor_breaks scale_x_continuous prism.ticks.length.x= theme minor_breaks= scale_x_continuous library(dplyr)\nlibrary(tidyr)\nlibrary(ggplot2)\nlibrary(ggprism)\n\nxlabs <- with(df, ifelse(R == \"R2\", paste(R, A, sep = \"\\n\"), R))\nbreaks <- seq_along(xlabs)\n\ndf %>% \n mutate(x = 1:n()) %>%\n pivot_longer(ACI:SB) %>% \n ggplot(aes(x, value, col = name)) +\n geom_line(size = 2) +\n xlab(\"\") +\n ylab(\"\") +\n theme(prism.ticks.length.x = unit(25, \"pt\"),\n legend.position = \"bottom\") +\n scale_x_continuous(guide = \"prism_minor\", \n limits = range(breaks), \n breaks = breaks, \n labels = xlabs,\n minor_breaks = breaks[xlabs == \"R3\"] + .5)\n \n df df <-\nstructure(list(A = c(25, 25, 25, 50, 50, 50, 100, 100, 100, 250, \n250, 250), R = c(\"R1\", \"R2\", \"R3\", \"R1\", \"R2\", \"R3\", \"R1\", \"R2\", \n\"R3\", \"R1\", \"R2\", \"R3\"), ACI = c(2.75769, 3.59868, 3.00425, 1.90415, \n2.19912, 2.01439, 1.34013, 1.45594, 1.3738, 0.84241, 0.87391, \n0.85184), PB = c(3.06259, 4.10288, 3.40414, 2.00337, 2.32796, \n2.13138, 1.37404, 1.49467, 1.40867, 0.84817, 0.88002, 0.85838\n), NB = c(3.13425, 4.22754, 3.49041, 2.03281, 2.36812, 2.16289, \n1.3858, 1.5086, 1.42187, 0.85346, 0.88572, 0.86346), Bca = c(2.65087, \n3.3918, 2.86767, 1.89719, 2.20208, 2.00181, 1.35534, 1.49656, \n1.38895, 0.85497, 0.9015, 0.86487), SB = c(3.33211, 4.42798, \n3.73011, 2.12197, 2.48144, 2.266, 1.41635, 1.54522, 1.45326, \n0.85775, 0.89055, 0.86863), `round(2)` = c(2, 2, 2, 2, 2, 2, \n2, 2, 2, 2, 2, 2)), class = \"data.frame\", row.names = c(NA, -12L\n))\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13349539/" ]
74,502,393
<p>I have a long string stored in a variable in Rust. I often remove some characters from its front with a <code>drain</code> method and use the value returned from it:</p> <pre class="lang-rust prettyprint-override"><code>my_str.drain(0..i).collect::&lt;String&gt;(); </code></pre> <p>The problem is, that draining from this string is done <em>really often</em> in the program and it's slowing it down a lot (it takes ~99.6% of runtime). This is a very expensive operation, since every time, the entire string has to be moved left in the memory.</p> <p>I do not drain from the end of the string at all (which should be much faster), just from the front.</p> <p>How can I make this more efficient? Is there some alternative to <code>String</code>, that uses a different memory layout, which would be better for this use case?</p>
[ { "answer_id": 74502737, "author": "FireFragment", "author_id": 14559107, "author_profile": "https://Stackoverflow.com/users/14559107", "pm_score": 0, "selected": false, "text": "VecDeque<char> String pop_front drain" }, { "answer_id": 74503257, "author": "prog-fh", "author_id": 11527076, "author_profile": "https://Stackoverflow.com/users/11527076", "pm_score": 1, "selected": false, "text": "clone() use std::time::Instant;\n\nfn with_drain(mut my_str: String) -> usize {\n let mut total = 0;\n 'work: loop {\n for &i in [1, 2, 3, 4, 5].iter().cycle() {\n if my_str.len() < i {\n break 'work;\n }\n let s = my_str.drain(0..i).collect::<String>();\n total += s.len();\n }\n }\n total\n}\n\nfn with_slice(my_str: String) -> usize {\n let mut total = 0;\n let mut pos = 0;\n 'work: loop {\n for &i in [1, 2, 3, 4, 5].iter().cycle() {\n let next_pos = pos + i;\n if my_str.len() <= next_pos {\n break 'work;\n }\n let s = &my_str[pos..next_pos];\n pos = next_pos;\n total += s.len();\n }\n }\n total\n}\n\nfn main() {\n let my_str=\"I have a long string stored in a variable in Rust.\nI often remove some characters from its front with a drain method and use the value returned from it:\nmy_str.drain(0..i).collect::<String>();\nThe problem is, that draining from this string is done really often in the program and it's slowing it down a lot (it takes ~99.6% of runtime). This is a very expensive operation, since every time, the entire string has to be moved left in the memory.\nI do not drain from the end of the string at all (which should be much faster), just from the front.\nHow can I make this more efficient? Is there some alternative to String, that uses a different memory layout, which would be better for this use case?\n\".to_owned();\n let repeat = 1_000_000;\n let instant = Instant::now();\n for _ in 0..repeat {\n let _ = with_drain(my_str.clone());\n }\n let drain_duration = instant.elapsed();\n let instant = Instant::now();\n for _ in 0..repeat {\n let _ = with_slice(my_str.clone());\n }\n let slice_duration = instant.elapsed();\n println!(\"{:?} {:?}\", drain_duration, slice_duration);\n}\n/*\n$ cargo run --release\n Finished release [optimized] target(s) in 0.00s\n Running `target/release/prog`\n5.017018957s 310.466253ms\n*/\n" }, { "answer_id": 74503843, "author": "kmdreko", "author_id": 2189130, "author_profile": "https://Stackoverflow.com/users/2189130", "pm_score": 2, "selected": true, "text": "SharedString Str" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559107/" ]
74,502,451
<p>I want to limit number of rows in tableView say I want to show only 2 rows initially and if user clicks &quot;See All&quot; button then display all the rows. The data (array) for tableView is coming from CoreData. I have entered (saved) all the data in another ViewController, and fetching data on some another ViewController. There might be a case where data may be nil. Currently, I'm displaying all the rows just like --&gt; return array.count, but I have no idea how to achieve my condition ?</p>
[ { "answer_id": 74502509, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 2, "selected": true, "text": "var showAllRows = false\n numberOfRowsInSection func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showAllRows {\n return array.count\n } else {\n return min(2, array.count)\n }\n}\n showAllRows showAllRows = true\ntableView.reloadData()\n" }, { "answer_id": 74502875, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": " func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showMoreRows {\n return array.count\n } else if array.count > 2 {\n return 2\n } else {\n return 0\n } \n func showMoreRowsClick() {\n\nself.showMoreRows.toggle()\nself.tableView.reloadData()\n\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452635/" ]
74,502,469
<p>I wrote an extension function to get an element of an JSON object by its name:</p> <pre class="lang-kotlin prettyprint-override"><code>fun JSONObject.obj (name: String): JSONObject? = try { this.getJSONObject(name) } catch (e: JSONException) { null } </code></pre> <p>Now I want to extend this for nested JSON objects. I wrote the following:</p> <pre class="lang-kotlin prettyprint-override"><code>tailrec fun JSONObject.obj (first: String, vararg rest: String): JSONObject? = if (rest.size == 0) obj(first) else obj(first)?.obj(rest[0], *rest.drop(1).toTypedArray()) </code></pre> <p>But this looks quite inefficient to me.</p> <p>What is the best way to slice a <code>vararg</code> argument?</p>
[ { "answer_id": 74502509, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 2, "selected": true, "text": "var showAllRows = false\n numberOfRowsInSection func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showAllRows {\n return array.count\n } else {\n return min(2, array.count)\n }\n}\n showAllRows showAllRows = true\ntableView.reloadData()\n" }, { "answer_id": 74502875, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": " func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showMoreRows {\n return array.count\n } else if array.count > 2 {\n return 2\n } else {\n return 0\n } \n func showMoreRowsClick() {\n\nself.showMoreRows.toggle()\nself.tableView.reloadData()\n\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402322/" ]
74,502,472
<p>hope you are doing fine i came across to a problem of data array manipulation at starting there was not much manipulation required as work progressed now more data manipulation is required and i am running short on this(as a fresher early days of my career problem explanation - as data i am receiving an array of object and each object contains another array of information (key-value pair) and that array also contains another array of information(key value pair ) and requirement is to i have to loop main data object-item with respect to length of deep nested array and display them on front except this i have done the most part. i am attaching a sample code of my problem below i am requesting you guys to provide solution for this issue</p> <p>`</p> <pre><code>import React, { useState } from &quot;react&quot;; const data = [ { id: 1, name: &quot;Something Goes here&quot;, address: &quot;Earth&quot;, arr1: [ { newId: 1, title: &quot;Title 1&quot;, midName: &quot;Nothing&quot;, arr2: [ { subId: 1, goes: &quot;Hello&quot;, ollo: &quot;Not what you think&quot;, }, { subId: 2, goes: &quot;Hello 2&quot;, ollo: &quot;Not what you&quot;, }, ], }, ], }, { id: 2, name: &quot;Something Goes&quot;, address: &quot;Mars&quot;, arr1: [ { newId: 3, title: &quot;Title sddsdsad&quot;, midName: &quot;Nothing&quot;, arr2: [ { subId: 2, goes: &quot;Hello adasdasdasd&quot;, ollo: &quot;Not what you think asdasdasdawd&quot;, }, { subId: 2, goes: &quot;Hello 2&quot;, ollo: &quot;Not what you asdasasd&quot;, }, ], }, ], }, ]; const App = () =&gt; { const [dummy, setDummy] = useState([]); let dummyArr = [], tempObj, temp; const tempFunc = () =&gt; { for (let i = 0; i &lt; data.length; i++) { for (let j = 0; j &lt; data[i].arr1; j++) { for (let k = 0; k &lt; data[i].arr1[j].arr2; k++) { temp = data[i].arr1[j].arr2[k]; delete data[i].arr1[j].arr2[k]; tempObj = { ...temp ,...data[i], }; dummyArr.push(tempObj); tempObj = {}; console(&quot;tempObj --&gt;&quot;, tempObj); } } } }; console.log(&quot;dummyArr&quot;, dummyArr); return ( &lt;React.Fragment&gt; &lt;button&gt;Hello oooo&lt;/button&gt; &lt;/React.Fragment&gt; ); }; export default App; </code></pre> <p>expected result is to have both arrays pushed into main itemObject `</p> <pre><code>const sampleArray = [ { id: 2, name: &quot;Something Goes&quot;, address: &quot;Mars&quot;, newId: 3, title: &quot;Title sddsdsad&quot;, midName: &quot;Nothing&quot;, subId: 2, goes: &quot;Hello adasdasdasd&quot;, ollo: &quot;Not what you think asdasdasdawd&quot;, }, ]; </code></pre> <p><code> </code></p>
[ { "answer_id": 74502509, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 2, "selected": true, "text": "var showAllRows = false\n numberOfRowsInSection func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showAllRows {\n return array.count\n } else {\n return min(2, array.count)\n }\n}\n showAllRows showAllRows = true\ntableView.reloadData()\n" }, { "answer_id": 74502875, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": " func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showMoreRows {\n return array.count\n } else if array.count > 2 {\n return 2\n } else {\n return 0\n } \n func showMoreRowsClick() {\n\nself.showMoreRows.toggle()\nself.tableView.reloadData()\n\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17901031/" ]
74,502,512
<p>Acceptable input : any 9 digit number</p> <p>Not acceptable : <code>123456789</code> and <code>987654321</code></p> <p>I am using <code>[0-9]{9}</code> but I want extra condition as well</p>
[ { "answer_id": 74502509, "author": "HangarRash", "author_id": 20287183, "author_profile": "https://Stackoverflow.com/users/20287183", "pm_score": 2, "selected": true, "text": "var showAllRows = false\n numberOfRowsInSection func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showAllRows {\n return array.count\n } else {\n return min(2, array.count)\n }\n}\n showAllRows showAllRows = true\ntableView.reloadData()\n" }, { "answer_id": 74502875, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": " func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if showMoreRows {\n return array.count\n } else if array.count > 2 {\n return 2\n } else {\n return 0\n } \n func showMoreRowsClick() {\n\nself.showMoreRows.toggle()\nself.tableView.reloadData()\n\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549696/" ]
74,502,547
<p>I am creating an <code>AuthGuard</code> for my app..now when i try to load the component without getting <strong>logged in</strong> it should redirect me to the login page..But i am getting an error like following <a href="https://i.stack.imgur.com/dQvUy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dQvUy.png" alt="image error" /></a></p> <p>and nothing happens.</p> <p>I am throwing this error from my backend <code>{&quot;status&quot;:401,&quot;message&quot;:&quot;Auth Token Not found!&quot;}}</code> as there is no auth token</p> <p>The following is the code of my <code>AuthGuard</code></p> <pre><code>export class AuthGuardService implements CanActivate { constructor(private authService: AuthService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable&lt;boolean&gt; { return this.authService.checkLogin().pipe( map((data: HttpResponse) =&gt; { if (data.status == 200) { console.log(&quot;OUTPUT:&quot;, data) return true } else return false }), ) } } </code></pre> <p>The following is my function in <code>AuthService</code>:</p> <pre><code> public checkLogin():Observable&lt;HttpResponse&gt; { return this.http.get&lt;HttpResponse&gt;('http://localhost:5000/auth/check-login', { withCredentials: true }) } </code></pre> <p>Now how can i handle the errors like these and set a fallback value to <code>false</code> so if any error occurs then that route could not be accessed</p>
[ { "answer_id": 74503200, "author": "Nahom Ersom", "author_id": 9700487, "author_profile": "https://Stackoverflow.com/users/9700487", "pm_score": 2, "selected": false, "text": "this.http.get<HttpResponse>('http://localhost:5000/auth/check-login', { withCredentials: true }).pipe(\n catchError((error=>{\n \n this.getErrorMessage(error);\n return throwError(()=>error);\n }))\n )\n private getErrorMessage(error:HttpErrorResponse){\n \n switch(error.status){\n \n case 400:{\n return this.toast.error(`Bad Request :${JSON.stringify(error.error?.Message)}`,error.status.toString())\n }\n case 401:{\n return this.toast.error(`Unauthorized :${JSON.stringify(error.error?.Message)}`,error.status.toString())\n }\n case 403:{\n return this.toast.error(`Access Denied :${JSON.stringify(error.error?.Message)}`,error.status.toString())\n }\n case 500:{\n return this.toast.error(`Internal Server Error :${JSON.stringify(error.error?.Message)}`,error.status.toString())\n }\n case 404:{\n return this.toast.error(`Page Not Found :${JSON.stringify(error.error?.Message)}`,error.status.toString())\n }\n default:{\n return this.toast.error('Check your internet connection!');\n }\n }\n }\n" }, { "answer_id": 74508179, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 3, "selected": true, "text": "checkLogin() true checkLogin() false catchError() map() true this.router.navigate() of(false) export class AuthGuardService implements CanActivate {\n\n constructor(private authService: AuthService, private router: Router) { }\n\n canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {\n\n return this.authService.checkLogin().pipe(\n map(() => true),\n catchError(() => {\n this.router.navigate(['route-to-fallback-page']);\n return of(false);\n })\n );\n }\n}\n UrlTree canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {\n\n return this.authService.checkLogin().pipe(\n map(() => true),\n catchError(() => this.router.parseUrl('/route-to-fallback-page'))\n );\n }\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18480147/" ]
74,502,551
<p>I have written the following code to read a csv file into a multidimensional list which is working fine. The problem arise when I created a function to calculate the total of 2D list. This is happening because the numbers are in string inside the 2D list i.e.</p> <p>[['0', '0', '30', '2', '21', '13', '23'], .....,['8', '25', '1', '6', '21', '23', '0']].</p> <p>What would be the simplest way to convert the string elements into integers in a 2D list such as</p> <p>[[0, 0, 30, 2, 21, 13, 23],.....,[8, 25, 1, 6, 21, 23, 0]]</p> <p><strong>My code so far</strong></p> <pre><code>rows = 52 cols = 7 def populate2D(): with open(&quot;rainfall.csv&quot;,&quot;r&quot;) as file: lineArray = file.read().splitlines() matrix = [] for line in lineArray: matrix.append(line.split(&quot;,&quot;)) return matrix def display(matrix): print(matrix) def yearly(matrix): total = 0 for row in matrix: for value in row: total += value return total matrix = populate2D() display(matrix) total = yearly(matrix) print() print(&quot;Total rainfall for the year is &quot; + str(total)) </code></pre> <p><strong>csv file</strong></p> <pre><code>0,0,30,2,21,13,23 29,3,29,30,7,8,25 26,5,26,13,4,13,4 22,30,13,15,15,0,2 3,12,11,10,17,0,15 8,13,11,24,30,24,27 22,18,2,29,11,13,18 15,1,29,23,18,7,0 23,27,3,7,13,14,28 6,25,24,14,20,23,5 24,29,26,22,0,9,18 22,27,22,20,24,29,21 23,13,14,4,13,1,21 25,21,21,6,28,17,19 4,6,11,10,21,1,5 11,7,22,11,10,24,15 25,11,23,3,23,8,3 22,23,0,29,15,12,5 21,11,18,22,1,4,3 11,10,3,1,30,14,22 2,16,10,2,12,9,9 2,29,17,16,13,18,7 22,15,27,19,6,26,11 21,7,18,4,14,14,2 6,30,12,4,26,22,11 21,16,14,11,28,20,3 19,10,22,18,30,9,27 8,15,17,4,11,16,6 19,17,16,6,18,18,6 2,15,3,25,27,16,11 15,5,26,24,24,30,5 15,11,16,22,14,23,28 25,6,7,20,26,18,16 5,5,21,22,24,16,5 6,27,11,8,24,1,16 28,4,1,4,3,19,24 19,3,27,14,12,24,0 6,3,26,15,15,22,26 18,5,0,14,15,7,26 10,5,12,22,8,7,11 11,1,18,29,6,9,26 3,23,2,21,29,15,25 5,7,1,6,15,18,24 28,11,0,6,28,11,26 4,28,9,24,11,13,2 6,2,14,18,20,21,1 20,29,22,21,11,14,20 28,23,14,17,25,3,18 6,27,6,20,19,5,24 25,3,27,22,7,12,21 12,22,8,7,0,11,8 8,25,1,6,21,23,0 </code></pre> <p><strong>output</strong></p> <pre><code>$ python rainfall.py [['0', '0', '30', '2', '21', '13', '23'], ['29', '3', '29', '30', '7', '8', '25'], ['26', '5', '26', '13', '4', '13', '4'], ['22', '30', '13', '15', '15', '0', '2'], ['3', '12', '11', '10', '17', '0', '15'], ['8', '13', '11', '24', '30', '24', '27'], ['22', '18', '2', '29', '11', '13', '18'], ['15', '1', '29', '23', '18', '7', '0'], ['23', '27', '3', '7', '13', '14', '28'], ['6', '25', '24', '14', '20', '23', '5'], ['24', '29', '26', '22', '0', '9', '18'], ['22', '27', '22', '20', '24', '29', '21'], ['23', '13', '14', '4', '13', '1', '21'], ['25', '21', '21', '6', '28', '17', '19'], ['4', '6', '11', '10', '21', '1', '5'], ['11', '7', '22', '11', '10', '24', '15'], ['25', '11', '23', '3', '23', '8', '3'], ['22', '23', '0', '29', '15', '12', '5'], ['21', '11', '18', '22', '1', '4', '3'], ['11', '10', '3', '1', '30', '14', '22'], ['2', '16', '10', '2', '12', '9', '9'], ['2', '29', '17', '16', '13', '18', '7'], ['22', '15', '27', '19', '6', '26', '11'], ['21', '7', '18', '4', '14', '14', '2'], ['6', '30', '12', '4', '26', '22', '11'], ['21', '16', '14', '11', '28', '20', '3'], ['19', '10', '22', '18', '30', '9', '27'], ['8', '15', '17', '4', '11', '16', '6'], ['19', '17', '16', '6', '18', '18', '6'], ['2', '15', '3', '25', '27', '16', '11'], ['15', '5', '26', '24', '24', '30', '5'], ['15', '11', '16', '22', '14', '23', '28'], ['25', '6', '7', '20', '26', '18', '16'], ['5', '5', '21', '22', '24', '16', '5'], ['6', '27', '11', '8', '24', '1', '16'], ['28', '4', '1', '4', '3', '19', '24'], ['19', '3', '27', '14', '12', '24', '0'], ['6', '3', '26', '15', '15', '22', '26'], ['18', '5', '0', '14', '15', '7', '26'], ['10', '5', '12', '22', '8', '7', '11'], ['11', '1', '18', '29', '6', '9', '26'], ['3', '23', '2', '21', '29', '15', '25'], ['5', '7', '1', '6', '15', '18', '24'], ['28', '11', '0', '6', '28', '11', '26'], ['4', '28', '9', '24', '11', '13', '2'], ['6', '2', '14', '18', '20', '21', '1'], ['20', '29', '22', '21', '11', '14', '20'], ['28', '23', '14', '17', '25', '3', '18'], ['6', '27', '6', '20', '19', '5', '24'], ['25', '3', '27', '22', '7', '12', '21'], ['12', '22', '8', '7', '0', '11', '8'], ['8', '25', '1', '6', '21', '23', '0']] Traceback (most recent call last): File &quot;C:\rainfall.py&quot;, line 33, in &lt;module&gt; total = yearly(matrix) File &quot;C:\rainfall.py&quot;, line 28, in yearly total += value TypeError: unsupported operand type(s) for +=: 'int' and 'str' </code></pre>
[ { "answer_id": 74502606, "author": "pavi2410", "author_id": 7595401, "author_profile": "https://Stackoverflow.com/users/7595401", "pm_score": 0, "selected": false, "text": "map for line in lineArray:\n matrix.append(line.split(\",\"))\n for line in lineArray:\n matrix.append(list(map(int, line.split(\",\"))))\n" }, { "answer_id": 74502617, "author": "Raboro", "author_id": 18052690, "author_profile": "https://Stackoverflow.com/users/18052690", "pm_score": 2, "selected": true, "text": "total = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4174508/" ]
74,502,555
<p>Why is R complaining about an error when my function already handles errors?</p> <p>I've created a function to grab the parent element of an href attribute which invariably is &quot;&lt;a&gt;&quot;. The function has some error handling to return NA if it can't find the href attribute.</p> <p>The function works just fine in isolation, but not in combination with dplyr::mutate. I can't figure out why that is.</p> <p>Minimal reproducible example:</p> <pre><code># Create html doc html.test &lt;- &quot;&lt;a href=\&quot;hello\&quot;&lt;/a&gt;&lt;a id=\&quot;ctl00_ctl00_btnSearch\&quot; data-action=\&quot;search\&quot; class=\&quot;go\&quot; href=\&quot;javascript:__doPostBack('ctl00%24ctl00%24btnSearch','')\&quot;&gt;&lt;span&gt;GO&lt;/span&gt;&lt;i class=\&quot;fal fa-search\&quot;&gt;&lt;/i&gt;&lt;/a&gt;&quot; %&gt;% minimal_html() # Create function fun.get.node.name &lt;- function(href.target){ # treat warnings as errors options(warn=2) xpath &lt;- paste0(&quot;//a/@href[.= \'&quot;, href.target, &quot;\']/..&quot;) res &lt;- try({ node_name &lt;- html_nodes(x = html.test, xpath = xpath) %&gt;% html_name() }, silent = TRUE) if (inherits(res, &quot;try-error&quot;)) { # print warnings as they occur options(warn=1) return(NA) } else { # print warnings as they occur options(warn=1) return(node_name) } } </code></pre> <p>Now, if I apply the function to the attribute href = &quot;hello&quot;, it works fine both in isolation and when applied within dplyr::mutate:</p> <pre><code>href.target &lt;- &quot;hello&quot; fun.get.node.name(href.target) [1] &quot;a&quot; data.frame(href = href.target) %&gt;% mutate(node_name = fun.get.node.name(href.target = href)) href node_name 1 hello a </code></pre> <p>But, if I apply the same function to the attribute href = &quot;javascript:__doPostBack('ctl00%24ctl00%24btnSearch','')&quot; (which for some reason can't be found) then the function works only in isolation and NOT when applied within dplyr::mutate:</p> <pre><code>href.target &lt;- &quot;javascript:__doPostBack('ctl00%24ctl00%24btnSearch','')&quot; fun.get.node.name(href.target) [1] NA data.frame(href = href.target) %&gt;% mutate(node_name = fun.get.node.name(href.target = href)) Error: (converted from warning) Problem while computing `node_name = fun.get.node.name(href.target = href)`. ℹ Invalid predicate [1206] </code></pre> <p>Why is R complaining about an error when the function already handles errors?</p>
[ { "answer_id": 74502606, "author": "pavi2410", "author_id": 7595401, "author_profile": "https://Stackoverflow.com/users/7595401", "pm_score": 0, "selected": false, "text": "map for line in lineArray:\n matrix.append(line.split(\",\"))\n for line in lineArray:\n matrix.append(list(map(int, line.split(\",\"))))\n" }, { "answer_id": 74502617, "author": "Raboro", "author_id": 18052690, "author_profile": "https://Stackoverflow.com/users/18052690", "pm_score": 2, "selected": true, "text": "total = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1958215/" ]
74,502,572
<p>Recently I started to learn Cassandra. I needed to design the database for my web application. So, I prepared conceptual data model as well as application workflow, and currently I’m stuck on something…</p> <p>Let me provide you with some details of the issue. Well, I want to show all friends of currently logged-in user WITH PROFILE PICTURES AND THEIR FULL NAME.</p> <p>So I probably need two tables:</p> <p><a href="https://i.stack.imgur.com/sjtXo.jpg" rel="nofollow noreferrer">Fragment of Application Workflow</a></p> <pre><code>**users_by_id** - user_id PARTITION KEY - email - password - profile_image - full_name </code></pre> <pre><code>**friends_by_user_id** - user_id PARTITION KEY (whose friend is it) - friend_id (user id of the friend) etc. </code></pre> <p>And now let’s say I want to display all friends in a list, but the problem is the user expects the app to show <strong>their profile pictures and their full name (not just the friend‘s user id), so the user can recognize who is who</strong> (pretty logical, right?). So, how do I do that? I mean I could get the users id and then query the users table to finally get the full name and profile picture individually. Although, I don’t think it would be very efficient (because what if the user have hundreds of friends?!).</p> <p>What is the right way to solve this problem? Thanks in advance!</p>
[ { "answer_id": 74502606, "author": "pavi2410", "author_id": 7595401, "author_profile": "https://Stackoverflow.com/users/7595401", "pm_score": 0, "selected": false, "text": "map for line in lineArray:\n matrix.append(line.split(\",\"))\n for line in lineArray:\n matrix.append(list(map(int, line.split(\",\"))))\n" }, { "answer_id": 74502617, "author": "Raboro", "author_id": 18052690, "author_profile": "https://Stackoverflow.com/users/18052690", "pm_score": 2, "selected": true, "text": "total = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19593532/" ]
74,502,598
<p>i have an interface(IDomainService) and a (lot) like it in my app which i mark more interfaces with it(IProductionLineTitleDuplicationChecker ) like what u will see in the rest:</p> <pre><code>public interface IDomainService { } </code></pre> <pre><code>public interface IProductionLineTitleDuplicationChecker : IDomainService { /// } </code></pre> <p>and the implementation like this:</p> <pre><code>public class ProductionLineTitleDuplicationChecker : IProductionLineTitleDuplicationChecker { private readonly IProductionLineRepository _productionLineRepository; public ProductionLineTitleDuplicationChecker(IProductionLineRepository productionLineRepository) { _productionLineRepository = productionLineRepository; } public bool IsDuplicated(string productionLineTitle) { /// } } </code></pre> <p>right now im using the <strong>built-in DI-container</strong> to <strong>resolve and register</strong> the services but i want to change it and use <strong>scrutor</strong> instead</p> <p>how can i resolve and register my <strong>Services</strong> using <strong>scrutor</strong>?</p>
[ { "answer_id": 74502606, "author": "pavi2410", "author_id": 7595401, "author_profile": "https://Stackoverflow.com/users/7595401", "pm_score": 0, "selected": false, "text": "map for line in lineArray:\n matrix.append(line.split(\",\"))\n for line in lineArray:\n matrix.append(list(map(int, line.split(\",\"))))\n" }, { "answer_id": 74502617, "author": "Raboro", "author_id": 18052690, "author_profile": "https://Stackoverflow.com/users/18052690", "pm_score": 2, "selected": true, "text": "total = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17788717/" ]
74,502,599
<p>I always get the output <code>None</code> instead of <code>False</code></p> <p>My code:</p> <pre><code>def bi_search(elements: list, x) -&gt; bool: i = len(elements)/2-1 i = int(i) print(i) if i == 0: return False elif x == elements[i]: return True elif x &lt; elements[i]: e = elements[0:i + 1] bi_search(e, x) elif x &gt; elements[i]: e = elements[i+1:len(elements)] bi_search(e, x) </code></pre> <p>commands:</p> <pre><code>my_list = [1, 2, 5, 7, 8, 10, 20, 30, 41, 100] print(bi_search(my_list, 21)) </code></pre> <p>Output:</p> <pre><code>4 1 0 None </code></pre> <p>I don't get it, it even says that is i = 0 right before the statement, so why do I not get False as a result?</p>
[ { "answer_id": 74502606, "author": "pavi2410", "author_id": 7595401, "author_profile": "https://Stackoverflow.com/users/7595401", "pm_score": 0, "selected": false, "text": "map for line in lineArray:\n matrix.append(line.split(\",\"))\n for line in lineArray:\n matrix.append(list(map(int, line.split(\",\"))))\n" }, { "answer_id": 74502617, "author": "Raboro", "author_id": 18052690, "author_profile": "https://Stackoverflow.com/users/18052690", "pm_score": 2, "selected": true, "text": "total = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17345696/" ]
74,502,626
<p>I have a little doubt. How can I make the marker parameter change to marker1, marker2, marker3 depending on how many elements are in the map?</p> <p>i have this but i want that for each element of the map there is a +1 for each marker</p> <pre><code> {teams.map((team) =&gt; &lt;pointer marker={marker1} </code></pre> <p>for example, that the first element of the .map has the parameter {marker1}, the second {marker2}, the third {marker3} and so on</p>
[ { "answer_id": 74502684, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "index team teams .map() teams.map((team, index) => <pointer marker={`marker-${index + 1}`} />)\n teams.map((team, index) => (\n <pointer onClick={() => handleClick(`marker-${index + 1}`)} />\n))\n .map() key" }, { "answer_id": 74502709, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "let markersArray = [marker1 , marker2 , ...] {\n teams.map((team,index) =>\n <pointer\n marker={markersArray[index]}\n}\n" }, { "answer_id": 74502788, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": "Let your array is \n**const markersArray = [....]** \n\nIn jsx, \n markersArray.map((team, index) => {\n <pointer\n marker={markersArray[index]}\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408479/" ]
74,502,635
<p>I have this part of the df</p> <pre><code> x y d n 0 -17.7 -0.785430 0.053884 y1 1 -15.0 -3820.085000 0.085000 y4 2 -12.5 2.138833 0.143237 y3 3 -12.4 1.721205 0.251180 y3 </code></pre> <p>I want to replace all instances of <code>y3</code> for &quot;3rd&quot; and <code>y4</code> for &quot;4th&quot; in column <code>n</code></p> <p>Output:</p> <pre><code> x y d n 0 -17.7 -0.785430 0.053884 y1 1 -15.0 -3820.085000 0.085000 4th 2 -12.5 2.138833 0.143237 3rd 3 -12.4 1.721205 0.251180 3rd </code></pre>
[ { "answer_id": 74502684, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "index team teams .map() teams.map((team, index) => <pointer marker={`marker-${index + 1}`} />)\n teams.map((team, index) => (\n <pointer onClick={() => handleClick(`marker-${index + 1}`)} />\n))\n .map() key" }, { "answer_id": 74502709, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "let markersArray = [marker1 , marker2 , ...] {\n teams.map((team,index) =>\n <pointer\n marker={markersArray[index]}\n}\n" }, { "answer_id": 74502788, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": "Let your array is \n**const markersArray = [....]** \n\nIn jsx, \n markersArray.map((team, index) => {\n <pointer\n marker={markersArray[index]}\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,502,641
<p>I developed a Rest API with some logs (requests, responses, more info and errors)</p> <p>I saw that if there are simultaneous requests, logs mix and you cant follow the execution in logs because you dont know which request was used for that log line.</p> <p>Is there any execution id that can be added at the beginning of every log line so I can follow the execution of that request?.</p> <p>I'm using Log4j</p>
[ { "answer_id": 74502684, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "index team teams .map() teams.map((team, index) => <pointer marker={`marker-${index + 1}`} />)\n teams.map((team, index) => (\n <pointer onClick={() => handleClick(`marker-${index + 1}`)} />\n))\n .map() key" }, { "answer_id": 74502709, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "let markersArray = [marker1 , marker2 , ...] {\n teams.map((team,index) =>\n <pointer\n marker={markersArray[index]}\n}\n" }, { "answer_id": 74502788, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": "Let your array is \n**const markersArray = [....]** \n\nIn jsx, \n markersArray.map((team, index) => {\n <pointer\n marker={markersArray[index]}\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9833056/" ]
74,502,659
<p>I am a newbie with this. I have created a database of hundreds of proverbs and their MEANING, as well as Headwords and their definitions (MEANS).</p> <p>I would like to generate a graph of a random Proverb, but with the related words and definitions.</p> <p>My current cypher query that does return some interesting data looks as so:</p> <pre><code>MATCH p=()-[:MEANS]-(a:Headword)-[:USED_IN]-(d:Proverb)-[:MEANING]-() RETURN p, rand() as r ORDER BY r LIMIT 1 </code></pre> <p>I am getting a random Proverb, but the USED_IN and MEANS relations are also limited to 1.<br /> I am wanting to produce something like below where there is a single Proverb and its MEANING (Orange), but there are relations to the words USED_IN (yellow), and the defintions (MEANS) of those words. How can I attain that?</p> <p>Just an FYI for the image below I bumped up the LIMIT in the cypher query to 3. But this may also produce 3 Proverbs etc.</p> <p><a href="https://i.stack.imgur.com/A2VCo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A2VCo.png" alt="Desired graph sample" /></a></p>
[ { "answer_id": 74502684, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "index team teams .map() teams.map((team, index) => <pointer marker={`marker-${index + 1}`} />)\n teams.map((team, index) => (\n <pointer onClick={() => handleClick(`marker-${index + 1}`)} />\n))\n .map() key" }, { "answer_id": 74502709, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "let markersArray = [marker1 , marker2 , ...] {\n teams.map((team,index) =>\n <pointer\n marker={markersArray[index]}\n}\n" }, { "answer_id": 74502788, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": "Let your array is \n**const markersArray = [....]** \n\nIn jsx, \n markersArray.map((team, index) => {\n <pointer\n marker={markersArray[index]}\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3358585/" ]
74,502,685
<p>I have to create a database with a single row for every day in the interval between the two dates (date_in - date_out). I have to use R.</p> <p>How can I do this?</p> <p>My data:</p> <pre><code> id date_in date_out days 1 1 13May2022 0:00:00 03Jul2022 0:00:00 51 2 3 10Nov2020 0:00:00 15Nov2020 0:00:00 5 3 4 25Feb2020 0:00:00 05Apr2020 0:00:00 40 </code></pre> <pre><code>&gt; dput(df) structure(list(id = c(1L, 3L, 4L), date_in = c(&quot;13May2022 0:00:00&quot;, &quot;10Nov2020 0:00:00&quot;, &quot;25Feb2020 0:00:00&quot;), date_out = c(&quot;03Jul2022 0:00:00&quot;, &quot;15Nov2020 0:00:00&quot;, &quot;05Apr2020 0:00:00&quot;), days = c(51, 5, 40 )), class = &quot;data.frame&quot;, row.names = c(NA, -3L)) </code></pre>
[ { "answer_id": 74502684, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "index team teams .map() teams.map((team, index) => <pointer marker={`marker-${index + 1}`} />)\n teams.map((team, index) => (\n <pointer onClick={() => handleClick(`marker-${index + 1}`)} />\n))\n .map() key" }, { "answer_id": 74502709, "author": "Tarmah", "author_id": 6894272, "author_profile": "https://Stackoverflow.com/users/6894272", "pm_score": 1, "selected": false, "text": "let markersArray = [marker1 , marker2 , ...] {\n teams.map((team,index) =>\n <pointer\n marker={markersArray[index]}\n}\n" }, { "answer_id": 74502788, "author": "Ahad_bukhari", "author_id": 12485183, "author_profile": "https://Stackoverflow.com/users/12485183", "pm_score": 0, "selected": false, "text": "Let your array is \n**const markersArray = [....]** \n\nIn jsx, \n markersArray.map((team, index) => {\n <pointer\n marker={markersArray[index]}\n})\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9390952/" ]
74,502,700
<p>Imagine a parent class which has a mangled attribute, and a child class:</p> <pre class="lang-py prettyprint-override"><code>class Foo: def __init__(self): self.__is_init = False async def init(self): # Some custom logic here, not important self.__is_init = True class Bar(Foo): ... # Create class instance. bar = Bar() # How access `__is_init` of the parent class from the child instance? </code></pre> <p>How can I get a <code>__is_init</code> value from a parent (<code>Foo</code>) class?</p> <hr /> <p>Obviously, I can <code>bar._Foo__is_init</code> in this example, but the problem is that class name is dynamic and I need a general purpose solution that will work with any passed class name.</p>
[ { "answer_id": 74502718, "author": "Dmitriy Neledva", "author_id": 16786350, "author_profile": "https://Stackoverflow.com/users/16786350", "pm_score": 0, "selected": false, "text": "class Foo:\n\n def __init__(self):\n self.__is_init = False\n\n async def init(self):\n self.__is_init = True\n\nclass Bar(Foo):\n\n def getattr_mangled(self, attr:str):\n for i in self.__dict__.keys():\n if attr in i:\n return getattr(self,i)\n # return self.__dict__[i] #or like this\n\n\n\nbar = Bar()\nprint(bar.getattr_mangled('__is_init')) #False\n __init__ Foo super().__init__() Foo _PARENT_CLASS_NAME__attrname" }, { "answer_id": 74502993, "author": "Nairum", "author_id": 9608133, "author_profile": "https://Stackoverflow.com/users/9608133", "pm_score": 1, "selected": false, "text": "from contextlib import suppress\n\nclass MangledAttributeError(Exception):\n ...\n\ndef getattr_mangled(object_: object, name: str) -> str:\n for cls_ in getattr(object_, \"__mro__\", None) or object_.__class__.__mro__:\n with suppress(AttributeError):\n return getattr(object_, f\"_{cls_.__name__}{name}\")\n raise MangledAttributeError(f\"{type(object_).__name__} object has no attribute '{name}'\")\n class Foo:\n\n def __init__(self):\n self.__is_init = False\n\n async def init(self):\n self.__is_init = True\n\nclass Bar(Foo):\n\n def __init__(self):\n super().__init__()\n\nbar = Bar()\nis_init = getattr_mangled(bar, \"__is_init\")\nprint(f\"is_init: {is_init}\") # Will print `False` which is a correct value in this example\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9608133/" ]
74,502,727
<p>I was able to shuffle through my deck of cards (array of objects), but now I'm trying to pull out/remove the first 25 cards(objects) and place them into their own stored array. However, my code is returning undefined when I try to reference the new deck cards var player1Deck = shuffledCards.splice(25); is returning as not a function. Is there anyway to remove the first 25 cards/object from this new shuffled array that I created?</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> //Deck with ranks var starterDeck = [ {"img": '2_of_clubs.png',"rank": 1},{"img": '3_of_clubs.png',"rank": 2},{"img": '4_of_clubs.png',"rank": 3},{"img": '5_of_clubs.png',"rank": 4},{"img": '6_of_clubs.png',"rank": 5},{"img": '7_of_clubs.png',"rank": 6},{"img": '8_of_clubs.png',"rank": 7},{"img": '9_of_clubs.png',"rank": 8},{"img": '10_of_clubs.png',"rank": 9},{"img": 'jack_of_clubs.png',"rank": 10},{"img": 'queen_of_clubs.png',"rank": 11},{"img": 'king_of_clubs.png',"rank": 12},{"img": 'ace_of_clubs.png',"rank": 13}, {"img": '2_of_diamonds.png',"rank": 1},{"img": '3_of_diamonds.png',"rank": 2},{"img": '4_of_diamonds.png',"rank": 3},{"img": '5_of_diamonds.png',"rank": 4},{"img": '6_of_diamonds.png',"rank": 5},{"img": '7_of_diamonds.png',"rank": 6},{"img": '8_of_diamonds.png',"rank": 7},{"img": '9_of_diamonds.png',"rank": 8},{"img": '10_of_diamonds.png',"rank": 9},{"img": 'jack_of_diamonds.png',"rank": 10},{"img": 'queen_of_diamonds.png',"rank": 11},{"img": 'king_of_diamonds.png',"rank": 12},{"img": 'ace_of_diamonds.png',"rank": 13}, {"img": '2_of_hearts.png',"rank": 1},{"img": '3_of_hearts.png',"rank": 2},{"img": '4_of_hearts.png',"rank": 3},{"img": '5_of_hearts.png',"rank": 4},{"img": '6_of_hearts.png',"rank": 5},{"img": '7_of_hearts.png',"rank": 6},{"img": '8_of_hearts.png',"rank": 7},{"img": '9_of_hearts.png',"rank": 8},{"img": '10_of_hearts.png',"rank": 9},{"img": 'jack_of_hearts.png',"rank": 10},{"img": 'queen_of_hearts.png',"rank": 11},{"img": 'king_of_hearts.png',"rank": 12},{"img": 'ace_of_hearts.png',"rank": 13}, {"img": '2_of_spades.png',"rank": 1},{"img": '3_of_spades.png',"rank": 2},{"img": '4_of_spades.png',"rank": 3},{"img": '5_of_spades.png',"rank": 4},{"img": '6_of_spades.png',"rank": 5},{"img": '7_of_spades.png',"rank": 6},{"img": '8_of_spades.png',"rank": 7},{"img": '9_of_spades.png',"rank": 8},{"img": '10_of_spades.png',"rank": 9},{"img": 'jack_of_spades.png',"rank": 10},{"img": 'queen_of_spades.png',"rank": 11},{"img": 'king_of_spades.png',"rank": 12},{"img": 'ace_of_spades.png',"rank": 13}, ] for(var i=0;i&lt;52; i++) { // We are taking our tempCard and placing it in the random position (randomIndex) var shuffledCards = starterDeck[i]; var randomIndex = Math.floor(Math.random() * 52); starterDeck[i] = starterDeck[randomIndex] starterDeck[randomIndex] = shuffledCards; // let newDeck = [shuffledCards] console.log(shuffledCards) var player1Deck = shuffledCards.splice(25); console.log(player1Deck) }</code></pre> </div> </div> </p>
[ { "answer_id": 74502718, "author": "Dmitriy Neledva", "author_id": 16786350, "author_profile": "https://Stackoverflow.com/users/16786350", "pm_score": 0, "selected": false, "text": "class Foo:\n\n def __init__(self):\n self.__is_init = False\n\n async def init(self):\n self.__is_init = True\n\nclass Bar(Foo):\n\n def getattr_mangled(self, attr:str):\n for i in self.__dict__.keys():\n if attr in i:\n return getattr(self,i)\n # return self.__dict__[i] #or like this\n\n\n\nbar = Bar()\nprint(bar.getattr_mangled('__is_init')) #False\n __init__ Foo super().__init__() Foo _PARENT_CLASS_NAME__attrname" }, { "answer_id": 74502993, "author": "Nairum", "author_id": 9608133, "author_profile": "https://Stackoverflow.com/users/9608133", "pm_score": 1, "selected": false, "text": "from contextlib import suppress\n\nclass MangledAttributeError(Exception):\n ...\n\ndef getattr_mangled(object_: object, name: str) -> str:\n for cls_ in getattr(object_, \"__mro__\", None) or object_.__class__.__mro__:\n with suppress(AttributeError):\n return getattr(object_, f\"_{cls_.__name__}{name}\")\n raise MangledAttributeError(f\"{type(object_).__name__} object has no attribute '{name}'\")\n class Foo:\n\n def __init__(self):\n self.__is_init = False\n\n async def init(self):\n self.__is_init = True\n\nclass Bar(Foo):\n\n def __init__(self):\n super().__init__()\n\nbar = Bar()\nis_init = getattr_mangled(bar, \"__is_init\")\nprint(f\"is_init: {is_init}\") # Will print `False` which is a correct value in this example\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11996252/" ]
74,502,731
<p>My aim is to create my own analogue of <code>std::basic_string</code> but with some additional conditions. I want my <code>AnyString&lt;CharType, Traits&gt;</code> to be convertible from <code>std::basic_string&lt;CharType, AnyOtherTraits, AnyAlloc&gt;</code> but I want to disable this constructor for some CharType such that <code>basic_string&lt;CharType&gt;</code> does not exist (compile).</p> <p>I tried to do something like that:</p> <pre><code> template&lt;typename OtherTraits, typename Alloc, typename = std::enable_if_t&lt;!std::is_array_v&lt;char_type&gt; &amp;&amp; std::is_trivial_v&lt;char_type&gt; &amp;&amp; std::is_standard_layout_v&lt;char_type&gt;&gt;&gt; AnyString(const std::basic_string&lt;char_type, OtherTraits, Alloc&gt;&amp;); </code></pre> <p>And I have <code>ColouredChar</code>, which does not meet the conditions listed inside <code>enable_if_t</code>.</p> <p>Now, when I'm trying to call the disabled constructor :</p> <pre><code>std::basic_string&lt;ColouredChar&gt; de(&quot;string&quot;_purple); ColouredString d(de); </code></pre> <p>I do not only get the compile errors from <code>basic_string</code> but also very strange one, telling me that completely different PRIVATE constructor constructor cannot convert its parameter from <code>basic_string</code>.</p> <p>Is there any way to make these compile errors more readable? Or at least explain whether there's anything here to worry about.</p>
[ { "answer_id": 74502812, "author": "Pepijn Kramer", "author_id": 16649550, "author_profile": "https://Stackoverflow.com/users/16649550", "pm_score": 3, "selected": true, "text": "#include <type_traits>\n#include <string>\n\n// declare your own concept\ntemplate<typename type_t>\nconcept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept\n \nclass ColouredString\n{\npublic:\n // then you can limit your constructor to types satisfying that concept\n ColouredString(const my_concept auto& /*arg*/)\n {\n }\n\n ~ColouredString() = default;\n};\n\n\nint main()\n{\n // ColouredString str{ 1 };\n ColouredString str{ \"hello world!\" };\n\n return 0;\n}\n" }, { "answer_id": 74503750, "author": "apple apple", "author_id": 5980430, "author_profile": "https://Stackoverflow.com/users/5980430", "pm_score": 1, "selected": false, "text": "class ColouredString{\npublic:\n template<typename T>\n requires (std::is_convertible_v<T, std::string>)\n ColouredString(const T&){}\n};\n std::convertable_to class ColouredString{\npublic:\n ColouredString(const std::convertible_to<std::string> auto&){}\n};\n string ColouredString std::basic_string<ColouredChar> de(\"string\"_purple); // it already fail here\nColouredString d(de); \n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74502731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20492391/" ]